/* Minification failed. Returning unminified contents.
(10044,74-75): run-time error JS1195: Expected expression: >
(10044,104-105): run-time error JS1004: Expected ';': )
(10063,17-21): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(10065,17-18): run-time error JS1002: Syntax error: }
(10067,41-42): run-time error JS1004: Expected ';': {
(10069,14-15): run-time error JS1195: Expected expression: )
(10072,50-51): run-time error JS1195: Expected expression: )
(10072,52-53): run-time error JS1004: Expected ';': {
(10481,5-6): run-time error JS1002: Syntax error: }
 */
/// <reference path="partials/index.html" />
(function () { 
 
    angular.module('app', ['ui.router', 'ngMaterial', 'ngAnimate', 'ngMessages', 'ui.bootstrap', 'angular-loading-bar', 'LocalStorageModule', 'toaster', 'ngSanitize', 'luegg.directives'])
    //App.config(function (FacebookProvider) {
    //    FacebookProvider.init('196219878131656'); //Here mention Developer facebook APPID  
    //})
        //.run(['$rootScope', '$window', 'srvAuth', function ($rootScope, $window, srvAuth) {

        //    $rootScope.user = {};

            //$window.fbAsyncInit = function () {
            //    FB.init({
            //        appId: '{196219878131656}',
            //        status: true,
            //        cookie: true,
            //        xfbml: true,
            //        version: 'v2.4'
            //    });
            //};

 

        //    (function (d) {

              

        //        var js,
        //            id = 'facebook-jssdk',
        //            ref = d.getElementsByTagName('script')[0];

        //        if (d.getElementById(id)) {
        //            return;
        //        }

        //        js = d.createElement('script');
        //        js.id = id;
        //        js.async = true;
        //        js.src = "//connect.facebook.net/en_US/sdk.js";

        //        ref.parentNode.insertBefore(js, ref);

        //    }(document));
        //}])


        .factory('facebookService', function ($q) {
            return {
                getMyLastName: function () {
                    var deferred = $q.defer();
                    FB.api('/me', {
                        fields: 'last_name'
                    }, function (response) {
                        if (!response || response.error) {
                            deferred.reject('Error occured');
                        } else {
                            deferred.resolve(response);
                        }
                    });
                    return deferred.promise;
                }
            }
        })

        .config(config);



    //#endregion

    //#region ams main Injector
    config.$inject = ['$urlRouterProvider', '$stateProvider', '$httpProvider'];
    //#endregion
   

    function config($urlRouterProvider, $stateProvider, $httpProvider) {
        $httpProvider.interceptors.push('authInterceptorService');
      //  $urlRouterProvider.when('/Home', '/Home/ProjectEntryForm');
        $urlRouterProvider.otherwise('/index');
        //$locationProvider.html5Mode({
        //    enabled: true,
        //    requireBase: false
            
        //});
       
        $stateProvider
            .state('Home', {
                url: '/Home',
                templateUrl: 'SPA/partials/Home.html',
                controller: 'indexController'
            })

            .state('index', {
                url: '/index',
                templateUrl: 'SPA/partials/index.html',
                params: { 'productID': null },
                controller: 'indexController',

            })



             //.state('Header_partial', {
             //    url: '/index',
             //    templateUrl: 'SPA/partials/Home/Header_partial.html',
             //    params: { 'productID': null },
             //    controller: 'indexController',

             //})



            .state('RelatedProduct', {
                url: '/RelatedProduct',
                templateUrl: 'SPA/partials/Home/RelatedProduct.html',
                params: { 'productID': null },
                controller: 'indexController',

            })


            .state('payment_detail', {
                url: '/payment_detail',
                templateUrl: 'SPA/partials/Home/payment_detail.html',
                params: { 'productID': null },
                controller: 'PaymentController',

            })

        
            .state('managesubscription', {
                url: '/managesubscription',
                templateUrl: 'SPA/partials/Home/managesubscription.html',
                params: { 'productID': null },
                controller: 'PaymentController',

            })
          
		 .state('ResetPassword', {
             url: '/ResetPassword?resetcode',
                templateUrl: 'SPA/partials/Home/ResetPassword.html',

                controller: 'ProfileController',

            })

            .state('MyTrades', {
                url: '/MyTrades',
                templateUrl: 'SPA/partials/Home/MyTrades.html',

                controller: 'ProfileController',

            })



             .state('UserProfile', {
                 url: '/UserProfile',
                 templateUrl: 'SPA/partials/Home/UserProfile.html',
               
                 controller: 'ProfileController',

             })

               .state('PrivacyPolicy', {
                   url: '/PrivacyPolicy',
                   templateUrl: 'SPA/partials/Home/Privacy_policy.html',
                   params: { 'productID': null },
                   controller: 'indexController',

               })

            .state('Privacy-Policy', {
                url: '/Privacy-Policy',
                templateUrl: 'SPA/partials/Home/PrivacyPolicy.html',
                params: { 'productID': null },
                controller: 'indexController',

            })

             .state('TermsofService', {
                 url: '/TermsofService',
                 templateUrl: 'SPA/partials/Home/Terms_of_use.html',
                 params: { 'productID': null },
                 controller: 'indexController',

             })

            .state('Terms-of-Service', {
                 url: '/Terms-of-Service',
                 templateUrl: 'SPA/partials/Home/Termsofuse.html',
                 params: { 'productID': null },
                 controller: 'indexController',

            })

            .state('Contact-Us', {
                url: '/Contact-Us',
                templateUrl: 'SPA/partials/Home/ContactUs.html',
                params: { 'productID': null },
                controller: 'indexController',

            })
              .state('FavouriteTrade', {
                  url: '/FavouriteTrade',
                  templateUrl: 'SPA/partials/Home/FavouriteTrade.html',
                  params: { 'productID': null },
                  controller: 'ProfileController',

              })

               .state('ShowUserDetails', {
                   url: '/ShowUserDetails',
                   templateUrl: 'SPA/partials/Home/ShowUserDetails.html',
                   params: { 'productID': null },
                   controller: 'ProfileController',

               })

             .state('filterpage', {
                 url: '/filterpage',
                 templateUrl: 'SPA/partials/Home/filterpage.html',

                 controller: 'SearchController',

            })

        
            .state('filterpage_collegetrades', {
                url: '/filterpage_collegetrades',
                templateUrl: 'SPA/partials/Home/filterpage_collegetrades.html',

                controller: 'SearchController',

            })

            .state('filterpage_needs', {
                url: '/filterpage_needs',
                templateUrl: 'SPA/partials/Home/filterpage_needs.html',

                controller: 'SearchController',

            })



              .state('Category_filterpage', {
                  url: '/Category_filterpage',
                  templateUrl: 'SPA/partials/Home/Category_filterpage.html',

                  controller: 'SearchController',

              })



              .state('edit_profile', {
                  url: '/edit_profile',
                  templateUrl: 'SPA/partials/Home/edit_profile.html',
                  params: { 'productID': null },
                  controller: 'ProfileController',

              })

        
               .state('my_needs', {
                   url: '/my_needs',
                   templateUrl: 'SPA/partials/Home/my_needs.html',
                   params: { 'productID': null },
                   controller: 'ProfileController',

               })
        
               .state('edit_charity', {
                   url: '/edit_charity',
                   templateUrl: 'SPA/partials/Home/edit_charity.html',
                   params: { 'productID': null },
                   controller: 'tradeController',

               })
        
        
        
             .state('CharityNeeds', {
                 url: '/CharityNeeds',
                 templateUrl: 'SPA/partials/Home/CharityNeeds.html',
                 params: { 'productID': null },
                 controller: 'CharityController',

             })
          

        
              .state('select_category', {
                  url: '/select_category',
                  templateUrl: 'SPA/partials/Home/select_category.html',
                  params: { 'productID': null },
                  controller: 'ProfileController',

              })
        

              .state('add_trade_details', {
                  url: '/add_trade_details',
                  templateUrl: 'SPA/partials/Home/add_trade_details.html',
                  params: { 'productID': null },
                  controller: 'tradeController',

              })

              .state('tradeUploaded', {
                  url: '/tradeUploaded',
                  templateUrl: 'SPA/partials/Home/tradeUploaded.html',
                  params: { 'productID': null },
                  controller: 'indexController',

              })

             .state('charity_list', {
                 url: '/charity_list',
                 templateUrl: 'SPA/partials/Home/charity_list.html',
                 params: { 'productID': null },
                 controller: 'indexController',

             })

             .state('Registerpage', {
                 url: '/Registerpage',
                 templateUrl: 'SPA/partials/Home/Registerpage_new.html',
                 params: { 'productID': null },
                 controller: 'indexController',

             })
              .state('testing', {
                  url: '/testing',
                  templateUrl: 'SPA/partials/Home/testing.html',
                  params: { 'productID': null },
                  controller: 'indexController',

            })

            .state('UploadImages', {
                url: '/UploadImages',
                templateUrl: 'SPA/partials/Home/UploadImages.html',
                params: { 'productID': null },
                controller: 'tradeController',

            })


            .state('AddTrade', {
                url: '/AddTrade',
                templateUrl: 'SPA/partials/Home/AddTrade.html',
                params: { 'productID': null },
                controller: 'tradeController',

            })

              .state('edit_Trade', {
                  url: '/edit_Trade',
                  templateUrl: 'SPA/partials/Home/edit_Trade.html',
                  params: { 'productID': null },
                  controller: 'tradeController',

              })

           
        .state('Need', {
            url: '/Need?tradeId&categoryId',
            templateUrl: 'SPA/partials/Home/Need.html',
            params: { 'productID': null },
            controller: 'tradeController',

        })
        
             .state('All_needs', {
                 url: '/All_needs',
                 templateUrl: 'SPA/partials/Home/All_needs.html',
                 params: { 'productID': null },
                 controller: 'CharityController',

             })
       


          .state('Trade', {
              url:'/Trade?tradeId&categoryId',
              templateUrl: 'SPA/partials/Home/Trade.html',
              controller: 'tradeController',
            })


             .state('single', {
                 url: '/single',
                 templateUrl: 'SPA/partials/Home/single.html', 
                 params: { 'productID': null },
                 controller: 'tradeController',

             })
        
          .state('trade_list', {
              url: '/trade_list',
              templateUrl: 'SPA/partials/Home/trade_list.html',
              params: { 'productID': null },
              controller: 'tradeController',

          })
             .state('CollegeTrades', {
                 url: '/CollegeTrades',
                 templateUrl: 'SPA/partials/Home/CollegeTrades.html',
                 params: { 'productID': null },
                 controller: 'tradeController',

             })

            .state('chat', {
                url: '/chat',
                templateUrl: 'SPA/partials/Home/chat.html',
                params: { 'productID': null },
                controller: 'chatController',

            })
           

    };

    run.$inject = ['authService'];

    function run(authService) {
        authService.fillAuthData();
    };
}());

;
/// <reference path="../partials/index.html" />
var srcData1 = "";
var SelectedLongitude = 0;
var SelectedLatitude = 0;
var lat = 0;
var lan = 0;
var mysrclat = 0;
var mysrclong = 0;
var Uid = 0;
var email = "";
var pagenumber = 1;
//function loadImageFileAsURL() {

function statusChangeCallback(response) {
    // Called with the results from FB.getLoginStatus().
    //debugger;
    console.log('statusChangeCallback');
    console.log(response);                   // The current login status of the person.
    if (response.status === 'connected') {   // Logged into your webpage and Facebook.
        testAPI();
        getFBData();

    } else {

        FB.login(function (response) {
            if (response.authResponse) {
                console.log('Welcome!  Fetching your information.... ');

                if (response.status === 'connected') {
                    testAPI();
                    getFBData();

                }

            } else {
                console.log('User cancelled login or did not fully authorize.');
            }
        });
    }


}






window.fbAsyncInit = function () {
    FB.init({
        appId: '196219878131656',
        status: true,
        cookie: true,                     // Enable cookies to allow the server to access the session.
        xfbml: true,                     // Parse social plugins on this webpage.
        version: 'v6.0'           // Use this Graph API version for this call.
    });


    //FB.getLoginStatus(function (response) {   // Called after the JS SDK has been initialized.
    //    statusChangeCallback(response);        // Returns the login status.
    //});
};

(function (d, s, id) {                      // Load the SDK asynchronously
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

//function checkLoginState() {               // Called when a person is finished with the Login Button.
//    FB.getLoginStatus(function (response) {   // See the onlogin handler
//        statusChangeCallback(response);
//    });
//}

function checkLoginState() {

    //debugger;

    FB.getLoginStatus(function (response) {
        statusChangeCallback(response);
    });

}


function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.

    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', { fields: "id, first_name, last_name, email, picture" }, function (response) {
        console.log(response);
        var url = response.picture.data.url;
        convertFileToDataURLviaFileReader(url);
        console.log('Successful login for: ' + response.first_name + response.id);
        //var fname = response.first_name;
        //var lname = response.last_name;

    });

    // alert("Login Successfull");

}
function convertFileToDataURLviaFileReader(url) {
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        var reader = new FileReader();
        reader.onloadend = function () {
            var Profile = reader.result;
            // $scope.GetFBIamge = Profile.replace(/data:image\/jpeg;base64,/g, '');
            var GetFBIamge = Profile.replace(/data:image\/jpeg;base64,/g, '');
            //$window.localStorage.setItem('ProfileImage', JSON.stringify($scope.GetFBIamge));
            window.localStorage.setItem('ProfileImage', GetFBIamge);
            //window.localStorage.setItem('ProfileImage', Profile);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}

var fname = "";
var lname = "";
var fbemail = "";
var fbpic = "";
var fbid = 0;

function getFBData() {

    FB.api('/me', { fields: "id, first_name, last_name, email, picture" }, function (data) {

        //debugger;
        console.log("datafbbb:" + JSON.stringify(data));
        fname: data.first_name;
        lname: data.last_name;
        fbemail: data.email;
        fbpic: data.picture;
        fbid: data.id;
        fb(data);

    })

};

function facebooklogout() {
    //debugger;
    FB.logout(function (response) {

        console.log(response);
        FB.Auth.setAuthResponse(null, 'unknown');
    });
}


var details = {
    FacebookId: null,
    App_token: "",
    One_signal_key: "",
    Device_id: "",
    Device_type: "",

}

function fb(data) {

    //debugger;
    details.FacebookId = data.id;
    //details.FacebookId = fname;
    //details.FacebookId = lname;

    console.log("d:" + JSON.stringify(details));
    var x = angular.element(document.getElementById('myModal')).scope();
    x.loginFb(data);
    //$.ajax({
    //    type: 'POST',
    //    url: 'api/Login/LoginWithFb',
    //    data: details,
    //    dataType: "json",
    //    success: function (data) {
    //          alert("success");


    //        //console.log("logindata: " + JSON.stringify(data.Result.UserID));

    //        //window.localStorage.setItem('UserId', data.Result.UserID);
    //        //window.localStorage.setItem('UserName', data.Result.UserName);
    //        //window.localStorage.setItem('FirstName', data.Result.FirstName);
    //        //window.localStorage.setItem('UserTypeID', data.Result.UserTypeId);
    //        //window.localStorage.setItem('UserImage', data.Result.UserImage);

    //        //$("#myModal").hide();
    //        //if (data.Result.UserTypeId == 1) {
    //        //    swal({
    //        //        title: "Success!",
    //        //        text: "Login Successfull!",
    //        //        icon: "success",
    //        //        button: "Ok!",
    //        //    });
    //        //    $state.go("index", {}, { reload: true });
    //        //}
    //        //else {
    //        //    swal({
    //        //        title: "Success!",
    //        //        text: "Thank you dear for logging to manage your Charity -" + data.Result.UserName,
    //        //        icon: "success",
    //        //        button: "Ok!",
    //        //    });
    //        //    $state.go("my_needs", {}, { reload: true });
    //        //}

    //        //$("body").css("padding", "0px");
    //    },
    //    error: function (data) {
    //        alert("error");

    //    }

    //});
    //registerfb(data);
}
var Registermodel_fb = {
    FirstName: "",
    LastName: "",
    Email: "",
    PhoneNumber: "",
    UserName: "",
    Password: "",
    StateId: "",
    CityId: "",
    CountryId: "",
    UserTypeId: 1,
    Zipcode: "",
    MiddleName: "",
    Latitude: "",
    Longitude: "",
    IpAddress: "",
    IsActive: "",
    IsDeleted: "",
    IsVerified: "",
    CreatedBy: "",
    CreatedDateTime: "",
    AddressLine1: "",
    AddressLine2: "",
    App_Token: "",
    Device_Id: "",
    Device_Type: "",
    Gender: "",
    UserImage: "",
    ActivationCode: "",
    Firebase_token: "",
    One_signal_key: "",
    CollegeId: null,
    FacebookId: null,
}
function registerfb(data) {

    console.log("registerdata: " + JSON.stringify(data));
    var url = data.picture.data.url;
    convertFileToDataURLviaFileReader(url);
    Registermodel_fb.FirstName = data.first_name;
    Registermodel_fb.LastName = data.last_name;
    Registermodel_fb.Email = data.email;
    Registermodel_fb.UserImage = window.localStorage.getItem('ProfileImage');
    Registermodel_fb.FacebookId = data.id;
    console.log("re:" + JSON.stringify(Registermodel_fb));
    $.ajax({
        type: 'POST',
        url: 'api/Users/RegisterUser',
        data: Registermodel_fb,
        dataType: "json",
        success: function (data) {
            alert("Registered");

            details.FacebookId = data.id;
            //details.FacebookId = fname;
            //details.FacebookId = lname;
            details.UserName = data.email;

            $.ajax({
                type: 'POST',
                url: 'api/Login/LoginWithFb',
                data: details,
                dataType: "json",
                success: function (data) {

                    alert("success");

                },
                error: function (data) {
                    alert("error");
                    //registerfb(data);
                }
            });
        },
        error: function (data) {
            // alert("error");
            // registerfb(data);

        }
    });

}


function onloadFunction() {

    gapi.client.setApiKey('AIzaSyADDoHBLWN8N3qaj9wnZO1DM8rt8DmJO0w');
    gapi.client.load('plus', 'v1', function () { })
}

function load() {
    window.location.reload();
}

function loadImageFileAsURL1() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
    var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];

        var fileReader = new FileReader();

        fileReader.onload = function (fileLoadedEvent) {
            //$srcData.push(fileLoadedEvent.target.result);
            // <--- data: base64
            srcData1 = fileLoadedEvent.target.result;
            //   var divTest = document.getElementById("imgTest");
            //  var newImage = document.createElement('img');
            //newImage.src = srcData;
        }

        fileReader.readAsDataURL(fileToLoad);
    }
}

function initMap() {
    //debugger;
    var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 21.146633, lng: 79.088860 },
        zoom: 13
    });
    var card = document.getElementById('pac-card');
    var input = document.getElementById('pac-input');
    var types = document.getElementById('type-selector');
    var strictBounds = document.getElementById('strict-bounds-selector');

    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);

    var autocomplete = new google.maps.places.Autocomplete(input);

    // Bind the map's bounds (viewport) property to the autocomplete object,
    // so that the autocomplete requests use the current map bounds for the
    // bounds option in the request.
    //autocomplete.bindTo('bounds', map);

    // Set the data fields to return when the user selects a place.
    //autocomplete.setFields(
    //    ['address_components', 'geometry', 'icon', 'name']);

    //var infowindow = new google.maps.InfoWindow();
    //var infowindowContent = document.getElementById('infowindow-content');
    //infowindow.setContent(infowindowContent);
    //var marker = new google.maps.Marker({
    //    map: map,
    //    anchorPoint: new google.maps.Point(0, -29)
    //});

    autocomplete.addListener('place_changed', function () {
        //infowindow.close();
        // marker.setVisible(false);
        var place = autocomplete.getPlace();
        SelectedLongitude = place.geometry.location.lng();
        SelectedLatitude = place.geometry.location.lat();

        //if (!place.geometry) {
        //    // User entered the name of a Place that was not suggested and
        //    // pressed the Enter key, or the Place Details request failed.
        //    window.alert("No details available for input: '" + place.name + "'");
        //    return;
        //}

        //// If the place has a geometry, then present it on a map.
        //if (place.geometry.viewport) {
        //    map.fitBounds(place.geometry.viewport);
        //} else {
        //    map.setCenter(place.geometry.location);
        //    map.setZoom(17);  // Why 17? Because it looks good.
        //}
        //marker.setPosition(place.geometry.location);
        //marker.setVisible(true);

        //var address = '';
        //if (place.address_components) {
        //    address = [
        //        (place.address_components[0] && place.address_components[0].short_name || ''),
        //        (place.address_components[1] && place.address_components[1].short_name || ''),
        //        (place.address_components[2] && place.address_components[2].short_name || '')
        //    ].join(' ');
        //}

        //infowindowContent.children['place-icon'].src = place.icon;
        //infowindowContent.children['place-name'].textContent = place.name;
        //infowindowContent.children['place-address'].textContent = address;
        //infowindow.open(map, marker);
    });
}


(function () {
    'use strict';
    var App = angular.module('app').controller('indexController', ['$http', '$scope', '$sce', '$state', '$stateParams', '$location', 'authService', 'salewithusService', 'tradeService', '$window', 'toaster', '$timeout', function ($http, $scope, $sce, $state, $location, $stateParams, authService, salewithusService, tradeService, $window, toaster, $timeout) {

        //App.config(function (FacebookProvider) {
        //    FacebookProvider.init('196219878131656'); //Here mention Developer facebook APPID  
        //})

        //var url = 'web.worldoftrade.com';
        //if (url.indexOf('//') < 0) {
        //    url = 'https://' + url;

        //    console.log(url);
        //}

        $(".modal-backdrop").hide();


        $(".modal-open").css("overflow", "scroll");

        // $("body").css("padding", "0px");

        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;

        $scope.showMsgs = false;
        $scope.EnterKeyPress = function (event, isbnnumber) {
            if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
                $scope.searchbyisbn(isbnnumber);
        }


        $scope.CheckLogin = function () {
            var UserId = window.localStorage.getItem('UserId');
            var Username = window.localStorage.getItem('userName');
            if (UserId == null) {


                $state.go("index");
                $("#myModal").show();

            }
            else {
            }
        }
        $scope.data = "";
        $scope.check_mail = function () {
            $scope.data = window.localStorage.getItem("UserName");
            if ($scope.data != null || $scope.data != undefined) {
                if ($scope.data.includes(".edu")) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }

        $scope.ShowSpinnerStatus = true;

        $scope.ShowSpinner = function () {
            $scope.ShowSpinnerStatus = true;
        };
        $scope.HideSpinner = function () {
            $scope.ShowSpinnerStatus = false;
        };

        $scope.logout = function () {

            var facebookid = window.localStorage.getItem('FacebookId');
            //debugger;
            if (facebookid != null) {
                facebooklogout();
            }

            window.localStorage.removeItem('UserId');
            window.localStorage.removeItem('userName');
            window.localStorage.removeItem('UserImage');
            window.localStorage.removeItem('UserIdfb');
            window.localStorage.removeItem('UserTypeIDfb');
            window.localStorage.removeItem('FacebookId');


            swal({
                title: "Success!",
                text: "Log Out Successfull!",
                icon: "success",
                button: "Ok!",
            });
            $state.go("index");
            $("#profile").hide();
            $("#login").show();
        };

        $scope.charityimage = [];
        $scope.userid = "";

        $scope.setusername_model = {
            UserId: ""
        }
        $scope.u_img = "";
        $scope.userimage = "";
        $scope.updated_img = "";
        $scope.editpage = "";
        $scope.setUsername = function () {
          
            $(".Username").text(window.localStorage.getItem('UserName'));
          
          
            $scope.editpage = tradeService.getpagenameedit();
            if ($scope.editpage == "editprofile") {
                $scope.GetUserData();
                $scope.u_img = tradeService.getuserimage();
                window.localStorage.setItem('UserImage', $scope.u_img);
                $scope.u_img = window.localStorage.getItem('UserImage');
            }
            else {
                $scope.u_img = window.localStorage.getItem('UserImage');
            }
        

            //$scope.userimage = $sce.trustAsHtml('<img src="' + $scope.u_img + '" class="img-fluid profile_border size" style="margin-top: 1px !important;">');
            //debugger;
            var facebookid = window.localStorage.getItem("FacebookId");
            //$scope.userimage = $sce.trustAsHtml('<img src="' + $scope.u_img + '" class="img-fluid profile_border size" style="margin-top: 1px !important;">');
            if (facebookid != null) {
                $scope.setusername_model.UserId = window.localStorage.getItem('UserId');
            }
            else {
                $scope.setusername_model.UserId = window.localStorage.getItem('UserId');

            }

            //$scope.setUsername();


        }

        $scope.GetUserData = function () {

            $scope.UserData = [];
            $scope.UserTypeId = [];
            //debugger;

            //  if($scope.checkfacebookId() == true){
            //       $scope.user_model.UserId = window.localStorage.getItem("UserIdfb");
            //  }else{
            //$scope.user_model.UserId = window.localStorage.getItem("UserId");
            //  }

            $scope.user_model.UserId = window.localStorage.getItem("UserId");


            salewithusService.userdata_($scope.user_model).then(function success(response) {
                console.log(response.data.Result);
                //debugger;
                $scope.UserData = response.data.Result;
                // $scope.Resetpasscode = response.data.Result.ResetPasswordCode;
               
                $scope.u_img = response.data.Result.UserImage;
                tradeService.setuserimage($scope.u_img);
                $scope.GetUserData();

            },
                function error(response) {

                    console.log("error");
                    // this function will be called when the request returned error status
                });
        }

        $scope.alert = function () {
            swal("If you are a Student then please register with your (.edu) email address for free use of this service.")
        }

        $scope.profiledata = function () {
            //debugger;
            var facebookid = window.localStorage.getItem("FacebookId");

            if (facebookid != null) {
                var UserId = window.localStorage.getItem('UserId');
            }
            else {
                var UserId = window.localStorage.getItem('UserId');
            }

            // var UserId = window.localStorage.getItem('UserId');
            //  var UserTypeId = window.localStorage.getItem('UserTypeID')
            if (UserId !== null) {
                $("#profile").show();

                $("#login").hide();
            }
            else {
                $("#profile").hide();

                $("#login").show();

            }


        }

        //fblogin//
        $scope.details = {
            FacebookId: "",
            App_token: "",
            One_signal_key: "",
            Device_id: "",
            Device_type: "",

        }

        $scope.loginFb = function (data) {
            //debugger;
            $scope.details.FacebookId = data.id;

            salewithusService.LoginUserfb($scope.details).then(function (response) {
                //debugger;
                if (response.data.Status == "Success") {

                    window.localStorage.setItem('FacebookId', response.data.Result.FacebookId);

                    //  $(".showloading").css("visibility", "hidden");

                    //window.localStorage.setItem('UserIdfb', response.data.Result.UserID);
                    window.localStorage.setItem('UserId', response.data.Result.UserID);
                    window.localStorage.setItem('UserName', response.data.Result.UserName);
                    //window.localStorage.setItem('FirstName', response.data.Result.FirstName);
                    //window.localStorage.setItem('UserTypeID', response.data.Result.UserTypeId);
                    window.localStorage.setItem('UserImage', response.data.Result.UserImage);
                    //window.localStorage.setItem('UserTypeIDfb', response.data.Result.UserTypeId);
                    window.localStorage.setItem('UserTypeID', response.data.Result.UserTypeId);

                    $("#myModal").hide();
                    if (response.data.Result.UserTypeId == 1) {
                        swal({
                            title: "Success!",
                            text: "Login Successfull!",
                            icon: "success",
                            button: "Ok!",
                        });
                        $state.go("index", {}, { reload: true });
                    }
                    else {

                    }

                    $("body").css("padding", "0px");


                }
                else {

                    $scope.registerfb(data);

                }

            })

        }
        $scope.Registermodel_fb = {
            FirstName: "",
            LastName: "",
            Email: "",
            PhoneNumber: "",
            UserName: "",
            Password: "",
            StateId: "",
            CityId: "",
            CountryId: "",
            UserTypeId: 1,
            Zipcode: "",
            MiddleName: "",
            Latitude: "",
            Longitude: "",
            IpAddress: "",
            IsActive: "",
            IsDeleted: "",
            IsVerified: "",
            CreatedBy: "",
            CreatedDateTime: "",
            AddressLine1: "",
            AddressLine2: "",
            App_Token: "",
            Device_Id: "",
            Device_Type: "",
            Gender: "",
            UserImage: "",
            ActivationCode: "",
            Firebase_token: "",
            One_signal_key: "",
            CollegeId: null,
            FacebookId: "",
        }

        $scope.registerfb = function (data) {
            //debugger;
            $scope.Registermodel_fb.FirstName = data.first_name;
            $scope.Registermodel_fb.LastName = data.last_name;
            // $scope.Registermodel_fb.Email = data.email;
            $scope.Registermodel_fb.FacebookId = data.id;
            $scope.Registermodel_fb.UserImage = window.localStorage.getItem('ProfileImage');
            // $scope.Registermodel_fb.UserName = data.Email;

            $scope.Registermodel_fb.UserTypeId = 1;

            $scope.Registermodel_fb.Latitude = mysrclat;

            $scope.Registermodel_fb.Longitude = mysrclong;

            salewithusService.AddRegister($scope.Registermodel_fb).then(function (response) {
                //  $window.location.reload();
                //$scope.FirstName = registermodel.FirstName;
                $scope.FirstName = response.data.Result.FirstName;
                $scope.userid_new = response.data.Result.UserId;

                //debugger;
                if (response.data.Status == "Success") {

                    //window.localStorage.setItem("Emailid", $scope.Registermodel_fb.Email);
                    //window.localStorage.setItem("Register_pass", $scope.Registermodel_fb.Password);

                    //if (response.data.Message == "User with this Email Already Exist") {
                    //    swal(response.data.Message);
                    //}
                    //else {

                    //}

                    // $("#verifymodal").show();
//debugger;

                    $("body").css("padding", "0px");
                    $scope.loginFb(data);
                    $state.go("index", {}, { reload: true });

                }
                else {

                    //  $(".showloading").css("visibility", "hidden");
                    //$("#verifymodal").modal('show');
                    alert("Something Went Wrong!!");
                }
            });

        }


        //fblogin//


        //get_currect_location_start//
        $scope.mysrclat = "";
        $scope.lat = "";
        $scope.lan = "";
        $scope.nearme = function () {
            //debugger;
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    mysrclat = position.coords.latitude;
                    mysrclong = position.coords.longitude;
                    //console.log("lat", mysrclat);
                    //console.log("ong", mysrclong);

                    $scope.$apply(function () {
                        $scope.lat = mysrclat;
                        salewithusService.setlat(mysrclat);
                        $scope.lan = mysrclong;
                        salewithusService.setlong(mysrclong);
                    })

                    $scope.$evalAsync(function () {
                        $scope.elat = mysrclat;
                        $scope.elan = mysrclong;
                    })

                    $("#lat").val(mysrclat);
                    $("#long").val(mysrclong);
                    $scope.Getrecommendedtrades();

                });
            }

        }

        $scope.AllRecommendedTrades = [];
        $scope.Trecommendedmodel = {

            UserId: null,

            Longitude: 0.0,
            Latitude: 0.0,
            Radius: 600000,
        };

        $scope.Getrecommendedtrades = function () {
            $scope.AllRecommendedTrades = [];
            $scope.Trecommendedmodel.UserId = window.localStorage.getItem('UserId');
            if ($scope.Trecommendedmodel.Longitude == 0 || $scope.Trecommendedmodel.Longitude == undefined) {

                $scope.Trecommendedmodel.Longitude = salewithusService.getlong();

            }
            else {

            }
            if ($scope.Trecommendedmodel.Latitude == 0 || $scope.Trecommendedmodel.Latitude == undefined) {

                $scope.Trecommendedmodel.Latitude = salewithusService.getlat();

            }
            else {

            }
            $scope.Trecommendedmodel.Radius = 100;

            salewithusService.recommendedtrades($scope.Trecommendedmodel).then(function (response) {
                if (response.data.Status == "Success") {

                    $scope.AllRecommendedTrades = response.data.Result;
                    $scope.ShowSpinnerStatus = false;
                    window.localStorage.setItem("trade_userid", response.data.Result[0].UserId);
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });



        }
        //get_currect_location_end//
        $scope.selectedproductDetailsList = [];

        $scope.AllProductsCategory = [];

        $scope.selectedproduct = [];
        $scope.AllCharity = [];

        $scope.Categorylist = [];
        $scope.Categorylist2 = [];
        $scope.Categorylist3 = [];
        $scope.Categorylist4 = [];
        $scope.Categorylist5 = [];
        $scope.Allcountrycode = [];
        $scope.charityid = "";
        $scope.proid = "";
        $scope.procatid = "";
        $scope.searchProductList = []
        $scope.minprice = null;
        $scope.maxprice = null;
        $scope.SearchTrademodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: 0,
            SubCategoryId: 0,
            MinPrice: null,
            MaxPrice: null,
            ISBN_No: ""
        }
        $scope.showSearchProducts = function (searchproductName) {
            $scope.searchProductList = [];
            $scope.SearchTrademodel.UserId = window.localStorage.getItem('UserId');
            $scope.SearchTrademodel.Latitude = SelectedLatitude;
            $scope.SearchTrademodel.Longitude = SelectedLongitude;
            $scope.SearchTrademodel.Radius = 600;
            $scope.SearchTrademodel.SearchText = searchproductName;
            // $scope.SearchTrademodel.ISBN_No = searchproductName;

            //debugger;

            $state.go("filterpage", {}, { reload: true });


            window.localStorage.setItem('searchproductName', searchproductName);

        }


        $scope.Searchneedsmodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: 0,
            SubCategoryId: 0,
            MinPrice: null,
            MaxPrice: null,
            ISBN_No: ""
        }
        $scope.showSearchProducts_needs = function (searchproductName) {
            $scope.searchProductList = [];
            $scope.Searchneedsmodel.UserId = window.localStorage.getItem('UserId');
            $scope.Searchneedsmodel.Latitude = SelectedLatitude;
            $scope.Searchneedsmodel.Longitude = SelectedLongitude;
            $scope.Searchneedsmodel.Radius = 600;
            $scope.Searchneedsmodel.SearchText = searchproductName;
            // $scope.SearchTrademodel.ISBN_No = searchproductName;

            //debugger;

            $state.go("filterpage_needs", {}, { reload: true });


            window.localStorage.setItem('searchproductName', searchproductName);

        }
        $scope.Searchcollegetradesmodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: 0,
            SubCategoryId: 0,
            MinPrice: null,
            MaxPrice: null,
            ISBN_No: ""
        }

        $scope.showSearchProducts_college = function (searchproductName) {
            $scope.searchProductList = [];
            $scope.Searchcollegetradesmodel.UserId = window.localStorage.getItem('UserId');
            $scope.Searchcollegetradesmodel.Latitude = SelectedLatitude;
            $scope.Searchcollegetradesmodel.Longitude = SelectedLongitude;
            $scope.Searchcollegetradesmodel.Radius = 600;
            $scope.Searchcollegetradesmodel.SearchText = searchproductName;
            // $scope.SearchTrademodel.ISBN_No = searchproductName;
            salewithusService.setpagename_college("filterpage_collegetrades");
           // //debugger;

            $state.go("filterpage_collegetrades", {}, { reload: true });


            window.localStorage.setItem('searchproductName', searchproductName);

        }

        $scope.getlist = [];
        $scope.getlistofproducts = function (searchproductName, maxprice, minprice) {
            $("#list").show();
            $scope.getlist = [];
            $scope.SearchTrademodel.SearchText = searchproductName;
            $scope.SearchTrademodel.Latitude = SelectedLatitude;
            $scope.SearchTrademodel.Longitude = SelectedLongitude;
            $scope.SearchTrademodel.Radius = 600;
            salewithusService.searchtrade($scope.SearchTrademodel).then(function (response) {

                if (response.data.Status == "Success") {

                    // swal("Updated Successfully!!");
                    $scope.getlist = response.data.Result;

                }
                else {
                    //  swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }
        $scope.AllCharity = [];

        $scope.charity_model = {

            pageNumber: 1,
            pageSize: 8
        }

        $scope.charity2 = [];
        //$scope.GetAllCharity = function () {
        //    $scope.AllCharity = []
        //    $scope.charity_model.pageNumber = pagenumber;


        //    salewithusService.Charity($scope.charity_model).then(function (response) {
        //        if (response.data.Status == "Success") {

        //            $scope.AllCharity = response.data.Result;


        //            for (var i = 0; i < $scope.AllCharity.length; i++) {
        //                var obj = $scope.AllCharity[i];
        //                $scope.charity2.push($scope.AllCharity[i]);
        //            }
        //            salewithusService.setcharityname(response.data.Result[0].CharityName);
        //            salewithusService.setcharityuserid(response.data.Result[0].UserId);
        //            salewithusService.setcharityimage(response.data.Result[0].CharityImage);

        //        }
        //        else {
        //            swal("Something Went Wrong!!");
        //        }

        //    }, function error(response) {
        //        console.log("error");
        //    });

        //}

        $scope.GetAllCharity = function () {
            $scope.AllCharity = [];

            $.LoadingOverlay("show"); //paras\
            $http({
                method: 'GET',
                url: 'api/Charity/charities'
            }).then(function success(response) {
                //debugger;
                $.LoadingOverlay("hide"); //paras\
                $scope.AllCharity = response.data.Result;
                salewithusService.setcharityname(response.data.Result[0].CharityName);
                salewithusService.setcharityuserid(response.data.Result[0].UserId);
                salewithusService.setcharityimage(response.data.Result[0].CharityImage);

                //window.localStorage.setItem("CharityName", response.data.Result[0].CharityName);
                //window.localStorage.setItem("CharityImage", response.data.Result[0].CharityImage);
            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                    // this function will be called when the request returned error status
                }
            );

        };

        $scope.loadMore_charitylist = function () {
            pagenumber = pagenumber + 1;
            $scope.GetAllCharity();
        }


        $scope.Tmodel = {

            UserId: 0,
            CollegeId: null,
            CategoryId: null,
            CategoryName: "",
            CollegeName: "",
            UserName: "",
            ItemName: "",
            Description: "",
            Longitude: 0.0,
            Lattitude: 0.0,
            Condition: "",
            Quantity: "",
            CreatedDateTime: null,
            ModifiedDateTime: null,
            CreatedBy: "",
            IpAddress: "",
            Size: "",
            Price: "",
            IsActive: null,
            short_description: "",
            TradeImage: "",
            IsLiked: false
        };

        $scope.Getalltradeafterlogin = function () {
            $scope.AllTrade = []
            $scope.Tmodel.UserId = window.localStorage.getItem('UserId');


            salewithusService.tradeafterlogin($scope.Tmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    //swal("Updated Successfully!!");
                    //$("#tradeafterlogin").show();
                    //$("#tradebeforelogin").hide();
                    $scope.AllTrade = response.data.Result;
                    // window.localStorage.setItem("trade_userid", response.data.Result[0].UserId);
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }


        $scope.GetAllTrade = function () {
            $scope.AllTrade = [6];
            //debugger;
            $http({
                method: 'GET',
                url: 'api/Trades/GetAllTrade'
            }).then(function success(response) {
                //debugger;
                $scope.AllTrade = response.data;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );

        };


        $scope.LoginModel = {
            UserName: "",
            Password: "",

        };

        $scope.showmessage = false;


        $scope.LoginUser = function (LoginModel) {

            $scope.LoginModel.UserName = LoginModel.UserName;

            $scope.LoginModel.Password = LoginModel.Password;

            if ($scope.LoginModel.UserName && $scope.LoginModel.Password != "") {

                salewithusService.LoginUser($scope.LoginModel).then(function (response) {

                    if (response.data.Status == "Success") {
                       $scope.fname= response.data.Result.FirstName;
                        //  $(".showloading").css("visibility", "hidden");

                        window.localStorage.setItem('UserId', response.data.Result.UserID);
                        window.localStorage.setItem('UserName', response.data.Result.UserName);
                        window.localStorage.setItem('FirstName', response.data.Result.FirstName);
                        window.localStorage.setItem('UserTypeID', response.data.Result.UserTypeId);
                        window.localStorage.setItem('UserImage', response.data.Result.UserImage);

                        $("#myModal").hide();
                        if (response.data.Result.UserTypeId == 1) {
                            swal({
                                title: "Success!",
                                text: "Login Successfull!",
                                icon: "success",
                                button: "Ok!",
                            });
                            $state.go("index", {}, { reload: true });
                        }
                        else {
                            swal({
                                title: "Success!",
                                text: "Thank you dear for logging to manage your Charity -" + $scope.fname,
                                icon: "success",
                                button: "Ok!",
                            });
                            $state.go("my_needs", {}, { reload: true });
                        }

                        $("body").css("padding", "0px");


                    }
                    else {


                        alert("Invalid UserName or Password");

                    }

                })
            }
            else {
                alert("Invalid UserName or Password");

            }
        }

        $scope.LoginUserfromRegister = function () {


            $scope.LoginModel.UserName = window.localStorage.getItem("Emailid");


            $scope.LoginModel.Password = window.localStorage.getItem("Register_pass");



            salewithusService.LoginUser($scope.LoginModel).then(function (response) {

                if (response.data.Status == "Success") {

                    window.localStorage.setItem('UserId', response.data.Result.UserID);
                    window.localStorage.setItem('UserName', response.data.Result.UserName);
                    window.localStorage.setItem('FirstName', response.data.Result.FirstName);
                    window.localStorage.setItem('UserTypeID', response.data.Result.UserTypeId);
                    window.localStorage.setItem('UserImage', response.data.Result.UserImage);

                    $("#myModal").hide();

                    swal({
                        title: "Success!",
                        text: "Login Successfull!",
                        icon: "success",
                        button: "Ok!",
                    });

                    $("body").css("padding", "0px");
                    $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                    if ($scope.usertype_ == 1) {
                        $state.go("index", {}, { reload: true });
                    }
                    else {
                        $state.go("my_needs", {}, { reload: true });
                    }



                }
                else {

                    alert("Invalid UserName or Password");

                }

            })

        }

        $scope.rememberMe = function () {
            //debugger;
            if (localStorage.chkbx && localStorage.chkbx != '') {
                $('#remember_me').attr('checked', 'checked');
                $('#email').val(localStorage.email);
                $('#pwd').val(localStorage.pass);
                $scope.LoginModel.UserName = localStorage.email;
                $scope.LoginModel.Password = localStorage.pass;
            }
            else {
                $('#remember_me').removeAttr('checked');
                $('#email').val('');
                $('#pwd').val('');
                $scope.LoginModel.UserName = "";

                $scope.LoginModel.Password = "";
            }
            $('#remember_me').click(function () {
                if ($('#remember_me').is(':checked')) {
                    // save username and password
                    localStorage.email = $('#email').val();
                    localStorage.pass = $('#pwd').val();
                    $scope.LoginModel.UserName = localStorage.email;
                    $scope.LoginModel.Password = localStorage.pass;
                    localStorage.chkbx = $('#remember_me').val();
                }
                else {
                    $scope.LoginModel.UserName = "";
                    localStorage.email = '';
                    localStorage.pass = '';
                    $scope.LoginModel.Password = "";
                    localStorage.chkbx = '';
                }
            });
        };
        $scope.msg = false;
        $scope.showMsgs_ = false;
        $scope.FirstName = "";
        $scope.userid_new = 0;
        $scope.registermodel = {
            FirstName: "",
            LastName: "",
            Email: "",
            PhoneNumber: "",
            UserName: "",
            Password: "",
            StateId: "",
            CityId: "",
            CountryId: "",
            UserTypeId: "User",
            Zipcode: "",
            MiddleName: "",
            Latitude: "",
            Longitude: "",
            IpAddress: "",
            IsActive: "",
            IsDeleted: "",
            IsVerified: "",
            CreatedBy: "",
            CreatedDateTime: "",
            AddressLine1: "",
            AddressLine2: "",
            App_Token: "",
            Device_Id: "",
            Device_Type: "",
            Gender: "",
            Firebase_token: "",
            One_signal_key: "",
            CollegeId: null,

        };


        $scope.getcountrycode = [];
        $scope.selectedCountrycode = "+1";
        $scope.PhoneNumber = "";
        $scope.showMsgs__ = false;
        $scope.showMsgs_phn = false;
        $scope.password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
        $scope.SaveData = function (registermodel) {
        
            $(".showloading").css("visibility", "visible");

            var selectedCode = $scope.selectedCountrycode;//$scope.subid = data;
            $scope.code = selectedCode.trim();
            // alert(selectedCode.trim());
            $scope.registermodel.FirstName = registermodel.FirstName;
            if ($scope.registermodel.UserTypeId == 'Charity') {
                $scope.registermodel.LastName = "Charity";
            }
            else {
                $scope.registermodel.LastName = registermodel.LastName;
            }

         
            $scope.registermodel.Email = registermodel.Email;

            if (registermodel.Email.includes(".edu")) {
                $scope.registermodel.CollegeId = salewithusService.getcollegeid();
            }
            else {
                $scope.registermodel.CollegeId = null;
            }

            $scope.registermodel.PhoneNumber = $scope.code + "-" + $scope.PhoneNumber;
            $scope.registermodel.UserName = registermodel.Email;

            $scope.registermodel.Password = registermodel.Password;

            $scope.registermodel.StateId = registermodel.StateId;
            $scope.registermodel.CityId = registermodel.CityId;
            $scope.registermodel.CountryId = $scope.selectedCountry;

            if ($scope.registermodel.UserTypeId == 'User') {

                $scope.registermodel.UserTypeId = 1;

            }

            else {
                $scope.registermodel.UserTypeId = 3;
            }
            $scope.registermodel.Zipcode = registermodel.Zipcode;
            $scope.registermodel.MiddleName = registermodel.MiddleName;

            if ($scope.registermodel.Latitude == "") {
                // $scope.nearme();
                $scope.registermodel.Latitude = mysrclat;
            }
            else {
                $scope.registermodel.Latitude = registermodel.Latitude;
            }

            if ($scope.registermodel.Longitude == "") {
                // $scope.nearme();
                $scope.registermodel.Longitude = mysrclong;
            }
            else {
                $scope.registermodel.Longitude = registermodel.Latitude;
            }

            // $scope.registermodel.Longitude = mysrclong;
            $scope.registermodel.IpAddress = registermodel.IpAddress;
            $scope.registermodel.IsActive = registermodel.IsActive;
            $scope.registermodel.IsDeleted = registermodel.IsDeleted;
            $scope.registermodel.IsVerified = registermodel.IsVerified;
            $scope.registermodel.CreatedBy = registermodel.CreatedBy;
            $scope.registermodel.CreatedDateTime = registermodel.CreatedDateTime;
            $scope.registermodel.AddressLine1 = registermodel.AddressLine1;
            $scope.registermodel.AddressLine2 = registermodel.AddressLine2;
            $scope.registermodel.App_Token = registermodel.App_Token;
            $scope.registermodel.Device_Id = registermodel.Device_Id;
            $scope.registermodel.Device_Type = registermodel.Device_Type;
            $scope.registermodel.Gender = registermodel.Gender;
            $scope.registermodel.Firebase_token = registermodel.Firebase_token;
            $scope.registermodel.One_signal_key = registermodel.One_signal_key;
            if ($scope.userForm.$valid) {
                if (registermodel.Password.match($scope.password)) {
                    salewithusService.AddRegister($scope.registermodel).then(function (response) {
                        //  $window.location.reload();
                        $scope.FirstName = registermodel.FirstName;
                        $scope.userid_new = response.data.Result.UserId;
                        if (response.data.Result.UserTypeId == 3) {
                            $scope.savecharitydata();
                        }
                        else {

                        }

                       // //debugger;
                        if (response.data.Status == "Success") {

                            window.localStorage.setItem("Emailid", $scope.registermodel.Email);
                            window.localStorage.setItem("Register_pass", $scope.registermodel.Password);

                            if (response.data.Message == "User with this Email Already Exist") {
                                swal(response.data.Message);
                            }
                            else {

                                $("#verifymodal").modal('show');

                                //  Cleardata(registermodel);
                            }



                            // $("#verifymodal").show();
                            //debugger;

                            $("body").css("padding", "0px");

                            //$state.go("index", {}, { reload: true });


                        }
                        else {

                            //  $(".showloading").css("visibility", "hidden");
                            //$("#verifymodal").modal('show');
                            alert("Something Went Wrong!!");
                        }
                    });
                }
                else {

                    swal("  Password should be 8 to 15 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character.");
                }
            }
            else {
                swal("Invaild input. please check.")
                $scope.IsDisabled = false;
            }
        }


        $scope.showPassword = false;

        $scope.toggleShowPassword = function () {
            $scope.showPassword = !$scope.showPassword;
        }



        $scope.Cleardata = function () {
            //debugger;
            $scope.registermodel.FirstName = "";
            $scope.registermodel.LastName = "";
            $scope.registermodel.Email = "";
            $scope.registermodel.CollegeId = "";
            $scope.registermodel.Zipcode = "";
            $scope.registermodel.MiddleName = "";
            $scope.registermodel.PhoneNumber = "";
            $scope.registermodel.Latitude = "";
            $scope.registermodel.Longitude = "";
            $scope.registermodel.IpAddress = "";
            $scope.registermodel.AddressLine1 = "";
            $scope.registermodel.AddressLine2 = "";
            $scope.registermodel.Gender = "";
            $scope.StartsWith = "";

        };
        $scope.SaveTempData = function () {

            $("#verifymodal").modal('show');
        }

        $scope.verifycodemodel = {

            Email: "",
            ActivationCode: ""
        };

        $scope.Verifycode = function (verifycodemodel) {

            if (verifycodemodel.ActivationCode == "") {

                swal("please enter verification code!");
            }
            else {


                $scope.verifycodemodel.Email = window.localStorage.getItem("Emailid");
                $scope.verifycodemodel.ActivationCode = verifycodemodel.ActivationCode;

                salewithusService.userverify($scope.verifycodemodel).then(function (response) {

                    //debugger;
                    if (response.data.Status == "Success") {

                        $("#verifymodal").modal('hide');
                        // swal(response.data.Message);

                        $scope.LoginUserfromRegister();
                        // $state.go("index", {}, { reload: true });
                        window.localStorage.removeItem("Emailid");
                    }
                    else {

                        $("#verifymodal").modal('hide');
                        swal(response.data.Message);

                    }
                });

            }
        }

        $scope.resendverifycodemodel = {

            Email: "",
        };

        $scope.Sendverificationcode = function () {

            if (window.localStorage.getItem("Emailid") == "") {

                swal("Please provide email id!");
            }
            else {

                $scope.resendverifycodemodel.Email = window.localStorage.getItem("Emailid");

                salewithusService.resendverificationcode($scope.resendverifycodemodel).then(function (response) {

                    //debugger;
                    if (response.data.Status == "Success") {

                        swal(response.data.Message);

                    }
                    else {

                        swal(response.data.Message);

                    }
                });
            }

            //swal("verification code send Successfully!");

        }

        $scope.checkemail = function (data) {
            if (data != null || data != undefined) {


                if (data.includes(".edu")) {
                    $("#University_list").show();
                    $scope.getuniversity();
                }
                else {
                    $("#University_list").hide();
                    //  alert("Invalid student email-Id.");
                }
            }
        }

        $scope.CollegeId = 0;
        $scope.StartsWith = "";
        $scope.university_model = {
            StartsWith: ""
        }

        $scope.getuniversity = function (StartsWith) {
            $("#list").show();
            $scope.university = [];
            $scope.university_model.StartsWith = StartsWith;
            salewithusService.university($scope.university_model).then(function (response) {


                if (response.data.Status == "Success") {

                    // swal("Updated Successfully!!");
                    $scope.university = response.data.Result;
                    $scope.CollegeId = salewithusService.setcollegeid(response.data.Result.CollegeId);

                }
                else {
                    //  swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }
        $scope.fillTextbox = function (data, collegeid) {
            $scope.StartsWith = data;
            salewithusService.setcollegeid(collegeid);
            window.localStorage.setItem("CollegeId", collegeid);
            $scope.university = null;
            $("#list").hide();
        }

        $scope.countryid = [];
        $scope.GetCountrycode = function () {


            //debugger;
            $scope.Allcountrycode = [];


            $http({
                method: 'GET',
                url: 'api/Country/GetCountryCodes'
            }).then(function success(response) {
                //debugger;
                $scope.Allcountrycode = response.data.Result;

                // $scope.Allcountrycode = response.data.Result.code;
                // $scope.countryid.push(0);
                for (var i = 0; i < $scope.Allcountrycode.length; i++) {

                    var obj = $scope.Allcountrycode[i];

                    $scope.getcountrycode.push($scope.Allcountrycode[i].code);

                }

                console.log("countrycode " + $scope.getcountrycode[0]);
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );
        }

        
        $scope.getcountrycountries = [];
        $scope.selectedCountry = 0;
        
        $scope.GetCountries = function () {


            //debugger;
            $scope.getcountries = [];


            $http({
                method: 'GET',
                url: 'api/Country/Countries'
            }).then(function success(response) {
                //debugger;
                $scope.getcountries = response.data.Result;

                // $scope.Allcountrycode = response.data.Result.code;
                // $scope.countryid.push(0);
                for (var i = 0; i < $scope.getcountries.length; i++) {

                    var obj = $scope.Allcountrycode[i];

                    $scope.getcountrycountries.push($scope.getcountries[i].code);

                }

                console.log("countrycode " + $scope.getcountrycode[0]);
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );
        }
        $scope.Charitymodel = {
            CharityId: 0,
            CharityName: "",
            Description: "",
            CityId: null,
            StateId: null,
            CountryId: null,
            UserId: "",
            CreatedDateTime: "2019-12-03 15:29:22.183",
            IpAddress: "",
            CharityImage: "",
            Needs: "",
        }

        $scope.savecharitydata = function () {
            // $scope.Charitymodel.CharityId = window.localStorage.getItem('CharityId');
            $scope.Charitymodel.UserId = $scope.userid_new;
            $scope.Charitymodel.CharityName = $scope.FirstName;
            $scope.Charitymodel.Description = $('#charitydiscription').val();
            $scope.Charitymodel.Needs = $('#charityneeds').val();

            if ($scope.Charitymodel.CreatedDateTime != "") {
                $scope.Charitymodel.CreatedDateTime = $("#cdatetime").val();

            }
            else {
                $scope.Charitymodel.CreatedDateTime = Charitymodel.CreatedDateTime;

            }

            salewithusService.charityneeds($scope.Charitymodel).then(function (response) {


                if (response.data.Status == "Success") {

                    // swal("Updated Successfully!!");

                }
                else {
                    //  swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }



        //$scope.GetAllProductsCategory = function () {

        //    //debugger;
        //    $scope.AllProductsCategory = [6];

        //    $http({
        //        method: 'GET',
        //        url: 'api/Category/GetCategoryList'

        //    }).then(function success(response) {

        //        //debugger;
        //        $scope.AllProductsCategory = response.data;
        //        window.localStorage.setItem('CategoryId', response.data.CategoryId);
        //        for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

        //            if (i < 6) {
        //                $scope.Categorylist2.push($scope.AllProductsCategory[i]);

        //            }
        //            if (i >= 6 && i < 12) {
        //                $scope.Categorylist3.push($scope.AllProductsCategory[i]);

        //            }
        //            if (i >= 12 && i < 18) {
        //                $scope.Categorylist4.push($scope.AllProductsCategory[i]);

        //            }

        //        }


        //    },
        //        function error(response) {
        //            console.log("error");
        //            // this function will be called when the request returned error status
        //        });


        //};

        $scope.allcategory_ = [];
        $scope.Categorylist6 = [];
        $scope.GetAllProductsCategory = function () {
            $.LoadingOverlay("show"); //paras\
            //debugger;
            $scope.AllProductsCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                $.LoadingOverlay("hide"); //paras\

                //debugger;
                // $scope.allcategory_ = response.data.length;
                $scope.AllProductsCategory = response.data.Result;

                $scope.allcategory_ = Array(Math.ceil($scope.AllProductsCategory.length / 6));

                window.localStorage.setItem('CategoryId', $scope.AllProductsCategory.CategoryId);
                for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

                    if (i < 6) {
                        $scope.Categorylist2.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 6 && i < 12) {
                        $scope.Categorylist3.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 12 && i < 18) {
                        $scope.Categorylist4.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 18 && i < 24) {
                        $scope.Categorylist5.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 24 && i < 35) {
                        $scope.Categorylist6.push($scope.AllProductsCategory[i]);

                    }

                }



            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                    // this function will be called when the request returned error status
                });


        };

        $scope.selectedcategoryfromheader = 0;
        $scope.selectedCategory = 0;
        $scope.AllSubCategory = [];
        $scope.categoryname = "";
        $scope.categories = {
            CategoryId: 0
        }
        $scope.GetAllSubCategory = function () {

            $scope.subid = 0;
            //debugger;
            $scope.AllCategory = [];
            $scope.Allsubcategories_ = [];
            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllCategory = response.data.Result;
                //  $scope.Allsubcategories = response.data.Result.Subcategories;
                salewithusService.setfrompage('Header');
                //debugger;


                for (var i = 0; i < $scope.AllCategory.length; i++) {
                    var obj = $scope.AllCategory[i];
                    $scope.subid = $scope.AllCategory[i].CategoryId;

                    if ($scope.AllCategory[i].CategoryId == $scope.subid) {
                        //for (var j = 0; j < obj.Subcategories.length; j++) {
                        //  $scope.getsubcategoriesbycateid();

                        if (obj.Subcategories.length > 0) {

                            $scope.Allsubcategories_ = obj.Subcategories;

                            $scope.AllSubCategory = new Array();
                            $scope.AllSubCategory.push(obj.Subcategories);
                        }

                        else {

                        }
                        //}
                    }

                }


            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });


        };

        $scope.AllSubCategory2 = [];
        $scope.selectedSubCategory = 0;
        $scope.GetSubCategory = function () {

            var selectedCategoryId = $scope.selectedCategory;//$scope.subid = data;
            $scope.subid = selectedCategoryId;
            $scope.subcat = $scope.selectedSubCategory;
            //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllSubCategory = response.data.Result;
                $scope.frompage = salewithusService.getfrompage();
                if ($scope.frompage == 'Header') {
                    $scope.searchbycategory();
                }
                else {
                    $scope.searchbycategory();
                }

                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        $scope.selected_categoryname = obj.CategoryName;
                        //if ($scope.selected_categoryname == "Bag") {
                        //    $("#rateperhour").show();
                        //}
                        //else {
                        //    $("#rateperhour").hide();
                        //}
                        salewithusService.setcategoryname($scope.selected_categoryname);
                        if (obj.Subcategories.length > 0) {
                            $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                            window.localStorage.setItem("SubCatIsAvailable", "true");
                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            $('#SubCategoryList').hide();
                            //swal({
                            //    text: "No Subcategories are available for this category.",
                            //    button: "Ok!",
                            //});
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });


        };

        $scope.searchmodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: null,
            SubCategoryId: null,
            MinPrice: null,
            MaxPrice: null,
            PageNumber: 1,
            PageSize: 8,
            ISBN_No: ""
        }

        $scope.searchbycategory = function () {

            $scope.searchProductList = [];
            $scope.searchmodel.UserId = window.localStorage.getItem('UserId');
            $scope.searchmodel.PageNumber = pagenumber;
            $scope.searchmodel.CategoryId = $scope.selectedCategory;
            $scope.searchmodel.SubCategoryId = $scope.selectedSubCategory;
            $scope.searchmodel.ISBN_No = $scope.isbnnumber;
            if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                $scope.searchmodel.Latitude = SelectedLatitude;
                $scope.searchmodel.Longitude = SelectedLongitude;
                $scope.searchmodel.Radius = 100;
            }
            else {
                $scope.searchmodel.Latitude = mysrclat;
                $scope.searchmodel.Longitude = mysrclong;
                $scope.searchmodel.Radius = 600000;

            }
            $scope.searchmodel.SearchText = "";

            //debugger;
            salewithusService.searchtrade($scope.searchmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.searchProductList = response.data.Result;
                    $scope.gettradesbycategoryid = $scope.searchProductList;
                    //for (var i = 0; i < $scope.searchProductList.length; i++) {
                    //    var obj = $scope.searchProductList[i];
                    //    $scope.gettradesbycategoryid.push($scope.searchProductList[i]);
                    //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                    //    $("#loader").hide();
                    //    //  pagenumber.shift();
                    //    $("#btn_spin").show();
                    //}

                    //if ($scope.totalcount == $scope.searchtrades.length) {
                    //    $("#btn_spin").hide();
                    //}
                    //else {
                    //    $("#btn_spin").show();
                    //}

                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });
        }

        $scope.searchbyisbn = function (data) {
            $scope.searchProductList = [];
            $scope.searchmodel.UserId = window.localStorage.getItem('UserId');
            $scope.searchmodel.PageNumber = pagenumber;
            $scope.searchmodel.CategoryId = $scope.selectedCategory;
            $scope.searchmodel.SubCategoryId = $scope.selectedSubCategory;
            $scope.searchmodel.ISBN_No = data;
            if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                $scope.searchmodel.Latitude = SelectedLatitude;
                $scope.searchmodel.Longitude = SelectedLongitude;
                $scope.searchmodel.Radius = 100;
            }
            else {
                $scope.searchmodel.Latitude = mysrclat;
                $scope.searchmodel.Longitude = mysrclong;
                $scope.searchmodel.Radius = 600000;

            }
            $scope.searchmodel.SearchText = "";

            //debugger;
            salewithusService.searchtrade($scope.searchmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.searchProductList = response.data.Result;
                    $scope.gettradesbycategoryid = $scope.searchProductList;
                    //for (var i = 0; i < $scope.searchProductList.length; i++) {
                    //    var obj = $scope.searchProductList[i];
                    //    $scope.searchtrades.push($scope.searchProductList[i]);
                    //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                    //    $("#loader").hide();
                    //    //  pagenumber.shift();
                    //    $("#btn_spin").show();
                    //}

                    //if ($scope.totalcount == $scope.searchtrades.length) {
                    //    $("#btn_spin").hide();
                    //}
                    //else {
                    //    $("#btn_spin").show();
                    //}

                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });
        }
        $scope.isbn = "";

        $scope.checkisbn = function () {
            $scope.isbn = $scope.selectedCategory;
            if ($scope.isbn == 1) {
                return true;
            }
            else {
                return false;
            }
        }

        $(".allcatlink").click(function () {

            $("#category").show();
            $scope.ShowSubcategories(1);

        });

        $scope.subid = 0;

        $scope.ShowSubcategories = function (categoryId) {


            $scope.subid = categoryId;
            $scope.Subcategories = [];
           // //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllSubCategory = response.data.Result;
                $("#category").show();
                $("#subcategories").show();
                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        if (obj.Subcategories.length > 0) {
                            //$('#SubCategoryList').show();
                            $scope.Subcategories = obj.Subcategories;
                            //window.localStorage.setItem("SubCatIsAvailable", "true");
                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            //$scope.showsubcategory();
                            $scope.showtradesbycategory();
                            //$('#SubCategoryList').hide();
                            //swal({
                            //    text: "No Subcategories are available for this category.",
                            //    button: "Ok!",
                            //});
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });


        };

        $("body").click(function () {

            $("#category").hide();
        });


        $scope.showsubcategory = function (Categotyid, subcategoryid) {

            salewithusService.setcategoryid($scope.subid);
            salewithusService.setsubcategoryid(subcategoryid);

            $state.go("RelatedProduct", {}, { reload: true });

        };
        $scope.showtradesbycategory = function () {

            salewithusService.setcategoryid($scope.subid);
            salewithusService.setsubcategoryid(null);

            $state.go("RelatedProduct", {}, { reload: true });

        };

        $scope.GetState = function () {
            $scope.State = [6];

            $http({
                method: 'GET',
                url: 'api/State/states'

            }).then(function success(response) {
                //debugger;
                $scope.State = response.data.Result;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });
        };


        $scope.GetCity = function () {
            $scope.City = [6];

            $http({
                method: 'GET',
                url: 'api/City/cities'

            }).then(function success(response) {
                //debugger;
                $scope.City = response.data.Result;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });
        };

        $scope.GetCountry = function () {
            $scope.Country = [6];

            $http({
                method: 'GET',
                url: 'api/Country/Countries'

            }).then(function success(response) {
                //debugger;
                $scope.Country = response.data.Result;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });

        };
        $scope.Id = 0;
        $scope.showProductsCharity = function (TradeId, CategoryId) {

            salewithusService.setuserid(ID);
            window.localStorage.setItem("single_Userid", ID);

            //  $scope.Id = window.localStorage.getItem("UserId");

            $state.go("Need", { 'tradeId': TradeId, 'categoryId': CategoryId }, { reload: true });
            // $state.go("single", {}, { reload: true });

        };



        $scope.usertype_ = 0;
        $scope.showProductsTrade = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);
            salewithusService.setcatid(categoryid);
            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

                $state.go("Trade", { 'tradeId': TradeId, 'categoryId': categoryid }, { reload: true });
                // $state.go("single", {}, { reload: true });

            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };

        $scope.showProductsbycategory = function (CategoryId) {

            salewithusService.setcategoryid(CategoryId);
            window.localStorage.setItem("Category_fp", CategoryId);

            $state.go("Category_filterpage", {}, { reload: true });

        };



        $scope.showRelatedProducts = function (productcatid) {
            salewithusService.setproductcatid(productcatid);

            $state.go("RelatedProduct", {}, { reload: true });


        }

        $scope.GetselectedproductDetailsList = function () {
            $scope.selectedproductDetailsList = [6];

            $scope.procatid = salewithusService.getproductcatid();
            $http({
                method: 'GET',
                url: 'api/Trades/GetselectedproductDetailsList?categoryId=' + $scope.procatid
            }).then(function success(response) {
                //debugger;
                $scope.selectedproductDetailsList = response.data.Result;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );

        }

        $scope.uploadFiles = function () {

            var files = [];
            for (var i = 1; i <= 10; i++) {
                var element = document.getElementById("inputFileToLoad" + i);
                var file = element.files[0];
                files.push(file);
            }
            for (var i = 0, f; f = files[i]; i++) {
                //console.log("out: " + fileName);
                $scope.readF(f);
            }
        }

        $scope.CheckFileExtension = function () {
            if ($('#inputFileToLoad1').val() == "") {
                return true;
            }
            else {
                var ext = $('#inputFileToLoad1').val().split('.').pop().toLowerCase();
                if ($.inArray(ext, ['png', 'jpg', 'jpeg']) == -1) {
                    //alert('invalid extension!');
                    return false;
                }
                else {
                    return true;
                }
            }
        }

        //favourite_code_start

        $scope.likemodel = {
            TradeId: 0,
            UserId: 0,

        }

        $scope.id = 0;
        $scope.uid = 0;

        $scope.LikeDislike = function (TradeId, IsLiked) {
            if (IsLiked) {
                $scope.Getlike(TradeId);
            }
            else {
                $scope.Getdislike(TradeId);
            }

        }


        $scope.Getlike = function (data) {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {

                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasaunfav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        // $(this).removeClass("fa fa-heart");
                        //$(this).addClass("fa fa-heart-o");
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart-o");
                        $scope.Getalltradeafterlogin();
                        $scope.gettradesbycategory();
                        $scope.Getrecommendedtrades();

                        // swal(" Unfavourite !!");

                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };


        $scope.Getdislike = function (data) {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {

                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasafav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        //$("#likebtn").removeClass("fa fa-heart-o");
                        //$("#likebtn").addClass("fa fa-heart");
                        //$("#likebtn").show();
                        //$("#dislikebtn").hide();
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart-o");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart");
                        $scope.Getalltradeafterlogin();
                        $scope.gettradesbycategory();
                        $scope.Getrecommendedtrades();

                        //  swal("Added as a favourite !!");

                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };
        //favourite_code_end


        $scope.onEnterKeyPress = function (event, searchproductName) {
            if (event.charCode == 13) {

                var btn_name = salewithusService.getsarchfortneeds();
                var collegetrade = salewithusService.getcollegetrades();
                if (btn_name != "charityneeds" || btn_name != undefined) {
                    $scope.showSearchProducts(searchproductName);
                }
                else {
                    if (collegetrade == "collegetrades" || collegetrade != undefined) {

                        $scope.showSearchProducts_college(searchproductName);

                    } else {
                        $scope.showSearchProducts_needs(searchproductName);
                    }


                }

            }

        }

       
        $scope.onEnterKeyPress_charity = function (event, searchproductName) {
            if (event.charCode == 13) {

                $scope.showSearchProducts_needs(searchproductName);
            }
          
            }
        $scope.showtrades = function (searchproductName) {

            var btn_name = salewithusService.getsarchfortneeds();
            var collegetrade = salewithusService.getcollegetrades();
            if (btn_name != "charityneeds") {
                $scope.showSearchProducts(searchproductName);
            }
            else {
                if (collegetrade == "collegetrades") {

                    $scope.showSearchProducts_college(searchproductName);

                } else {
                    $scope.showSearchProducts_needs(searchproductName);
                }


            }



        }

        $scope.usertypefb_ = "";
        $scope.Usertype = function (data) {

            $scope.usertypefb_ = window.localStorage.getItem("UserTypeIDfb");
            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid || $scope.usertypefb_ == data) {
                return true;

            }
            else {
                return false;
                //debugger;
                //$scope.userfb(data);
            }

        }
        $scope.userfb = function (data) {
            $scope.usertypefb_ = window.localStorage.getItem("UserTypeIDfb");
            if (data == $scope.usertypefb_) {
                return true;
            }
            else {
                return false;
            }

        }
        $scope.keyword = "";
        $scope.message_ = false;
        $scope.forgot_password = {
            Email: ""
        }
        $scope.fp_alert = function () {
            $("#myModal").hide();
            $scope.keyword = prompt("Please Enter email address.", "");

            if ($scope.keyword !== null) {
                $scope.forgot_password.Email = $scope.keyword;
                //  $scope.validate($scope.forgot_password.Email);
                if ($scope.forgot_password.Email !== "" && $scope.validate($scope.forgot_password.Email)) {
                    salewithusService.forgot_password($scope.forgot_password).then(function (response) {


                        if (response.data.Status == "Success") {

                            swal("Message sent Successfully!!");
                            $("body").css("padding", "0px");
                            $(".modal-backdrop.show").css("opacity", "0");
                            $state.go("index", {}, { reload: true });
                        }
                        else {
                            swal("Something Went Wrong!!");
                        }

                    }, function error(response) {
                        console.log("error");
                    });
                }
                else {
                    $("#myModal").hide();
                    $scope.fp_alert();
                }

            }
            else {

                $state.go("index", {}, { reload: true });
                $("body").css("padding", "0px");
                $(".modal-backdrop.show").css("opacity", "0");
            }
        }


        $scope.validate = function (email) {

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) {

                alert("Invalid Email Address");
                return false;
            }
            else
                return true;
        }


        $scope.showCharity = function (ID) {

            salewithusService.setuserid(ID);
            window.localStorage.setItem("single_Userid", ID);
            //  $scope.Id = window.localStorage.getItem("UserId");

            $state.go("single", {}, { reload: true });
            // $state.go("single", {}, { reload: true });

        };
        $scope.getrelatedproducts = {
            CategoryId: 0,
            SubCategoryId: 0,
            UserId: null,

        }
        $scope.gettradesbycategoryid = [];
        $scope.gettradesbycategory = function () {
            $scope.gettradesbycategoryid = [];

            $scope.getrelatedproducts.CategoryId = salewithusService.getcategoryid();
            //$scope.search_model.CategoryId = window.localStorage.getItem("Category_fp");
            //$scope.getrelatedproducts.CategoryId = 1
            //$scope.search_model.SubCategoryId = salewithusService.getsubcategoryid();
            $scope.getrelatedproducts.SubCategoryId = salewithusService.getsubcategoryid();
            $scope.getrelatedproducts.UserId = window.localStorage.getItem("UserId");

            salewithusService.gettradesbycategoryid($scope.getrelatedproducts).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.gettradesbycategoryid = response.data.Result;
                    //$scope.trades_bycategory = $scope.searchbysubcategory;
                    //$("#divShowSearchProduct").hide();
                    //$("#divShowSearchProductByCategory").show();

                    //window.localStorage.removeItem('searchproductName');
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });

        }



        $scope.showallneeds = function () {
            salewithusService.setsarchfortneeds("charityneeds");
            $state.go("All_needs");
        }

        $scope.collegetrade = function () {
            salewithusService.setcollegetrades("collegetrades");
            $state.go("CollegeTrades");
        }

        //$scope.paymntstatus = {
        //    UserId: "",
        //}
        //$scope.paymentstatus = function () {
        //    $scope.paymntstatus.UserId = window.localStorage.getItem("UserId");
        //    tradeService.checkpaymentstatus($scope.paymntstatus).then(function (response) {
        //        window.localStorage.setItem("Status_", response.data.Result);
        //    }, function error(response) {
        //        console.log("error");
        //    });

        //}
        //$scope.checkpaymentstatus = function () {
        //    $scope.paymentstatus();
        //    var status_ = window.localStorage.getItem("Status_");

        //    if (status_ == "UnSubscribed") {
        //        return false;
        //    }
        //    else {
        //        return true;
        //    }
        //}

        $scope.paymntstatus = {
            UserId: "",
        }
        $scope.checkpaymentstatus = function () {
            $scope.paymntstatus.UserId = window.localStorage.getItem("UserId");
            tradeService.checkpaymentstatus($scope.paymntstatus).then(function (response) {
                //debugger;

                var status_ = response.data.Result;
              
                if (status_ == "UnSubscribed") {

                    $("#managesubscription").hide();
                  
                }

                else {
                    $("#managesubscription").show();
                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.checkselectedusertype = function () {
            if ($("#radio1").is(":checked")) {
               
                return true;
            }
            else {
                return false;
            }
        }

        //Inquiry Start
        $scope.Iquirymodel = {
            Name:"",
            Phone:"",
            Email: "",
            Message:"",
        };

        $scope.SendInquiry = function (Inquirymodel) {
            //debugger;

                //$scope.resendverifycodemodel.Email = window.localStorage.getItem("Emailid");

            salewithusService.SendInquiry(Inquirymodel).then(function (response) {

                    //debugger;
                    if (response.data.Status == "Success") {
                        swal(response.data.Message);
                        
                        ClearInquiryData(Inquirymodel);
                        
                    }
                    else {

                        swal(response.data.Message);

                    }
                });
            }

            //swal("verification code send Successfully!");

        
        function ClearInquiryData(Inquirymodel) {
            //debugger;
            Inquirymodel.Name = "";
            Inquirymodel.Phone = "";
            Inquirymodel.Email = "";
            Inquirymodel.Message = "";

        };

        //Inquiry End


    }]);


}())

;


(function () {

    angular.module('app').controller('PaymentController', ['$http', '$scope', '$location', '$timeout', 'authService', 'tradeService', 'salewithusService', '$rootScope', '$state', '$window', function ($http, $scope, $location, $timeout, authService, tradeService,salewithusService, $rootScope, $state, $window) {

        $scope.Payment_model = {
            UserId: "",
            TransId: "",
            StripeCustID: "",
            CardId: "",
            ExpYear: "",
            ExpMonth: "",
            Cvc: "",
            Payment: "",
            CardHolderName: "",
            ExpThru: "",
            Status: 1,
            NextBillingDate: "",
            Payment_method: "stripe",
            CreatedDateTime: "",
            IpAddress: "",
            CreatedBy: "",
            DeviceType: "",
           Email:""
        }
        $scope.disable = false;
        $scope.CardHolderName = "";
        $scope.Email = "";
        $scope.Status = 1;
        $scope.savepaymentdetails = function () {
            $scope.disable = true;
            $scope.Payment_model.UserId = window.localStorage.getItem("UserId");
            
            $scope.Payment_model.CardId = window.localStorage.getItem("cardID");
            $scope.Payment_model.ExpYear = window.localStorage.getItem("expiration_year");
            $scope.Payment_model.ExpMonth = window.localStorage.getItem("expiration_month");
            $scope.Payment_model.Cvc = window.localStorage.getItem("security_code");
            $scope.Payment_model.CardHolderName = $scope.CardHolderName;
            $scope.Payment_model.Payment = 3000;
            $scope.Payment_model.Email = $scope.Email;
            $scope.Status = tradeService.getstatus();
            tradeService.setpaymentpage("paymnentpage");
          //  var pagename = salewithusService.gettradefrompage();
            var pagename = window.localStorage.getItem("Pagename");
           // console.log("user:" + pagename);
            if ($scope.Status == 2) {
               
               // swal("Users has been subscribed successfully.")
                tradeService.updatepayment($scope.Payment_model).then(function (response) {
                    //debugger;
                   
                    if (response.data.Status == "Success") {

                        alert("Users has been subscribed successfully.")
                        window.close();
                    }

                    else {
                        alert("something went wrong.")
                    }
                   
                }, function error(response) {
                    console.log("error");
                });
              
                if (pagename == "add_trade_detail") {
                //window.close();
                  // $scope.previousdata();
                  // $state.go("add_trade_details");
                }
                else {

                   $state.go("index");
                }
              //  swal("Users has been subscribed successfully.");
            

              //  $state.go("index");
            }
            else {
             

                tradeService.paymentdetails($scope.Payment_model).then(function (response) {
                    //debugger;

                    if (response.data.Status == "Success") {

                        // $state.go("add_trade_details");
                        alert("Users has been subscribed successfully.")
                      //  var pagename = tradeService.gettradefrompage();
                        if (pagename == "add_trade_detail") {
                            window.close();
                           // $state.go("add_trade_details");
                        }
                        else {

                            $state.go("UserProfile");
                        }

                    }
                    else {
                        //$state.go("payment_detail");
                        alert(response.data.Message);
                    }

                }, function error(response) {
                    console.log("error");
                });
            }

         
          
        }

      

        $scope.cancel_model = {
            UserId: "",
           
        }
        $scope.cancelsubscription = function () {
            $scope.cancel_model.UserId = window.localStorage.getItem("UserId");
            tradeService.cancelsubscription($scope.cancel_model).then(function (response) {
               
                if (response.data.Status == "Success") {

                    // $state.go("add_trade_details");
                 
                    swal("You have unsubsribed successfully.");
                    $state.go("index");
                }
                else {

                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.payment_method = "";

        $scope.paymntstatus = {
            UserId: "",
        }
        $scope.checkpaymentstatus = function () {
            $scope.paymntstatus.UserId = window.localStorage.getItem("UserId");
            tradeService.checkpayment($scope.paymntstatus).then(function (response) {
                //debugger;
                
                $scope.payment_method = response.data.Result.Payment_method;
                $("#cardnumber").val(response.data.Result.card_id);
                $("#expdate").val(response.data.Result.exp_thru);
              
                $("#nameoncard").val(response.data.Result.card_holder_name);
               // $("#namecard").val(response.data.Result.card_id);
             
               // tradeService.setstatus(response.data.Result.Status);
                if (response.data.Result.Status == 1)
                {
                    if ($scope.payment_method == "stripe") {
                        $state.go("managesubscription");
                    }
                    else {
                        swal("It seems that you were subscribed from InApp account.Please check InApp to proceed.");
                        $state.go("index");
                    }
                  

                }
              
                else {

                 //swal("You have to subscribe before proceed.")
                    $state.go("payment_detail");
                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.updatepayment_model = {
            UserId: "",
            TransId: "",
            StripeCustID: "",
            CardId: "",
            ExpYear: "",
            ExpMonth: "",
            Cvc: "",
            Payment: "",
            CardHolderName: "",
            ExpThru: "",
            Status: 1,
            NextBillingDate: "",
            Payment_method: "stripe",
            CreatedDateTime: "",
            IpAddress: "",
            CreatedBy: "",
            DeviceType: "",
            Email: ""
        }
        $scope.UpdatePaymentDetails = function () {
            $scope.updatepayment_model.UserId = window.localStorage.getItem("UserId");
            $scope.updatepayment_model.CardId = window.localStorage.getItem("cardID");
            $scope.updatepayment_model.ExpYear = window.localStorage.getItem("expiration_year");
            $scope.updatepayment_model.ExpMonth = window.localStorage.getItem("expiration_month");
            $scope.updatepayment_model.Cvc = window.localStorage.getItem("security_code");
            $scope.updatepayment_model.CardHolderName = $scope.CardHolderName;
            $scope.updatepayment_model.Payment = 3000;
            $scope.updatepayment_model.Email = $scope.Email;
            tradeService.updatepayment($scope.updatepayment_model).then(function (response) {
                //debugger;
              //  $scope.payment_method = response.data.Result.Payment_method;
               // tradeService.setstatus(response.data.Result.Status);
                if (response.data.Status == "Success") {

                    swal("Users has been subscribed successfully.")

                }

                else {

                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.paymntstatus_model = {
            UserId: "",
        }
        $scope.checkstatus = function () {
            $scope.paymntstatus_model.UserId = window.localStorage.getItem("UserId");
            tradeService.checkpayment($scope.paymntstatus_model).then(function (response) {
                //debugger;
               // $scope.payment_method = response.data.Result.Payment_method;
                tradeService.setstatus(response.data.Result.Status);
            

            }, function error(response) {
                console.log("error");
            });

        }

        //$scope.subscribewithpreviousdetail = function () {
        //    if ($('#subscribe_').is(':checked')) {
        //        //$('#email_').attr('disabled', true);
        //        $('#cardnumber').attr('disabled', true);
        //       // $('#expdate').attr('disabled', true);
        //        //$('#secruitycode').attr('disabled', true);
        //        $('#nameoncard').attr('disabled', true);
        //        //$('#nameoncard').attr('disabled', true);
        //      //  $scope.UpdatePaymentDetails();
        //        $scope.paymntstatus.UserId = window.localStorage.getItem("UserId");
        //        tradeService.checkpayment($scope.paymntstatus).then(function (response) {
        //            //debugger;

        //            $scope.payment_method = response.data.Result.Payment_method;
        //            $("#cardnumber").val(response.data.Result.card_id);
        //           // $("#expdate").val(response.data.Result.exp_thru);

        //            $("#nameoncard").val(response.data.Result.card_holder_name);
                 
        //        }, function error(response) {
        //            console.log("error");
        //        });
        //    }
        //    else {
        //        $('#email_').attr('enabled', true);
        //        $('#cardnumber').attr('enabled', true);
        //        $('#expdate').attr('enabled', true);
        //        $('#secruitycode').attr('enabled', true);
        //        $('#nameoncard').attr('enabled', true);
        //        $('#nameoncard').attr('enabled', true);
        //      //  $scope.UpdatePaymentDetails();
        //        $("#cardnumber").val("");
        //        $("#expdate").val("");

        //        $("#nameoncard").val("");
        //    }
        //}

        //$scope.statusforpreviousdetail = function () {
        //    $scope.Status = tradeService.getstatus();
        //    if ($scope.Status == 2) {
        //        return true;
        //    }
        //    else {
        //        return false;
        //    }
        //}
    }]);

}());

var srcData = "";
var srcData3 = "";

function loadImageFileAsURL() {

    var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];

        var fileReader = new FileReader();
       
        fileReader.onload = function (fileLoadedEvent) {
            srcData = fileLoadedEvent.target.result; // <--- data: base64

            //   var divTest = document.getElementById("imgTest");
            //  var newImage = document.createElement('img');
            //newImage.src = srcData;


        }

        fileReader.readAsDataURL(fileToLoad);
    }
}



(function () {
    'use strict';
    angular.module('app').controller('ProfileController', ['$http', '$scope', '$sce', '$state', '$stateParams', '$location', 'authService', 'salewithusService', 'tradeService', 'chatService', '$window', 'toaster', function ($http, $scope, $sce, $state, $location, $stateParams, authService, salewithusService, tradeService, chatService, $window, toaster) {
       
        $(".modal-open").css("overflow", "scroll");
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;

        $scope.TradeID = 0;
        $scope.userid = "";
        $scope.ID = 0;
        $scope.TradesByUserId = [];
        $scope.deleteTrade = [];
        $scope.fetchedUserId = "";
        $scope.resetpasswordcodefromurl = $stateParams.$$search.resetcode;
        $(".modal-backdrop").css("display", "none");
        

        // $scope.setUsername();
      
        $scope.CheckLogin = function () {
            var UserId = window.localStorage.getItem('UserId');
            var Username = window.localStorage.getItem('userName');
            if (UserId == null) {
                $state.go("index");
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",

                });
            }
            else {
            }
        };
      
        $scope.srcData1 = "";
        $scope.srcData_new="";
        $scope.stepsModel = [];
        $scope.scrt = [];
        $scope.showMsgs_ = false;

        $scope.imageUpload = function (event) {
            var files = event.target.files; //FileList object
            
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                var reader = new FileReader();
                reader.onload = $scope.imageIsLoaded;
                reader.readAsDataURL(file);
            }
            
        }

        $scope.imageIsLoaded = function (e) {
            $scope.$apply(function () {
                $scope.stepsModel.push(e.target.result);
            });
        }

        $scope.loadImageFileAsURL1 = function () {
            var filesSelected = document.getElementById("inputFileToLoad1").files;
            if (filesSelected.length > 0) {
                var fileToLoad = filesSelected[0];

                var fileReader = new FileReader();

                fileReader.onload = function (fileLoadedEvent) {
                    srcData1 = fileLoadedEvent.target.result
                    console.log("srcdata:" + srcData1);
                    // $srcData.push(fileLoadedEvent.target.result);
                }

                fileReader.readAsDataURL(fileToLoad);
            }

        }
      
        //$scope.charityimageupload = function () {
        //    //debugger;
        //    var filesSelected = document.getElementById("charityimageupload").files;
        //    if (filesSelected.length > 0) {
        //        var fileToLoad = filesSelected[0];

        //        var fileReader = new FileReader();

        //        fileReader.onload = function (fileLoadedEvent) {
        //             srcData_new = fileLoadedEvent.target.result
        //            // $srcData.push(fileLoadedEvent.target.result);
        //        }

        //        fileReader.readAsDataURL(fileToLoad);
        //    }

        //}
        
        $scope.showRelatedProducts = function (productcatid) {
            salewithusService.setproductcatid(productcatid);

            $state.go("RelatedProduct", {}, { reload: true });


        }

        //favourite_code_start
        $scope.likemodel = {
            TradeId: 0,
            UserId: 0,

        }

        $scope.id = 0;
        $scope.uid = 0;

        $scope.LikeDislike = function (TradeId, IsLiked) {
            if (IsLiked) {
                $scope.Getlike(TradeId);
            }
            else {
                $scope.Getdislike(TradeId);
            }

        }
        $scope.Getlike = function (data) {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {
               
                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasaunfav($scope.likemodel).then(function (response) {

                    if (response.data.Status == "Success") {
                        //$("#likebtn").hide();
                        //$("#dislikebtn").show();
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart-o");
                      // $scope.GetFavouriteListByUserid();
                        $scope.GetFavouriteListByUserid();
                        $scope.GetTradeByUserId();
                      //  swal(" unfavourite !!");
                       
                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };


        $scope.Getdislike = function (data) {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {
               
                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasafav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        //$("#likebtn").show();
                        //$("#dislikebtn").hide();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart-o");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart");
                       // $scope.GetFavouriteListByUserid();
                        $scope.GetFavouriteListByUserid();
                        $scope.GetTradeByUserId();
                       // swal("Added as a favourite !!");
                 
                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };

        $scope.favouritemodel = {
            UserId: 0,
        }
        $scope.GetFavouriteListByUserid = function () {
            $.LoadingOverlay("show");
            $scope.Favourite = [6];
            $scope.favouritemodel.UserId = window.localStorage.getItem('UserId');

            salewithusService.favouritelist($scope.favouritemodel).then(function (response) {
                //debugger;

                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide");

                    //swal("Added as a favourite !!");
                    $scope.Favourite = response.data.Result;
                }
                else {
                    swal("Something Went Wrong!!");

                }

            }, function error(response) {
                console.log("error");
            });
        }


        $scope.showProductsTrade_up = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);
            salewithusService.setcatid(categoryid);
            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {
                if ($scope.usertype_ == 1) {
                    $state.go("Trade", { 'tradeId': TradeId, 'categoryId': categoryid}, { reload: true });
                    // $state.go("single", {}, { reload: true });
                }
              
                else {
                    $state.go("Need", { 'tradeId': TradeId, 'categoryId': categoryid}, { reload: true });
                }
            }
            else {
                $state.go("index", {}, { reload: true });
            }

        };

        
        

        $scope.usertype_ = 0;
        $scope.showProductsTrade_fav = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);
            salewithusService.setcatid(categoryid);
            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
           
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

                $state.go("Trade", { 'tradeId': TradeId, 'categoryId': categoryid}, { reload: true });
                // $state.go("single", {}, { reload: true });

            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };
        //favourite_code_end

   
        $scope.logout = function () {

            window.localStorage.removeItem('UserId');
            window.localStorage.removeItem('userName');
           // window.localStorage.removeItem('UserImage');

            swal({
                title: "Success!",
                text: "Log Out Succesfull!",
                icon: "success",
                button: "Ok!",
            });
            $state.go("index");
        };

        //$scope.setUsername = function () {


        //    $(".Username").text(window.localStorage.getItem('UserName'));
        //    //$(".Userimage").url(window.localStorage.getItem('UserImage'));
        //};
        $scope.getcountrycode = [];
        $scope.userid = "";
       
     
        $scope.selectedCountrycode = "";
        $scope.GetCountrycode = function () {
          

            //debugger;
            $scope.Allcountrycode = [];


            $http({
                method: 'GET',
                url: 'api/Country/GetCountryCodes'
            }).then(function success(response) {
                //debugger;
                $scope.Allcountrycode = response.data.Result;
                // $scope.Allcountrycode = response.data.Result.code;
                // $scope.countryid.push(0);
                for (var i = 0; i < $scope.Allcountrycode.length; i++) {

                    var obj = $scope.Allcountrycode[i];

                    $scope.getcountrycode.push($scope.Allcountrycode[i].code);

                }

                console.log("countrycode " + $scope.getcountrycode[0]);
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );
        }

        $scope.user_model = {
            UserId:null
        }
        $scope.UserData = [];
        $scope.str = "";
        $scope.Resetpasscode = "";
        $scope.GetUserData = function () {

            $scope.UserData = [];
            $scope.UserTypeId = [];
            //debugger;

          //  if($scope.checkfacebookId() == true){
          //       $scope.user_model.UserId = window.localStorage.getItem("UserIdfb");
          //  }else{
          //$scope.user_model.UserId = window.localStorage.getItem("UserId");
          //  }

            $scope.user_model.UserId = window.localStorage.getItem("UserId");
          
            
            salewithusService.userdata_($scope.user_model).then(function success(response) {
                console.log(response.data.Result);
                //debugger;
                $scope.UserData = response.data.Result;
               // $scope.Resetpasscode = response.data.Result.ResetPasswordCode;
                if (response.data.Result.FacebookId == null || response.data.Result.FacebookId == "" ) {
                    $scope.str = response.data.Result.PhoneNumber;
                    console.log("str:" + $scope.str);
                    var txtphn = $scope.str.split("-");
                    console.log("str33:" + txtphn);
                    $scope.selectedCountrycode = txtphn[0];
                }
                else {
                    var txtphn = "";
                }
             
                //var phn = str.slice(5, 15);
                //var code = str.slice(0, 4);
            
                $scope.UserTypeId = response.data.Result.UserTypeId;
                $scope.u_img = response.data.Result.UserImage;
                window.localStorage.setItem('UserImage_update', response.data.Result.UserImage);
                $scope.userimage = $sce.trustAsHtml('<img src="' + $scope.u_img + '" id="photo-id" style="width:75px;height:75px;"  >');
                window.localStorage.setItem('UserTypeId', response.data.Result.UserTypeId);
              
                window.localStorage.setItem('Emailid_nw', response.data.Result.Email);
                window.localStorage.setItem('verify', response.data.Result.IsVerified);
                if ($scope.UserTypeId == 1) {
                    $scope.UserTypeId = "User";

                    $("#Cneeds").hide();
                    $("#Cname").hide();
                    $("#Cdiscription").hide();
                    $("#charitydata").hide();
                  
                    //$("#charityimageupload").hide();                                    
                }
                else {
                    $scope.UserTypeId = "Charity";
                    //$("#inputFileToLoad1").hide();
                    $("#fname").hide();
                    $("#lname").hide();
                    $("#Cname").show();
                    $("#Cdiscription").show();
                    $("#charitydata").show();
                  
                }

                $("#usertype").val($scope.UserTypeId);
                $("#inptname").val($scope.UserData.FirstName);
                $("#middlename").val($scope.UserData.MiddleName);
                $("#lastname").val($scope.UserData.LastName);
                if (txtphn.length == 1) {
                    if (response.data.Result.FacebookId == null || response.data.Result.FacebookId == "" ) {
                        $("#phone").val($scope.UserData.PhoneNumber);
                    }
                    else {
                        $("#phone").hide();
                    }
                   // $("#code").val(txtphn[0]);
                  

                }
                else {
                    if (response.data.Result.FacebookId == null || response.data.Result.FacebookId == "") {
                        $("#code").val(txtphn[0]);
                        $("#phone").val(txtphn[1]);
                    }
                    else {
                        $("#code").hide();
                        $("#phone").hide();
                    }
                }
                //debugger;
                $("#inptemail").val($scope.UserData.Email);
                $("#inptaddress").val($scope.UserData.AddressLine1);
                $("#inptaddress2").val($scope.UserData.AddressLine2);
                $("#username").val($scope.UserData.UserName);
                $("#passwrd").val($scope.UserData.Password);
                $("#createddate").val($scope.UserData.CreatedDateTime);
                $("#zipcode").val($scope.UserData.Zipcode);
                $("#verified").val($scope.UserData.IsVerified);
                $("#longitude").val($scope.UserData.Longitude);
                $("#Latitude").val($scope.UserData.Latitude);
                $("#charityname").val($scope.UserData.FirstName);
                $("#university").val($scope.UserData.CollegeName);
                $("#universityid").val($scope.UserData.CollegeId);
                $("#countryname").val($scope.UserData.CountryName);
                $("#countryID").val($scope.UserData.CountryId);
                if ($scope.UserTypeId !== 1) {
                    $("#charityname").val().show();
                    $("#userdata").hide();
                }
                else {
                    $("#charityname").hide();
                    $("#userdata").show();
                }

                $scope.GetUserData();

            },
                function error(response) {

                    console.log("error");
                    // this function will be called when the request returned error status
                });
        }
        
        $scope.checkfacebookId = function () {
            //debugger;
            var facbookid = window.localStorage.getItem("FacebookId");
            if (facbookid == null)
            {
                return true;

            }
            else {
                return false;
            }
        }

        $scope.verify = false;
        $scope.check_ = function () {
            $scope.verify = window.localStorage.getItem("verify");
            if ($scope.verify == "false") {
               
                return true;
            }
            else {
                return false;
            }
        }

        $scope.check_mail = function (data) {
            if (data == "") {
                data = window.localStorage.getItem("UserName");
                if (data != null || data != undefined) {
                    if (data.includes(".edu")) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
            else {
                if (data != null || data != undefined) {
                    if (data.includes(".edu")) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
          
        }


        $scope.paymntstatus = {
            UserId: "",
        }
        $scope.checkpaymentstatus = function () {
            $scope.paymntstatus.UserId = window.localStorage.getItem("UserId");
            tradeService.checkpayment($scope.paymntstatus).then(function (response) {
                //debugger;

                if (response.data.Result == "Paid") {

                    $state.go("UserProfile");

                }
                else {

                    if (confirm('Looking to new trade? You can add new trades by getting a monthly subscription of $4.99 and the subscription will be renewed automatically each month.')) {
                        // Save it!
                        // Cleardata(trademodel);
                        // $('#rateperhour').removeAttr('checked');
                        // $("#uploadimages_").show();
                        $state.go("payment_detail");
                    }
                    else {
                        $state.go("index");
                    }

                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.GetEditTrade = function (data, categoryid) {
            $.LoadingOverlay("show"); 
            $scope.EditTrade = [];
            //tradeService.posttradedata($scope.trademodel).then(function (response)
           // $scope.ID = window.localStorage.getItem("UserId");
            $scope.ID = data
            $scope.categoryid = categoryid;
            salewithusService.setcatidfrommytrades(categoryid);
            $http({
                method: 'GET',
                url: 'api/Trades/GettradesByTradeid?TradeId=' + $scope.ID
            }).then(function success(response) {
                
                if (response.data.Status == "Success") {
                    
                    window.localStorage.setItem("TradeId", response.data.Result[0].TradeId);
                    $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                    if ($scope.usertype_ == 1) {
                      //  $state.go("edit_Trade", { 'tradeId': data, 'categoryId': CategoryId });
                        $state.go("edit_Trade", { reload: true });
                    }
                    else {
                       // $state.go("edit_charity");
                        $state.go("edit_charity", { reload: true });
                    }
                    
                }
                else {
                    $.LoadingOverlay("hide"); 
                }
            });

        };
        
        
      

        $scope.deleteaddedtrade = {
            TradeId: 0,
           
        }
        $scope.GetdeleteTrade = function (data) {

            $scope.deleteaddedtrade.TradeId = data;

            salewithusService.deleteaddedtrade($scope.deleteaddedtrade).then(function (response) {


                if (response.data.Status == "Success") {
                    //$window.location.reload();
                    $scope.GetTradeByUserId();
                    swal("Trade Deleted Successfully!!");
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        };
        
     

        $scope.GetSaveChanges = function () {

            $scope.SaveChanges = [6];
            $scope.userid = window.localStorage.getItem('UserId');
            $http({
                method: 'POST',
                url: 'api/Users/UpdateUserProfile' + $scope.userid

            }).then(function success(response) {

                if (response.data.Status == "Success") {
                    swal(response.data.Message);
                    //debugger;
                    Cleardata();

                    window.localStorage.setItem("UserId", response.data.Result.UserId);
                    //$state.go("Index");
                }
                else {
                    swal(response.data.Message);
                }



                //debugger;
                // $scope.State = response.data.Status;
                // },
                // function error(response) {
                // console.log("error");
                // this function will be called when the request returned error status
            });


        };

        /* Update User Profile starts */

        $scope.editprofile = {

            UserId: 0,
            FirstName: "",
            MiddleName: "",
            LastName: "",
            Email: "",
            PhoneNumber: "",
            AddressLine1: "",
            AddressLine2: "",
            CityId: null,
            StateId: null,
            CountryId: null,
            Zipcode: "442200",
            Longitude: 0.0,
            Latitude: 0.0,
            UserTypeId: "",
            UserName: "",
            Password: "",
            CreatedDateTime: "2019-12-03 15:29:22.183",
            CreatedBy: "",
            IsActive: false,
            IsDeleted: false,
            IsVerified: false,
            IpAddress: "",
            App_Token: "",
            UserImage: "",
            Device_Type: "",
            Device_Id: "",
            Gender: "",
            Firebase_token: "",
            One_signal_key: "",
            CollegeId: null,
            ResetPasswordCode: ""
            

        };
        //code_university_start//
        $scope.CollegeId = 0;
        $scope.StartsWith = "";
        $scope.university_model = {
            StartsWith: ""
        }

        $scope.getuniversity = function (StartsWith) {
            $("#list").show();
            $scope.university = [];
            $scope.university_model.StartsWith = StartsWith;
            salewithusService.university($scope.university_model).then(function (response) {


                if (response.data.Status == "Success") {

                    // swal("Updated Successfully!!");
                    $scope.university = response.data.Result;
                    $scope.CollegeId = salewithusService.setcollegeid(response.data.Result.CollegeId);

                }
                else {
                    //  swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }
        $scope.fillTextbox = function (data, collegeid) {
            $scope.StartsWith = data;
            window.localStorage.setItem("CollegeId", collegeid);
            $scope.university = null;
            $("#list").hide();
        }
        //code_university_end//
      
        $scope.selectedCountry = 0;
        $scope.UpdateData = function (editprofile) {
         //  $scope.selectedCountrycode = selectedCountrycode;
          
           
            if (editprofile.CountryId != null) {
                $scope.editprofile.CountryId = $scope.selectedCountry;
               
            }
            else {
                $scope.editprofile.CountryId = $("#countryID").val();

            }
            //debugger;

            /* code to fetch userid */
            var facebookid = window.localStorage.getItem("FacebookId");
           
                $scope.editprofile.UserId = window.localStorage.getItem('UserId');
         
            /* code to fetch userid */

            /* code to fetch FirstName */

            if (editprofile.FirstName != "") {

                $scope.editprofile.FirstName = editprofile.FirstName;
            }
            else {
                $scope.editprofile.FirstName = $("#inptname").val();

            }

            /* code to fetch FirstName */

            /* code to fetch MiddleName */

            if (editprofile.MiddleName != "") {

                $scope.editprofile.MiddleName = editprofile.MiddleName;
            }
            else {
                $scope.editprofile.MiddleName = $("#middlename").val();
            }

            /* code to fetch MiddleName */

            /* code to fetch LastName */

            if (editprofile.LastName != "") {
                $scope.editprofile.LastName = editprofile.LastName;
            }
            else {

                $scope.editprofile.LastName = $("#lastname").val();

            }

            /* code to fetch LastName */

            /* code to fetch Email */

            if (editprofile.Email != "") {

                $scope.editprofile.Email = editprofile.Email;

            }
            else {
                $scope.editprofile.Email = $("#inptemail").val();
            }
          

            /* code to fetch Email */

            /* code to fetch PhoneNumber */

            if (editprofile.PhoneNumber == "" || editprofile.PhoneNumber == undefined) {
             
                if (facebookid == null)
                {
                    $scope.editprofile.PhoneNumber = $scope.selectedCountrycode + "-" + $("#phone").val();
                }
                else {
                    $scope.editprofile.PhoneNumber = "";
                }
              
            }
            else {
                if (facebookid == null) {
                    $scope.editprofile.PhoneNumber = $scope.selectedCountrycode + "-" + editprofile.PhoneNumber;
                }
                else {
                    $scope.editprofile.PhoneNumber = "";
                }
               

            }

            /* code to fetch PhoneNumber */

            /* code to fetch AddressLine1 */

            if (editprofile.AddressLine1 != "") {

                $scope.editprofile.AddressLine1 = editprofile.AddressLine1;

            }
            else {
                $scope.editprofile.AddressLine1 = $("#inptaddress").val();
            }

            /* code to fetch AddressLine1 */
           
            
            /* code to fetch AddressLine2 */

            if (editprofile.AddressLine2 != "") {
                $scope.editprofile.AddressLine2 = editprofile.AddressLine2;

            }
            else {

                $scope.editprofile.AddressLine2 = $("#inptaddress2").val();
            }

            /* code to fetch AddressLine2 */

            //$scope.editprofile.CityId = editprofile.CityId;
            //$scope.editprofile.StateId = editprofile.StateId;
            //$scope.editprofile.CountryId = editprofile.CountryId;

            //$scope.editprofile.Zipcode = editprofile.Zipcode;
            if (editprofile.Zipcode != "") {
                $scope.editprofile.Zipcode = editprofile.Zipcode;

            }
            else {

                $scope.editprofile.Zipcode = $("#zipcode").val();
            }

            if (editprofile.Longitude != "") {
                $scope.editprofile.Longitude = editprofile.Longitude;

            }
            else {

                $scope.editprofile.Longitude = $("#longitude").val();
            }
            if (editprofile.Latitude != "") {
                $scope.editprofile.Latitude = editprofile.Latitude;

            }
            else {

                $scope.editprofile.Latitude = $("#Latitude").val();
            }
            if (editprofile.Email.includes(".edu")) {
                if ($scope.editprofile.CollegeId == ""){
                  
                 
                    $scope.editprofile.CollegeId = $("#universityid").val();
                }
                else {
                    $scope.editprofile.CollegeId = window.localStorage.getItem("CollegeId");
                }
            }
           
            else {

                $scope.editprofile.CollegeId = null;
            }

            
            //$scope.editprofile.Longitude = editprofile.Longitude;
            //$scope.editprofile.Latitude = editprofile.Latitude;
            $scope.editprofile.UserTypeId = window.localStorage.getItem('UserTypeId');
            if ($scope.editprofile.UserTypeId == 1) {
                $scope.editprofile.UserTypeId = 1;
                $('#charityname').hide();
                $('#charitydiscription').hide();
                $('#charityneeds').hide();
            }
            else {
                $scope.editprofile.UserTypeId = 3;
                $('#charityname').val();
                $('#charitydiscription').val();
                $('#charityneeds').val();
                $('#cdatetime').val();
            }

            if ($scope.editprofile.UserTypeId == 3) {


                $scope.savecharitydata();

            }
            else {

            }


            /* code to fetch UserName */

            if (editprofile.UserName != "") {
                $scope.editprofile.UserName = editprofile.UserName;

            }
            else {

                $scope.editprofile.UserName = $("#username").val();
            }

            /* code to fetch UserName */

            /* code to fetch Password */

            if (editprofile.Password != "") {
                $scope.editprofile.Password = editprofile.Password;

            }
            else {

                $scope.editprofile.Password = $("#passwrd").val();
            }

            /* code to fetch Password */
            if (editprofile.CreatedDateTime != "") {
                $scope.editprofile.CreatedDateTime = editprofile.CreatedDateTime;

            }
            else {

                $scope.editprofile.CreatedDateTime = $("#createddate").val();
            }
            //$scope.editprofile.CreatedDateTime = editprofile.CreatedDateTime;
            //$scope.editprofile.CreatedBy = editprofile.CreatedBy;
            //$scope.editprofile.IsActive = editprofile.IsActive;
            //$scope.editprofile.IsDeleted = editprofile.IsDeleted;
            //$scope.editprofile.IsVerified = editprofile.IsVerified;
            //$scope.editprofile.IpAddress = editprofile.IpAddress;
            //$scope.editprofile.App_Token = editprofile.App_Token;

          //  $scope.editprofile.ResetPasswordCode = $scope.Resetpasscode;
            /* code to fetch UserImage */

           // $scope.editprofile.UserImage = srcData1.substr(srcData1.indexOf(',') + 1);
            $scope.editprofile.UserImage = srcData1.substr(srcData1.indexOf(',') + 1);

            /* code to fetch UserImage */

            //$scope.editprofile.Device_Type = editprofile.Device_Type;
            //$scope.editprofile.Device_Id = editprofile.Device_Id;
            //$scope.editprofile.Gender = editprofile.Gender;
            //$scope.editprofile.Firebase_token = editprofile.Firebase_token;
            //$scope.editprofile.One_signal_key = editprofile.One_signal_key;
            //$scope.editprofile.ResetPasswordCode = editprofile.ResetPasswordCode;

            /* code to send profile data to update */
            if ($scope.editprofile.Email != "") {

                if ($scope.editprofile.PhoneNumber != null) {

                    salewithusService.Updated($scope.editprofile).then(function (response) {

                        
                        tradeService.setpagenameedit("editprofile");
                        if (response.data.Status == "Success") {

                            swal("Updated Successfully!!");
                         
                            $state.go("ShowUserDetails");
                           
                            $scope.editprofile.CollegeId = window.localStorage.removeItem("CollegeId");
                        }
                        else {
                            swal("Something Went Wrong!!");
                        }

                    }, function error(response) {

                        console.log("error");

                    });
                }
                else {
                    $scope.showMsgs = true;
                }
            }
            else {
                $scope.showMsgs_ = true;
            }

            /* code to send profile data to update */

        };

    
        $scope.Charitymodel = {
           
        UserId :0,                                                  
        FirstName:"",
        LastName: "",
        Email:"",
        PhoneNumber:"",
        AddressLine1:"",
        AddressLine2:"",
        Zipcode:"",        
        UserTypeId:0,
        UserName:"",
        Password:"",
        UserImage: "",
        Device_Id: "",
       Device_Type:"",
        One_signal_key:"",
        Firebase_token: "",
        Longitude:"",
        Latitude :"" ,
        CreatedDateTime:"2019-11-28 05:44:10.020",
        CharityId: 0,
        CharityName:"",
       Description: "",
        Needs:""
        }

        $scope.savecharitydata = function () {
            $scope.Charitymodel.CharityId = window.localStorage.getItem('CharityId');
            $scope.Charitymodel.UserId = window.localStorage.getItem('UserId');
           $scope.Charitymodel.FirstName = $("#inptname").val();
           $scope.Charitymodel.LastName = "";
            $scope.Charitymodel.Email = $("#inptemail").val();
            $scope.Charitymodel.Password = $("#passwrd").val();
            $scope.Charitymodel.PhoneNumber = $scope.selectedCountrycode + "-" + $("#phone").val();
           $scope.Charitymodel.AddressLine1 = $("#inptaddress").val();
      $scope.Charitymodel.AddressLine2 = $("#inptaddress2").val();
           $scope.Charitymodel.Zipcode = $("#zipcode").val();
          
                $scope.Charitymodel.Longitude = $("#longitude").val();
         
                $scope.Charitymodel.Latitude = $("#Latitude").val();
        
            $scope.Charitymodel.UserTypeId = window.localStorage.getItem('UserTypeId');
           
            $scope.Charitymodel.CharityName = $('#charityname').val();
            $scope.Charitymodel.Description = $('#charitydiscription').val();
            $scope.Charitymodel.Needs = $('#charityneeds').val();
          
           
                $scope.Charitymodel.CreatedDateTime = $("#cdatetime").val();

       
            $scope.Charitymodel.UserImage = srcData1.substr(srcData1.indexOf(',') + 1);
           
           
            salewithusService.Addcharity($scope.Charitymodel).then(function (response) {


                if (response.data.Status == "Success") {

                    // swal("Updated Successfully!!");

                }
                else {
                    //  swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.ShowSpinnerStatus = true;

        $scope.ShowSpinner = function () {
            $scope.ShowSpinnerStatus = true;
        };
        $scope.HideSpinner = function () {
            $scope.ShowSpinnerStatus = false;
        };
        $scope.usertype = 0;
        $scope.gettradesmodel = {
           
            UserId:"",
          
        }
        
        $scope.GetTradeByUserId = function () {
            $.LoadingOverlay("show"); //paras
           
            $scope.TradeByUserId = [];
            //debugger;
           
            $scope.gettradesmodel.UserId = window.localStorage.getItem('UserId');
           
                tradeService.gettrades($scope.gettradesmodel).then(function (response) {
                    //debugger;

                    if (response.data.Status == "Success") {
                        $.LoadingOverlay("hide");
                        $scope.TradeByUserId = response.data.Result;
                        //$.LoadingOverlay("hide");
                        //$scope.HideSpinner();
                        //if (response.data.Result[0].IsSold == true) {
                        //    $("#soldimage").show();
                        //}
                        //else {
                        //    $("#soldimage").hide();
                        //}
                        $.LoadingOverlay("hide");
                    }
                    else {
                        swal("Something Went Wrong!!");

                    }

                }, function error(response) {
                    console.log("error");
                });

        }


        $scope.Trademodel = {
            TradeId: 0,
            TradeImages:[],
        }

        $scope.Getimages = function () {
            $scope.Tradeimage = [6];
            //debugger;
            $scope.Trademodel.TradeId = window.localStorage.getItem('TradeId');

            salewithusService.gettradeimages($scope.Trademodel).then(function (response) {
                //debugger;

                if (response.data.Status == "Success") {
                    //swal("Added as a favourite !!");
                    $scope.Tradeimage = response.data.Result;
                   
                }
                else {
                    swal("Something Went Wrong!!");

                }

            }, function error(response) {
                console.log("error");
            });
        }
        $scope.procatid = "";
       

        //charity__Start//
        $scope.GetCharityByUserId = function () {
            $scope.CharityByUserId = [];
            //debugger;
            $scope.procatid = window.localStorage.getItem('UserId');
            $http({
                method: 'GET',
                url: 'api/Charity/GetCharityByUserId?UserId=' + $scope.procatid
            }).then(function success(response) {
                //debugger;
                $scope.CharityByUserId = response.data.Result;
                //  $("#charityname").val($scope.UserTypeId);
              
                $("#charityname").val($scope.CharityByUserId[0].CharityName);
                $("#charitydiscription").val($scope.CharityByUserId[0].Description);
                $("#cdatetime").val($scope.CharityByUserId[0].CreatedDateTime);
                $("#fileuploadcharity").val($scope.CharityByUserId[0].CharityImage);
                $("#charityneeds").val($scope.CharityByUserId[0].Needs);
                window.localStorage.setItem('CharityId', response.data.Result[0].CharityId)
            },
                function error(response) {

                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );

        }

        $scope.GetAllProductsCategory = function () {
            $.LoadingOverlay("show"); //paras\
            //debugger;
            $scope.AllProductsCategory = [];


            $http({
                method: 'GET',
                url: 'api/Category/GetCategoryList'

            }).then(function success(response) {
                //debugger;
                $.LoadingOverlay("hide"); //paras\
                $scope.AllProductsCategory = response.data;
                window.localStorage.setItem('CategoryId', response.data.CategoryId);

                for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

                    if (i < 6) {
                        $scope.Categorylist2.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 6 && i < 12) {
                        $scope.Categorylist3.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 12 && i < 18) {
                        $scope.Categorylist4.push($scope.AllProductsCategory[i]);

                    }

                }


            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                    // this function will be called when the request returned error status
                });


        };
        $scope.subid = 0;


        $scope.AllSubCategory2 = [];
        $scope.GetAllSubCategory = function () {

            var selectedCategoryId = $scope.selectedCategory;//$scope.subid = data;
            $scope.subid = selectedCategoryId;
            //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllSubCategory = response.data.Result;

                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        if (obj.Subcategories.length > 0) {
                            $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                        }
                        else {
                            $('#SubCategoryList').hide();
                            swal({
                                text: "No Subcategories are available for this category.",
                                button: "Ok!",
                            });
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });


        };
        $scope.charity_message = false;
        $scope.charity_message_ = false;
        $scope.Charity={
            UserId:null,
            CharityName: "",
            Description: "",
          
          
          
            Needs: "",
        }
        $scope.AddCharityNeeds = function (Charity) {
            $scope.Charity.UserId = window.localStorage.getItem('UserId');
            $scope.Charity.CharityName = Charity.CharityName;
            $scope.Charity.Description = Charity.Description;
          
            //if ($scope.Charity.CreatedDateTime != "") {
            //    $scope.Charity.CreatedDateTime = Charity.CreatedDateTime;

            //}
            //else {

            //    $scope.Charity.CreatedDateTime = $("#cdatetime").val();
            //}
          
            $scope.Charity.Needs = Charity.Needs;
            //  $scope.Charity.CharityImage = srcData3.substr(srcData3.indexOf(',') + 1);
            if ($scope.Charity.CharityName || $scope.Charity.Needs !== "") {

                if ($scope.Charity.Needs !== "") {
                    salewithusService.charityneeds($scope.Charity).then(function (response) {
                        //debugger;

                        if (response.data.Status == "Success") {
                           
                            swal("Submitted Successfully !!");
                            $state.go("index");

                        }
                        else {
                            swal("Something Went Wrong!!");

                        }

                    }, function error(response) {
                        console.log("error");
                    });
                }
                else {
                    $scope.charity_message_ = true;
                }
            }
            else {
                $scope.charity_message = true;
            }

        }

        //charity__end//


        //markedassold_start//
        $scope.Marked_sold_unsold = function (tradeid, userid,IsSold) {
            if (IsSold) {
                $scope.markedasUnsold(tradeid, userid, IsSold);
            }
            else {
              
                $scope.markedassold(tradeid, userid, IsSold);
            }

        }

        $scope.markedassold_model = {
            TradeId:0,
            UserId: 0
        }
        $scope.markedassold = function (tradeid, userid, IsSold) {
            $scope.markedassold_model.TradeId = tradeid;
            $scope.markedassold_model.UserId = userid;
            salewithusService.marked_sold($scope.markedassold_model).then(function (response) {
                //debugger;

                if (response.data.Status == "Success") {
                    $("#soldimage").show();
                    $("#soldunsold_" + $scope.markedassold_model.TradeId).removeClass("sold_icon.png");
                    $("#soldunsold_" + $scope.markedassold_model.TradeId).addClass("Unsold_icon.png");
                    $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                    if ($scope.usertype_ == 1) {
                        swal("Marked as agreement reached !!");
                        $scope.GetTradeByUserId();
                    }
                    else {
                        swal("Marked as renew !!");
                        $scope.GetTradeByUserId();
                    }
                    //$scope.GetTradeByUserId();
                }
                else {
                    swal("Something Went Wrong!!");

                }

            }, function error(response) {
                console.log("error");
            });
        }
        //markedassold_end//
        
        $scope.markedasUnsold = function (tradeid, userid, IsSold) {
            $scope.markedassold_model.TradeId = tradeid;
            $scope.markedassold_model.UserId = userid;
            salewithusService.marked_unsold($scope.markedassold_model).then(function (response) {
                //debugger;

                if (response.data.Status == "Success") {
                 
                    $("#soldimage").hide();
                    $("#sold").hide();
                    $("#unsold").show();
                    $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                    if ($scope.usertype_ == 1) {
                        swal("Marked As renew !!");
                        $scope.GetTradeByUserId();
                    }
                    else {
                        swal("Marked as agreement reached !!");
                        $scope.GetTradeByUserId();
                    }
                   
                }
                else {
                    swal("Something Went Wrong!!");

                }

            }, function error(response) {
                console.log("error");
            });
        }

        $scope.IsLoggedInUser = function (fromUserId) {
            var loggedinUserId = window.localStorage.getItem('UserId');
            if (fromUserId == loggedinUserId)
                return true;
            else
                return false;
        };

        //reset_password//
        $scope.ConfirmPassword = "";
        $scope.resetpassword = {
            UserId: "",
            Password: "",
            ResetPasswordCode:""

        }
        $scope.showMsgs = false;
        $scope.isDisabled = false;

        $scope.showPassword = false;

        $scope.toggleShowPassword = function () {
            $scope.showPassword = !$scope.showPassword;
        }


        $scope.savepassword = function (resetpassword) {
           
           $scope.resetpassword.UserId = window.localStorage.getItem("UserId");
            //$scope.resetpassword.UserId =2226;
            $scope.resetpassword.Password = resetpassword.NewPassword;
            $scope.resetpassword.ResetPasswordCode = $scope.resetpasswordcodefromurl;
            //$scope.resetpassword.Password = $scope.ConfirmPassword;
            if ($scope.resetpassword.Password == $scope.ConfirmPassword) {

                salewithusService.reset_password($scope.resetpassword).then(function (response) {


                    if (response.data.Status == "Success") {
                      
                        swal("Your new password has been changed successfully.");
                     
                        $scope.Cleardata();
                      
                      //  $state.go("ResetPassword");
                        $("body").css("padding", "0px");
                        $("#my_password").hide();

                    }
                    else {
                        //  swal("Something Went Wrong!!");
                    }

                    $scope.isDisabled = true;

                }, function error(response) {
                    console.log("error");
                });

            }
            else {
                $scope.showMsgs = true;
            }
        }
        $scope.Cleardata = function () {
            $scope.resetpassword.UserId = "";
            //$scope.resetpassword.UserId =2226;
            $scope.resetpassword.Password = "";
            $scope.resetpassword.ResetPasswordCode = "";
        }

        $scope.cancel = function () {
            $("#my_password").hide();
            $state.go("edit_profile", {}, { reload: true });
        }
        //reset_password//

        //verification//

        $scope.SaveTempData = function () {

            $("#verifymodal").modal('show');
        }

        $scope.verifycodemodel = {

            Email: "",
            ActivationCode: ""
        };

        $scope.Verifycode = function (verifycodemodel) {

            if (verifycodemodel.ActivationCode == "") {

                swal("please enter verification code!");
            }
            else {

               
                $scope.verifycodemodel.Email = window.localStorage.getItem("Emailid_nw");
                $scope.verifycodemodel.ActivationCode = verifycodemodel.ActivationCode;

                salewithusService.userverify($scope.verifycodemodel).then(function (response) {

                    //debugger;
                    if (response.data.Status == "Success") {

                        $("#verifymodal").modal('hide');
                        swal(response.data.Message);

                        window.localStorage.removeItem("Emailid_nw");
                        $state.go("edit_profile", {}, { reload: true });
                    }
                    else {

                        $("#verifymodal").modal('hide');
                        swal(response.data.Message);

                    }
                });

            }
        }
        $scope.usertypefb_ = "";
        $scope.Usertype = function (data) {

            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid || $scope.usertypefb_ == data) {
                return true;

            }
            else {
                return false;

            }
         
        }
        $scope.userfb = function (data) {
            $scope.usertypefb_ = window.localStorage.getItem("UserTypeIDfb");
            if (data == $scope.usertypefb_) {
                return true;
            }
            else {
                return false;
            }

        }


        $scope.resendverifycodemodel = {

            Email: "",
        };

        $scope.Sendverificationcode = function () {

            if (window.localStorage.getItem("Emailid_nw") == "") {

                swal("Please provide email id!");
            }
            else {

                $scope.resendverifycodemodel.Email = window.localStorage.getItem("Emailid_nw");

                salewithusService.resendverificationcode($scope.resendverifycodemodel).then(function (response) {

                    //debugger;
                    if (response.data.Status == "Success") {

                        swal(response.data.Message);

                    }
                    else {

                        swal(response.data.Message);

                    }
                });
            }

            //swal("verification code send Successfully!");

        }

        //verification//

        $scope.model_mytrade = {
            FromUserId: 0,
            ToUserId: 0,
            TradeId: 0,
            Message: "",
            CreatedDateTime: "",
            IsRead: false,
            DeletedByUserId: "",
            IsOfferedMsg: false,
        }
        $scope.offer_msg = false;
        $scope.Note = 0;
        $scope.itemname_ = "";
        $scope.tradeid_ = null;
        $scope.categoryid_ = null;

        $scope.sendoffermodal = function (itemname, tradeid, categoryid) {
            $("#sendoffermodal").modal('show');

            $scope.itemname_ = itemname;
            $scope.tradeid_ = tradeid;
            $scope.categoryid_ = categoryid;

        }
        $scope.Sendoffer = function () {
          
            $("#sendoffermodal").modal('hide');
            var hasNumber = /\d/;
            $scope.model_mytrade.FromUserId = window.localStorage.getItem("UserId");
            $scope.model_mytrade.ToUserId = tradeService.getmyofferuserid();
            $scope.model_mytrade.TradeId = $scope.tradeid_;
            $scope.userData = window.localStorage.getItem("FirstName");
            // $scope.offer_model.Message = $scope.userData + " " + "has offered this trade for" + " " + "$" + offer_model.Message;
            $scope.model_mytrade.Message = "$" + $scope.Note + " " + "I am offering you my trade" + " " + $scope.itemname_ + " " + "Please checkout this:" + " " + "https://web.worldoftrade.com/#/Trade?tradeId=" + $scope.tradeid_ + "&categoryId=" + $scope.categoryid_ ;
            if ($scope.model_mytrade.Message != "") {
                if (hasNumber.test($scope.model_mytrade.Message)) {
                    $scope.model_mytrade.IsOfferedMsg = true;
                }

                salewithusService.offer_($scope.model_mytrade).then(function (response) {

                    if (response.data.Status == "Success") {
                        //$window.location.reload();
                        //  $scope.GetTradeByUserId();
                        var chattradeId = salewithusService.gettradeid();
                        chatService.settradeid(chattradeId);
                        chatService.setfrompage("single");
                        swal("Offer has been Sent Successfully.");
                        $("#modal .close").hide();
                        //$state.go("chat");
                        $("#myOffer").hide();
                        $(".modal-backdrop").hide();

                       // $state.go("Chat");
                    }
                    else {
                        $("#modal .close").hide();
                        swal("You cannot offer to yourself !!");
                        $state.go("index");
                        $("body").css("padding", "0px");

                    }

                }, function error(response) {
                    console.log("error");
                });
            }
            else {
                $scope.offer_msg = true;
            }

        }

        $scope.checkfacebookid = function () {
            var facebookid = window.localStorage.getItem('FacebookId');
            if (facebookid != null) {
                return false;
            }
            else {
                return true;
            }
        }
        
        $scope.forgot_password = {
            Email: ""
        }
        $scope.sendmail = function () {
          //  $("#myModal").hide();
          //  $scope.keyword = prompt("Please Enter email address.", "");

           
            $scope.forgot_password.Email = $("#inptemail").val();
                //  $scope.validate($scope.forgot_password.Email);
                if ($scope.forgot_password.Email !== "" && $scope.validate($scope.forgot_password.Email)) {
                    salewithusService.forgot_password($scope.forgot_password).then(function (response) {


                        if (response.data.Status == "Success") {

                            swal("Please check your email.");
                            //$("body").css("padding", "0px");
                            //$(".modal-backdrop.show").css("opacity", "0");
                           // $state.go("index", {}, { reload: true });
                        }
                        else {
                            swal("Something Went Wrong!!");
                        }

                    }, function error(response) {
                        console.log("error");
                    });
                }
                else {
                  //  $("#myModal").hide();
                   // $scope.fp_alert();
                }

           
        }


        $scope.validate = function (email) {

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) {

                alert("Invalid Email Address");
                return false;
            }
            else
                return true;
        }
        $scope.getcountrycountries = [];
        $scope.GetCountries = function () {


            //debugger;
            $scope.getcountries = [];


            $http({
                method: 'GET',
                url: 'api/Country/Countries'
            }).then(function success(response) {
                //debugger;
                $scope.getcountries = response.data.Result;

                // $scope.Allcountrycode = response.data.Result.code;
                // $scope.countryid.push(0);
                for (var i = 0; i < $scope.getcountries.length; i++) {

                    var obj = $scope.Allcountrycode[i];

                    $scope.getcountrycountries.push($scope.getcountries[i].code);

                }

                console.log("countrycode " + $scope.getcountrycode[0]);
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );
        }

       
    }]);


   
}())

;
var mysrclat = 0;
var mysrclong = 0;
var pagenumber = 1;
(function () {
    'use strict';
      angular.module('app').controller('SearchController', ['$http', '$scope', '$state', '$stateParams', '$location', 'authService', 'salewithusService', 'tradeService', '$window', 'toaster', function ($http, $scope, $state, $location, $stateParams, authService, salewithusService,tradeService, $window, toaster) {
       

        $(".modal-backdrop").hide();
        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
          $scope.isbnnumber = "";
        $scope.$watch('groups[0].open', function (isOpen) {
            if (isOpen) {
                console.log('First group was opened');
            }
        });

          $scope.onEnterKeyPress = function (event, isbnnumber) {
              if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
                  $scope.showTradesbyisbnnumber(isbnnumber);
          }

          
          $scope.EnterKeyPress = function (event, isbnnumber) {
              if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
                  $scope.searchbyisbn(isbnnumber);
          }



        $scope.CheckLogin = function () {
            var UserId = window.localStorage.getItem('UserId');
            var Username = window.localStorage.getItem('userName');
            if (UserId == null && Username == null) {
                $state.go("index");
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }
            else {
            }
        }

        $scope.logout = function () {

            window.localStorage.removeItem('UserId');
            window.localStorage.removeItem('userName');
            //window.localStorage.removeItem('UserImage');

            swal({
                title: "Success!",
                text: "Log Out Succesfull!",
                icon: "success",
                button: "Ok!",
            });
            $state.go("index");
            $("#profile").hide();
            $("#login").show();
        };

    
      
        $scope.relatedparentID = [];
        $scope.AllProductsCategory = [];
        $scope.GetAllProductsCategory = function () {
            $.LoadingOverlay("show"); //paras\
            //debugger;
            $scope.AllProductsCategory = [6];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoryList'

            }).then(function success(response) {
                $.LoadingOverlay("hide"); //paras\
                //debugger;
                // $scope.allcategory_ = response.data.length;
                $scope.AllProductsCategory = response.data;
                window.localStorage.setItem('CategoryId', response.data.CategoryId);
                //for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

                //    if (i < 6) {
                //        $scope.Categorylist2.push($scope.AllProductsCategory[i]);

                //    }
                //    if (i >= 6 && i < 12) {
                //        $scope.Categorylist3.push($scope.AllProductsCategory[i]);

                //    }
                //    if (i >= 12 && i < 18) {
                //        $scope.Categorylist4.push($scope.AllProductsCategory[i]);

                //    }

                //}



            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                    // this function will be called when the request returned error status
                });


        };

        $scope.AllSubCategory2 = [];
        $scope.selectedSubCategory = 0;
        $scope.GetSubCategory = function () {
            $.LoadingOverlay("show"); //paras\
            var selectedCategoryId = $scope.selectedCategory;//$scope.subid = data;
            $scope.subid = selectedCategoryId;
            $scope.subcat = $scope.selectedSubCategory;
            //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                $.LoadingOverlay("hide"); //paras\
                //debugger;
                $scope.AllSubCategory = response.data.Result;
                $scope.frompage = salewithusService.getfrompage();
                $scope.collehetrades = salewithusService.getpagename_college();
                if ($scope.frompage == 'Header') {
                    $scope.searchbycategory();
                }
                else {
                    if ($scope.collehetrades == "filterpage_collegetrades") {
                        $scope.searchbycollegetrades();
                    }
                    else {
                        $scope.searchbycategory();
                    }
                   
                }

                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        $scope.selected_categoryname = obj.CategoryName;
                        //if ($scope.selected_categoryname == "Bag") {
                        //    $("#rateperhour").show();
                        //}
                        //else {
                        //    $("#rateperhour").hide();
                        //}
                        salewithusService.setcategoryname($scope.selected_categoryname);
                        if (obj.Subcategories.length > 0) {
                            $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                            window.localStorage.setItem("SubCatIsAvailable", "true");
                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            $('#SubCategoryList').hide();
                            //swal({
                            //    text: "No Subcategories are available for this category.",
                            //    button: "Ok!",
                            //});
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                    // this function will be called when the request returned error status
                });


        };

        $scope.searchmodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: null,
            SubCategoryId: null,
            MinPrice: null,
            MaxPrice: null,
            PageNumber: 1,
            PageSize: 8,
            ISBN_No:""
        }
        
        $scope.searchbycategory = function () {
            $scope.searchProductList = [];
            $scope.searchmodel.UserId = window.localStorage.getItem('UserId');
            $scope.searchmodel.PageNumber = pagenumber;
            $scope.searchmodel.CategoryId = $scope.selectedCategory;
            $scope.searchmodel.SubCategoryId = $scope.selectedSubCategory;
            $scope.searchmodel.ISBN_No = $scope.isbnnumber;
            if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                $scope.searchmodel.Latitude = SelectedLatitude;
                $scope.searchmodel.Longitude = SelectedLongitude;
                $scope.searchmodel.Radius = 100;
            }
            else {
                $scope.searchmodel.Latitude = mysrclat;
                $scope.searchmodel.Longitude = mysrclong;
                $scope.searchmodel.Radius = 600000;

            }
            $scope.searchmodel.SearchText = "";

            //debugger;
            salewithusService.searchtrade($scope.searchmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.searchProductList = response.data.Result;
                    $scope.searchtrades = $scope.searchProductList;
                    //for (var i = 0; i < $scope.searchProductList.length; i++) {
                    //    var obj = $scope.searchProductList[i];
                    //    $scope.searchtrades.push($scope.searchProductList[i]);
                    //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                    //    $("#loader").hide();
                    //    //  pagenumber.shift();
                    //    $("#btn_spin").show();
                    //}

                    //if ($scope.totalcount == $scope.searchtrades.length) {
                    //    $("#btn_spin").hide();
                    //}
                    //else {
                    //    $("#btn_spin").show();
                    //}

                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });
          }
          $scope.searchcollege = {
              UserId: null,
              Latitude: 0,
              Longitude: 0,
              Radius: 0,
              SearchText: "",
              CategoryId: null,
              SubCategoryId: null,
              MinPrice: null,
              MaxPrice: null,
              PageNumber: 1,
              PageSize: 8,
              ISBN_No: ""
          }
          

          $scope.searchbycollegetrades = function () {
              $.LoadingOverlay("show"); //paras\
              $scope.searchProductList = [];
              $scope.searchcollege.UserId = window.localStorage.getItem('UserId');
              $scope.searchcollege.PageNumber = pagenumber;
              $scope.searchcollege.CategoryId = $scope.selectedCategory;
              $scope.searchcollege.SubCategoryId = $scope.selectedSubCategory;
              $scope.searchcollege.ISBN_No = $scope.isbnnumber;
              if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                  $scope.searchcollege.Latitude = SelectedLatitude;
                  $scope.searchcollege.Longitude = SelectedLongitude;
                  $scope.searchcollege.Radius = 100;
              }
              else {
                  $scope.searchcollege.Latitude = mysrclat;
                  $scope.searchcollege.Longitude = mysrclong;
                  $scope.searchcollege.Radius = 600000;

              }
              $scope.searchcollege.SearchText = "";

              //debugger;
              salewithusService.searchtrade_college($scope.searchcollege).then(function (response) {
                  if (response.data.Status == "Success") {
                      $.LoadingOverlay("hide"); //paras\
                      $scope.searchProductList = response.data.Result;
                      $scope.searchtrades = $scope.searchProductList;
                      //for (var i = 0; i < $scope.searchProductList.length; i++) {
                      //    var obj = $scope.searchProductList[i];
                      //    $scope.searchtrades.push($scope.searchProductList[i]);
                      //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                      //    $("#loader").hide();
                      //    //  pagenumber.shift();
                      //    $("#btn_spin").show();
                      //}

                      //if ($scope.totalcount == $scope.searchtrades.length) {
                      //    $("#btn_spin").hide();
                      //}
                      //else {
                      //    $("#btn_spin").show();
                      //}

                  }
                  else {
                      swal("Something Went Wrong!!");
                  }

              }, function error(response) {
                  console.log("error");
                  $.LoadingOverlay("hide"); //paras\

              });
          }


          $scope.searchbyisbn = function (data) {
              $.LoadingOverlay("show"); //paras\
              $scope.searchProductList = [];
              $scope.searchmodel.UserId = window.localStorage.getItem('UserId');
              $scope.searchmodel.PageNumber = pagenumber;
              $scope.searchmodel.CategoryId = $scope.selectedCategory;
              $scope.searchmodel.SubCategoryId = $scope.selectedSubCategory;
              $scope.searchmodel.ISBN_No = data;
              if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                  $scope.searchmodel.Latitude = SelectedLatitude;
                  $scope.searchmodel.Longitude = SelectedLongitude;
                  $scope.searchmodel.Radius = 100;
              }
              else {
                  $scope.searchmodel.Latitude = mysrclat;
                  $scope.searchmodel.Longitude = mysrclong;
                  $scope.searchmodel.Radius = 600000;

              }
              $scope.searchmodel.SearchText = "";

              //debugger;
              salewithusService.searchtrade($scope.searchmodel).then(function (response) {
                  if (response.data.Status == "Success") {
                      $.LoadingOverlay("hide"); //paras\
                      $scope.searchProductList = response.data.Result;
                      $scope.searchtrades = $scope.searchProductList;
                      //for (var i = 0; i < $scope.searchProductList.length; i++) {
                      //    var obj = $scope.searchProductList[i];
                      //    $scope.searchtrades.push($scope.searchProductList[i]);
                      //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                      //    $("#loader").hide();
                      //    //  pagenumber.shift();
                      //    $("#btn_spin").show();
                      //}

                      //if ($scope.totalcount == $scope.searchtrades.length) {
                      //    $("#btn_spin").hide();
                      //}
                      //else {
                      //    $("#btn_spin").show();
                      //}

                  }
                  else {
                      swal("Something Went Wrong!!");
                  }

              }, function error(response) {
                  console.log("error");
                  $.LoadingOverlay("hide"); //paras\

              });
          }

          
       
        $scope.subid = 0;

          $scope.isbn = "";

          $scope.checkisbn = function () {
              $scope.isbn = $scope.selectedCategory;
              if ($scope.isbn == 1) {
                  return true;
              }
              else {
                  return false;
              }
          }


      
        $scope.refresh_ = function () {
            $state.go("Category_filterpage", {}, {reload:true});
        }
       
   
        $scope.showProductsTrade_up = function (TradeId,CategoryId) {

            salewithusService.settradeid(TradeId);
            window.localStorage.setItem("Tradeid", TradeId);
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {
                
                $state.go("Trade", { 'tradeId': TradeId, 'categoryId': CategoryId}, { reload: true });
                    // $state.go("single", {}, { reload: true });
               
            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };


        $scope.userid = "";
     
        $scope.showProductsTrade = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);
            salewithusService.setcatid(categoryid);
            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

                $state.go("Trade", { 'tradeId': TradeId, 'categoryId': categoryid}, { reload: true });
                // $state.go("single", {}, { reload: true });

            }
            else {
                $state.go("index", {}, { reload: true });
            }


          };

          

          $scope.showProductsNeeds = function (TradeId, categoryid) {

              salewithusService.settradeid(TradeId);
              salewithusService.setcatid(categoryid);
              window.localStorage.setItem("Tradeid", TradeId);
              window.localStorage.setItem("single_catid", categoryid);
              $scope.usertype_ = window.localStorage.getItem("UserTypeID");
              //salewithusService.setcategoryid (TradecategoryId)
              if (TradeId >= 0) {

                  $state.go("Need", { 'tradeId': TradeId, 'categoryId': categoryid }, { reload: true });
                  // $state.go("single", {}, { reload: true });

              }
              else {
                  $state.go("index", {}, { reload: true });
              }


          };


        //favourite_code_start

          $scope.usertypefb_ = "";
          $scope.Usertype = function (data) {

              Uid = window.localStorage.getItem("UserTypeID");
              if (data == Uid || $scope.usertypefb_ == data) {
                  return true;

              }
              else {
                  return false;

              }

          }

        $scope.likemodel = {
            TradeId: 0,
            UserId: 0,

        }

        $scope.id = 0;
        $scope.uid = 0;

        $scope.LikeDislike = function (TradeId, IsLiked) {
            if (IsLiked) {
                $scope.Getlike(TradeId);
            }
            else {
                $scope.Getdislike(TradeId);
            }

        }


          $scope.Getlike = function (data) {
              $.LoadingOverlay("show"); //paras\
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {

                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasaunfav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        $.LoadingOverlay("hide"); //paras\
                        // $(this).removeClass("fa fa-heart");
                        //$(this).addClass("fa fa-heart-o");
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart-o");
                        $scope.Getalltradeafterlogin()
                       // swal(" unfavourite !!");

                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };


          $scope.Getdislike = function (data) {
              $.LoadingOverlay("show"); //paras\
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {

                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasafav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        $.LoadingOverlay("hide"); //paras\
                        //$("#likebtn").removeClass("fa fa-heart-o");
                        //$("#likebtn").addClass("fa fa-heart");
                        //$("#likebtn").show();
                        //$("#dislikebtn").hide();
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart-o");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart");
                        $scope.Getalltradeafterlogin()

                       // swal("Added as a favourite !!");

                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };
        //favourite_code_end

        $scope.profiledata = function () {
            //debugger;
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {
                $("#profile").show();
                $("#login").hide();
            }
            else {
                $("#profile").hide();
                $("#login").show();
            }
        }

        $scope.searchproductName = "";
        $scope.showRelatedProducts = function (productcatid) {
            salewithusService.setproductcatid(productcatid);

            $state.go("RelatedProduct", {}, { reload: true });
        }

        //$scope.SearchProductByName = function () {
        //    //debugger;
        //    $scope.searchProductList = [6];

        //    //$scope.searchproductName = salewithusService.getsearchproductName();
        //    //alert($stateParams.searchproductName);
        //    //$scope.searchproductName = $stateParams.searchproductName;
        //    $("#divShowSearchProduct").show();
        //    $("#divShowSearchProductByCategory").hide();
        //    $scope.searchproductName = //
        //        $http({
        //            method: 'GET',
        //        url: 'api/Search/SearchProductByName?productName=' + $scope.searchproductName

        //        }).then(function success(response) {
        //            //debugger;
        //            $scope.searchProductList = response.data;
        //            //window.localStorage.removeItem('searchproductName');
        //        },
        //            function error(response) {
        //                console.log("error");
        //                // this function will be called when the request returned error status
        //            });
        //}


        //$scope.showSearchProducts = function (searchproductName) {
        //    //debugger;
        //    //salewithusService.setsearchproductName(searchproductName);
        //    $state.go("filterpage");
        //    $scope.searchproductName = searchproductName;
        //    //window.localStorage.setItem('searchproductName', searchproductName);
        //    //$state.go("filterpage", {}, { reload: true });

        //}
        $scope.searchProductList = [];
        $scope.minprice = null;
        $scope.maxprice = null;
        $scope.SearchTrademodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: null,
            SubCategoryId: null,
            MinPrice: null,
            MaxPrice: null,
            PageNumber: 1,
            PageSize: 8,
            ISBN_No:""
        }
        $scope.totalcount = 0;
        $scope.searchtrades = [];
          $scope.showSearchProducts = function (searchproductName, maxprice, minprice) {
              $.LoadingOverlay("show"); //paras\
            $scope.searchProductList = [];
            $scope.SearchTrademodel.UserId = window.localStorage.getItem('UserId');
            $scope.SearchTrademodel.PageNumber = pagenumber;
            if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                $scope.SearchTrademodel.Latitude = SelectedLatitude;
                $scope.SearchTrademodel.Longitude = SelectedLongitude;
                $scope.SearchTrademodel.Radius = 100;
            }
            else {
                $scope.SearchTrademodel.Latitude = mysrclat;
                $scope.SearchTrademodel.Longitude = mysrclong;
                $scope.SearchTrademodel.Radius = 600000;

            }
          
            $scope.SearchTrademodel.MinPrice = minprice;
            $scope.SearchTrademodel.MaxPrice = maxprice;
            if (searchproductName == "" || searchproductName == null) {
                if (window.localStorage.getItem('searchproductName') != "undefined")
                    $scope.SearchTrademodel.SearchText = window.localStorage.getItem('searchproductName');
               // $scope.SearchTrademodel.ISBN_No = window.localStorage.getItem('searchproductName');
            }
            else {
                    $scope.SearchTrademodel.SearchText = "";
              //  $scope.SearchTrademodel.ISBN_No = "";
            }
            //debugger;
            salewithusService.searchtrade($scope.SearchTrademodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide"); //paras\
                $scope.searchProductList = response.data.Result;
             
                for (var i = 0; i < $scope.searchProductList.length; i++) {
                    var obj = $scope.searchProductList[i];
                    $scope.searchtrades.push($scope.searchProductList[i]);
                    $scope.totalcount = $scope.searchProductList[i].TotalCount;
                   
                    $("#loader").hide();
                  //  pagenumber.shift();
                    $("#btn_spin").show();
                }

                if ($scope.totalcount == $scope.searchtrades.length) {
                    $("#btn_spin").hide();
                }
                else {
                    $("#btn_spin").show();
                }
          
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
                $.LoadingOverlay("hide"); //paras\
            });

            //window.localStorage.setItem('searchproductName', searchproductName);
            //$state.go("filterpage", {}, { reload: true });

          }
          $scope.SearchNeedmodel = {
              UserId: null,
              Latitude: 0,
              Longitude: 0,
              Radius: 0,
              SearchText: "",
              CategoryId: null,
              SubCategoryId: null,
              MinPrice: null,
              MaxPrice: null,
              PageNumber: 1,
              PageSize: 8,
              ISBN_No: ""
          }
          $scope.showSearchProducts_needs = function (searchproductName, maxprice, minprice) {
              $.LoadingOverlay("show"); //paras\
              $scope.searchProductList_needs = [];
              $scope.SearchNeedmodel.UserId = window.localStorage.getItem('UserId');
              $scope.SearchNeedmodel.PageNumber = pagenumber;
              if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                  $scope.SearchNeedmodel.Latitude = SelectedLatitude;
                  $scope.SearchNeedmodel.Longitude = SelectedLongitude;
                  $scope.SearchNeedmodel.Radius = 100;
              }
              else {
                  $scope.SearchNeedmodel.Latitude = mysrclat;
                  $scope.SearchNeedmodel.Longitude = mysrclong;
                  $scope.SearchNeedmodel.Radius = 600000;

              }

              $scope.SearchNeedmodel.MinPrice = minprice;
              $scope.SearchNeedmodel.MaxPrice = maxprice;
              if (searchproductName == "" || searchproductName == null) {
                  if (window.localStorage.getItem('searchproductName') != "undefined")
                      $scope.SearchNeedmodel.SearchText = window.localStorage.getItem('searchproductName');
                  // $scope.SearchTrademodel.ISBN_No = window.localStorage.getItem('searchproductName');
              }
              else {
                  $scope.SearchNeedmodel.SearchText = "";
                  //  $scope.SearchTrademodel.ISBN_No = "";
              }
              //debugger;
              salewithusService.searchNeeds($scope.SearchNeedmodel).then(function (response) {
                  if (response.data.Status == "Success") {
                      $.LoadingOverlay("hide"); //paras\
                      $scope.showSearchProducts_needs = response.data.Result;

                      for (var i = 0; i < $scope.showSearchProducts_needs.length; i++) {
                          var obj = $scope.showSearchProducts_needs[i];
                          $scope.searchtrades.push($scope.showSearchProducts_needs[i]);
                          $scope.totalcount = $scope.showSearchProducts_needs[i].TotalCount;

                          $("#loader").hide();
                          //  pagenumber.shift();
                          $("#btn_spin").show();
                      }

                      if ($scope.totalcount == $scope.searchtrades.length) {
                          $("#btn_spin").hide();
                      }
                      else {
                          $("#btn_spin").show();
                      }

                  }
                  else {
                      swal("Something Went Wrong!!");
                  }

              }, function error(response) {
                  console.log("error");
                  $.LoadingOverlay("hide"); //paras\
              });

              //window.localStorage.setItem('searchproductName', searchproductName);
              //$state.go("filterpage", {}, { reload: true });

          }
      
        $scope.Searchtradebysubcategories = function (data) {
            $scope.searchbysubcategory = [];
            $.LoadingOverlay("show"); //paras\
            $scope.search_model.Longitude = mysrclong;
            $scope.search_model.Latitude = mysrclat;
            $scope.search_model.Radius = 6000;
            $scope.search_model.CategoryId = salewithusService.getcategoryid();
            $scope.search_model.CategoryId = window.localStorage.getItem("Category_fp");
            $scope.search_model.SubCategoryId = data;
            $scope.search_model.UserId = window.localStorage.getItem("UserId");

            salewithusService.Search_bymaincategory($scope.search_model).then(function (response) {
                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide"); //paras\
                    $scope.searchbysubcategory = response.data.Result;
                  $scope.searchtrades = $scope.searchbysubcategory;
                    //$("#divShowSearchProduct").hide();
                    //$("#divShowSearchProductByCategory").show();

                    //window.localStorage.removeItem('searchproductName');
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
                $.LoadingOverlay("hide"); //paras\

            });

        }

        $scope.showFilterSearchProducts = function (searchproductName) {
            //debugger;
            //salewithusService.setsearchproductName(searchproductName);
            //$state.go("filterpage");
            //$scope.searchproductName = searchproductName;
            window.localStorage.setItem('searchproductName', searchproductName);
            $scope.SearchProductByName();
            //$window.location.reload();

            //$state.go("filterpage", { 'searchproductName': searchproductName }, { reload: true });

        }

        

        //get_currect_location_start//
        $scope.mysrclat = "";
        $scope.lat = "";
        $scope.lan = "";
        $scope.nearme = function () {
            //debugger;
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    mysrclat = position.coords.latitude;
                    mysrclong = position.coords.longitude;
                    console.log("lat", mysrclat);
                    console.log("ong", mysrclong);
                    // Use either $scope.$apply() or $scope.evalAsync not both for same result
                    //$scope.$apply()  
                    $scope.$apply(function () {
                        $scope.lat = mysrclat;
                        $scope.lan = mysrclong;
                    })
                    //$scope.$evalAsync()
                    $scope.$evalAsync(function () {
                        $scope.elat = mysrclat;
                        $scope.elan = mysrclong;
                    })


                });
            }

        }
        //get_currect_location_end//

        //trades_by category//
        $scope.search_model = {
            Longitude:0.00,
            Latitude:0.00,
            Radius:6000,
            CategoryId:null,
            SubCategoryId:null,
            UserId: null,
            PageNumber: 1,
            PageSize: 20,
            ISBN_No: ""
        }
        $scope.trades_bycategory = [];
        $scope.Search_bymaincategory = function () {
            $scope.trades_bycategory = [];
            
            $scope.search_model.Longitude = mysrclong;
            $scope.search_model.Latitude = mysrclat;
            $scope.search_model.Radius = 6000;
            $scope.search_model.CategoryId = salewithusService.getcategoryid();

            $scope.search_model.CategoryId = window.localStorage.getItem("Category_fp");
            $scope.search_model.SubCategoryId = null;
            $scope.search_model.UserId = window.localStorage.getItem("UserId");
            $scope.search_model.PageNumber = pagenumber;

            salewithusService.Search_bymaincategory($scope.search_model).then(function (response) {
                if (response.data.Status == "Success") {
                    if (response.data.Message == "No records found.") {
                        $("#norecord_").show();
                    }
                    else {
                        $scope.trades_bycategory = response.data.Result;

                        $("#divShowSearchProduct").show();
                        $("#divShowSearchProductByCategory").hide();
                        //for (var i = 0; i < $scope.trades_bycategory.length; i++) {
                        //    var obj = $scope.trades_bycategory[i];
                        //    $scope.totalcount = $scope.trades_bycategory[i].TotalCount;
                        //    $scope.trades_bycategory.push($scope.trades_bycategory[i]);
                        //    //pagenumber = 1;
                        //    $("#loader").hide();
                        //    $("#btn_spin").show();
                        //}

                        //if ($scope.totalcount == $scope.AllTrade_.length) {
                        //    $("#btn_spin").hide();
                        //}
                        //else {
                        //    $("#btn_spin").show();
                        //}
                    }

                 
                    
                    //window.localStorage.removeItem('searchproductName');
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });

        }
         // $scope.iSBNnumber = "";

          $scope.search_modelmaincat = {
              Longitude: 0.00,
              Latitude: 0.00,
              Radius: 6000,
              CategoryId: null,
              SubCategoryId: null,
              UserId: null,
              PageNumber:1,
              PageSize:0,
              ISBN_No: ""
          }

        $scope.showTradesbymaincategory = function () {
            $.LoadingOverlay("show"); //paras
            $scope.trades_bycategory = [];
           // var selectedmaincategoryId = $scope.selectedmaincategory;
            $scope.search_modelmaincat.Longitude = mysrclong;
            $scope.search_modelmaincat.Latitude = mysrclat;
            $scope.search_modelmaincat.Radius = 6000;
           // $scope.search_model.CategoryId = salewithusService.getcategoryid();

            $scope.search_modelmaincat.CategoryId = $scope.selectedmaincategory;
            $scope.search_modelmaincat.SubCategoryId = null;
           // $scope.search_modelmaincat.ISBN_No = $scope.isbnnumber;

            $scope.search_model.UserId = window.localStorage.getItem("UserId");

            salewithusService.Search_bymaincategory($scope.search_model).then(function (response) {
                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide"); //paras
                    if (response.data.Message == "No records found.") {
                        $("#norecord_").show();
                    }
                    else {
                        $scope.trades_bycategory = response.data.Result;

                        $("#divShowSearchProduct").show();
                        $("#divShowSearchProductByCategory").hide();
                    }



                    //window.localStorage.removeItem('searchproductName');
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
                $.LoadingOverlay("hide"); //paras

            });

          };

       
          $scope.showTradesbyisbnnumber = function (data) {
              $.LoadingOverlay("show"); //paras
              $scope.trades_bycategory = [];
              // var selectedmaincategoryId = $scope.selectedmaincategory;
              $scope.search_modelmaincat.Longitude = mysrclong;
              $scope.search_modelmaincat.Latitude = mysrclat;
              $scope.search_modelmaincat.Radius = 6000;
              // $scope.search_model.CategoryId = salewithusService.getcategoryid();

              $scope.search_modelmaincat.CategoryId = $scope.selectedmaincategory;
              $scope.search_modelmaincat.SubCategoryId = null;
              $scope.search_modelmaincat.ISBN_No = data;

              $scope.search_modelmaincat.UserId = window.localStorage.getItem("UserId");

              salewithusService.Search_bymaincategory($scope.search_modelmaincat).then(function (response) {
                  if (response.data.Status == "Success") {
                      $.LoadingOverlay("hide"); //paras
                      if (response.data.Message == "No records found.") {
                          $("#norecord_").show();
                      }
                      else {
                          $scope.trades_bycategory = response.data.Result;

                          $("#divShowSearchProduct").show();
                          $("#divShowSearchProductByCategory").hide();
                      }



                      //window.localStorage.removeItem('searchproductName');
                  }
                  else {
                      swal("Something Went Wrong!!");
                  }

              }, function error(response) {
                  console.log("error");


              });

          };


          $scope.checkisbn_ = function () {
              $scope.isbn = $scope.selectedmaincategory;
              if ($scope.isbn == 1) {
                  return true;
              }
              else {
                  return false;
              }
          }

        $scope.searchbysubcategory = [];
        $scope.Search_bysubcategory = function (data) {
            $scope.searchbysubcategory = [];

            $scope.search_model.Longitude = mysrclong;
            $scope.search_model.Latitude = mysrclat;
            $scope.search_model.Radius = 6000;
            $scope.search_model.CategoryId = salewithusService.getcategoryid();
            $scope.search_model.CategoryId = window.localStorage.getItem("Category_fp");
            $scope.search_model.SubCategoryId = data;
            $scope.search_model.UserId = window.localStorage.getItem("UserId");

            salewithusService.Search_bymaincategory($scope.search_model).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.searchbysubcategory = response.data.Result;
                    $scope.trades_bycategory = $scope.searchbysubcategory;
                    //$("#divShowSearchProduct").hide();
                    //$("#divShowSearchProductByCategory").show();

                    //window.localStorage.removeItem('searchproductName');
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });

        }

        //trades_by category//

        $scope.selectedmaincategory = 0;
        $scope.subid = 0;
        $scope.selectedCategory = 0;
        $scope.AllSubCategory2 = [];
        $scope.categoryname = "";
        $scope.GetAllSubCategory = function () {
            var selectedCategoryId = salewithusService.getcategoryid();
            //var selectedCategoryId = tradeService.getcategoryid();
            var selectedCategoryId = window.localStorage.getItem("Category_fp");
            $scope.selectedmaincategory = salewithusService.getcategoryid();
            $scope.subid = selectedCategoryId;
            //debugger;
            $scope.AllSubCategory = [];
           

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllSubCategory = response.data.Result;
               
                //debugger;
                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        $scope.categoryname = obj.CategoryName;

                        if (obj.Subcategories.length > 0) {
                            //   $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                            window.localStorage.setItem("SubCatIsAvailable", "true");
                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            //  $('#SubCategoryList').hide();
                            swal({
                                text: "No Subcategories are available for this category.",
                                button: "Ok!",
                            });
                        }
                    }
                }

            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });

        };

      

        $scope.ShowSubcategories = function (categoryId) {


            $scope.subid = categoryId;
            $scope.Subcategories = [];
            //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllSubCategory = response.data.Result;
                //$("#category").show();
                //$("#subcategories").show();
                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        $scope.categoryname = obj.CategoryName;

                        if (obj.Subcategories.length > 0) {
                            //   $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                            window.localStorage.setItem("SubCatIsAvailable", "true");
                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            //  $('#SubCategoryList').hide();
                            swal({
                                text: "No Subcategories are available for this category.",
                                button: "Ok!",
                            });
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });


        };
      
        $scope.loadMore_search = function () {
            $("#loader").show();
            pagenumber = pagenumber + 1;
            $scope.showSearchProducts();
        }

        $scope.loadMore_categoryfilter = function () {
            $("#loader").show();
            pagenumber = pagenumber + 1;
            $scope.Search_bymaincategory();

        };
        

    }]);

 

}())

;

var usertype = [];
var id = [];
var usertype_ = [];
var typeid = [];

(function () {

    angular.module('app').controller('CheckController', ['$http', '$scope', '$location', '$timeout', 'authService', 'tradeService', 'salewithusService', '$rootScope', '$state', '$window', function ($http, $scope, $location, $timeout, authService, tradeService,salewithusService, $rootScope, $state, $window) {
       

        $scope.getusertypeofuser = function () {

            $scope.UserTypeId = [];
            //debugger;
            $scope.Userid = window.localStorage.getItem('UserId');
            $http({
                method: 'GET',
                url: 'api/Login/SearchdataByuserId?UserId=' + $scope.Userid

            }).then(function success(response) {
                console.log(response.data.Result);
                //debugger;

                $scope.UserTypeId = response.data.Result[0].UserTypeId;
                typeid = $scope.UserTypeId;

            },
                function error(response) {

                    console.log("error");
                    // this function will be called when the request returned error status
                });
        }
        $scope.CheckLogin_Ut = function () {
           
                var UserId = window.localStorage.getItem('UserId');
            
          
          
            //var Username = window.localStorage.getItem('userName');
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
            if (UserId == null) {
              //  $scope.checkusertype_();
              //  $scope.checkusertype_3();
                $state.go("index");
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",

                });
               
            }
          
                else {
                    //$state.go("index");
                    //swal({
                    //    title: "Please Login!",
                    //    text: "This is only for Users!",
                    //    //icon: "error",
                    //    button: "Ok!",

                    //});
                }
            }
       
      

        $scope.CheckLogin_ = function () {
            var UserId = window.localStorage.getItem('UserId');
          
          //  var usertype = 1;
            if (UserId == null) {
                $state.go("index");
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",

                });
            }
            else {


            }

        };

        $scope.Usertype = function (data) {

            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid) {
                return true;

            }
            else {
                return false;

            }
        }

    }]);

}());
var pagenumber = 1;

(function () {
    'use strict';
    angular.module('app').controller('CharityController', ['$http', '$scope', '$state', '$stateParams', '$location', 'authService', 'salewithusService', 'tradeService', '$window', 'toaster', function ($http, $scope, $state, $location, $stateParams, authService, salewithusService,tradeService, $window, toaster) {



        $(".modal-backdrop").css("display", "none");
     
        $scope.needs_ = {
            UserId: null,
            PageNumber: 1,
            PageSize: 12
        }
        $scope.totalcount = 0;
        $scope.charity = [];
        $scope.usertype_need = 0;
        $scope.GetCharity_needs = function () {
            $.LoadingOverlay("show"); //paras\
            $scope.charity_ = [];
            $scope.needs_.UserId = window.localStorage.getItem("UserId");
            $scope.needs_.PageNumber = pagenumber;
            //$scope.needs_.UserId = 1002;
            salewithusService.needs_($scope.needs_).then(function (response) {
                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide"); //paras\
                   
                    $scope.charity_ = response.data.Result;
                    for (var i = 0; i < $scope.charity_.length; i++) {
                        var obj = $scope.charity_[i];
                        $scope.charity.push($scope.charity_[i]);
                        $scope.totalcount = $scope.charity_[i].TotalCount;
                        $("#loader").hide();
                        $("#btn_spin").show();
                    }

                    if ($scope.totalcount == $scope.charity.length) {
                        $("#btn_spin").hide();
                    }
                    else {
                        $("#btn_spin").show();
                    }

                   

                    $scope.usertype_need = window.localStorage.setItem("Usertype_need", response.data.Result.UserTypeId);
                    // window.localStorage.setItem("trade_userid", response.data.Result[0].UserId);
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                $.LoadingOverlay("hide"); //paras
                console.log("error");
            });
        }
        $scope.getcharitymodel = {
            UserId:0
        }
        $scope.selectedcharity = [];
        $scope.Getselectedproduct = function () {
            $.LoadingOverlay("show"); //paras\
            $scope.selectedcharity = [];
            $scope.getcharitymodel.UserId = salewithusService.getuserid();
           // $scope.getcharitymodel.UserId = window.localStorage.getItem("UserId");
            salewithusService.getcharitydetails($scope.getcharitymodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide"); //paras\
                    //swal("Updated Successfully!!");
                    //$("#tradeafterlogin").show();
                    //$("#tradebeforelogin").hide();
                    $scope.selectedcharity = response.data.Result;
                    // window.localStorage.setItem("trade_userid", response.data.Result[0].UserId);
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        };


        $scope.EnterKeyPress = function (event, isbnnumber) {
            if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
                $scope.searchbyisbn(isbnnumber);
        }
    
        $scope.showProductscharity = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);
        
            salewithusService.setcatid(categoryid);
          
            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);
           
          //  $scope.usertype_ = window.localStorage.getItem("Usertype_need");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

               // $state.go("Trade", {}, { reload: true });
                // $state.go("single", {}, { reload: true });

                $state.go("Need", { 'tradeId': TradeId, 'categoryId': categoryid}, { reload: true });
            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };

        $scope.showCharity = function (ID) {

            salewithusService.setuserid(ID);
            window.localStorage.setItem("single_Userid", ID);
            //  $scope.Id = window.localStorage.getItem("UserId");

            $state.go("single", {}, { reload: true });
            // $state.go("single", {}, { reload: true });

        };

        $scope.loadMore_needs = function () {
            $("#loader").show();
            pagenumber = pagenumber + 1;
            $scope.GetCharity_needs();
        }

        $scope.usertypefb_ = "";
        $scope.subid = 0;
        $scope.subcat = 0;
        $scope.Usertype = function (data) {

            $scope.usertypefb_ = window.localStorage.getItem("UserTypeIDfb");
            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid || $scope.usertypefb_ == data) {
                return true;

            }
            else {
                return false;
                //debugger;
                //$scope.userfb(data);
            }

        }
        
        $scope.GetSubCategory = function () {
            $.LoadingOverlay("show"); //paras\


            var selectedCategoryId = $scope.selectedCategory;//$scope.subid = data;
            $scope.subid = selectedCategoryId;
            $scope.subcat = $scope.selectedSubCategory;
            //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                $.LoadingOverlay("hide"); //paras\


                //debugger;
                $scope.AllSubCategory = response.data.Result;
                $scope.frompage = salewithusService.getfrompage();
                if ($scope.frompage == 'Header') {
                    $scope.searchbycategory();
                }
                else {
                    $scope.searchbycategory();
                }

                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        $scope.selected_categoryname = obj.CategoryName;
                        //if ($scope.selected_categoryname == "Bag") {
                        //    $("#rateperhour").show();
                        //}
                        //else {
                        //    $("#rateperhour").hide();
                        //}
                        salewithusService.setcategoryname($scope.selected_categoryname);
                        if (obj.Subcategories.length > 0) {
                            $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                            window.localStorage.setItem("SubCatIsAvailable", "true");
                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            $('#SubCategoryList').hide();
                            //swal({
                            //    text: "No Subcategories are available for this category.",
                            //    button: "Ok!",
                            //});
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\


                    // this function will be called when the request returned error status
                });


        };

        $scope.searchmodel = {
            UserId: null,
            Latitude: 0,
            Longitude: 0,
            Radius: 0,
            SearchText: "",
            CategoryId: null,
            SubCategoryId: null,
            MinPrice: null,
            MaxPrice: null,
            PageNumber: 1,
            PageSize: 8,
            ISBN_No: ""
        }
        $scope.searchProductList = [];
        $scope.searchbycategory = function () {
            $.LoadingOverlay("show"); //paras\


            $scope.searchProductList = [];
            $scope.searchmodel.UserId = window.localStorage.getItem('UserId');
            $scope.searchmodel.PageNumber = pagenumber;
            $scope.searchmodel.CategoryId = $scope.selectedCategory;
            $scope.searchmodel.SubCategoryId = $scope.selectedSubCategory;
            $scope.searchmodel.ISBN_No = $scope.isbnnumber;
            if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                $scope.searchmodel.Latitude = SelectedLatitude;
                $scope.searchmodel.Longitude = SelectedLongitude;
                $scope.searchmodel.Radius = 100;
            }
            else {
                $scope.searchmodel.Latitude = mysrclat;
                $scope.searchmodel.Longitude = mysrclong;
                $scope.searchmodel.Radius = 600000;

            }
            $scope.searchmodel.SearchText = "";

            //debugger;
            salewithusService.searchneeds($scope.searchmodel).then(function (response) {
                if (response.data.Status == "Success") {

                    $scope.searchProductList = response.data.Result;
                    $scope.searchtrades = $scope.searchProductList;
                    $scope.charity = $scope.searchProductList;
                    //for (var i = 0; i < $scope.searchProductList.length; i++) {
                    //    var obj = $scope.searchProductList[i];
                    //    $scope.searchtrades.push($scope.searchProductList[i]);
                    //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                    //    $("#loader").hide();
                    //    //  pagenumber.shift();
                    //    $("#btn_spin").show();
                    //}

                    //if ($scope.totalcount == $scope.searchtrades.length) {
                    //    $("#btn_spin").hide();
                    //}
                    //else {
                    //    $("#btn_spin").show();
                    //}

                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });
        }

        $scope.searchbyisbn = function (data) {
            $scope.searchProductList = [];
            $scope.searchmodel.UserId = window.localStorage.getItem('UserId');
            $scope.searchmodel.PageNumber = pagenumber;
            $scope.searchmodel.CategoryId = $scope.selectedCategory;
            $scope.searchmodel.SubCategoryId = $scope.selectedSubCategory;
            $scope.searchmodel.ISBN_No = data;
            if (SelectedLatitude != 0 && SelectedLongitude != 0) {
                $scope.searchmodel.Latitude = SelectedLatitude;
                $scope.searchmodel.Longitude = SelectedLongitude;
                $scope.searchmodel.Radius = 100;
            }
            else {
                $scope.searchmodel.Latitude = mysrclat;
                $scope.searchmodel.Longitude = mysrclong;
                $scope.searchmodel.Radius = 600000;

            }
            $scope.searchmodel.SearchText = "";

            //debugger;
            salewithusService.searchneeds($scope.searchmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.searchProductList = response.data.Result;
                    $scope.searchtrades = $scope.searchProductList;
                    $scope.charity = $scope.searchProductList;
                    //for (var i = 0; i < $scope.searchProductList.length; i++) {
                    //    var obj = $scope.searchProductList[i];
                    //    $scope.searchtrades.push($scope.searchProductList[i]);
                    //    $scope.totalcount = $scope.searchProductList[i].TotalCount;

                    //    $("#loader").hide();
                    //    //  pagenumber.shift();
                    //    $("#btn_spin").show();
                    //}

                    //if ($scope.totalcount == $scope.searchtrades.length) {
                    //    $("#btn_spin").hide();
                    //}
                    //else {
                    //    $("#btn_spin").show();
                    //}

                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");

            });
        }

        $scope.isbn = "";

        $scope.checkisbn = function () {
            $scope.isbn = $scope.selectedCategory;
            if ($scope.isbn == 1) {
                return true;
            }
            else {
                return false;
            }
        }

        $scope.AllProductsCategory = [];
        $scope.GetAllProductsCategory = function () {
            $.LoadingOverlay("show"); //paras\
            //debugger;
            $scope.AllProductsCategory = [6];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoryList'

            }).then(function success(response) {
                $.LoadingOverlay("hide"); //paras\
                //debugger;
                // $scope.allcategory_ = response.data.length;
                $scope.AllProductsCategory = response.data;
                window.localStorage.setItem('CategoryId', response.data.CategoryId);
                //for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

                //    if (i < 6) {
                //        $scope.Categorylist2.push($scope.AllProductsCategory[i]);

                //    }
                //    if (i >= 6 && i < 12) {
                //        $scope.Categorylist3.push($scope.AllProductsCategory[i]);

                //    }
                //    if (i >= 12 && i < 18) {
                //        $scope.Categorylist4.push($scope.AllProductsCategory[i]);

                //    }

                //}



            },
                function error(response) {
                    console.log("error");
                    $.LoadingOverlay("hide"); //paras\
                    // this function will be called when the request returned error status
                });


        };

        $scope.checkcategory_ = function () {
            $scope.selected_categoryname = salewithusService.getcategoryname();
            if ($scope.selected_categoryname == "Books") {
                return true;

            }
            else {
                return false;
            }
        }

        salewithusService.setcategoryname($scope.selected_categoryname);

    }]);


}())


;
var map;
var files = [];
var count = 0;
var imagesjson = [];
var finalsrcdata = [];
var srcData = [];
var SelectedLongitude = 0;
var SelectedLongitude_ = 0;
var SelectedLatitude = 0;
var SelectedLatitude_ = 0;
var Lattitude_ = 0.0;
var Longitude_ = 0.0;
var lat = 0;
var lan = 0;
var mysrclat = 0;
var mysrclong = 0;
var TradeId = 0;
var sId = 0;
var length = 0;
var totallength = 0;
var imagesdata_ = [];
var firstname = [];
var src = "";

var pagenumber = 1;
// Multiple images preview in browser
var imagesPreview = function (input, placeToInsertImagePreview) {

    if (input.files) {
        var filesAmount = input.files.length;

        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();

            reader.onload = function (event) {
                $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
            }

            reader.readAsDataURL(input.files[i]);
        }
    }

};

$('#gallery-photo-add').on('change', function () {
    imagesPreview(this, 'div.gallery');
});

function loadImageFileAsURL() {

    var placeToInsertImagePreview = document.getElementById("gallery");

    var filesSelected = document.getElementById("inputFileToLoad");
    if (filesSelected.files.length < 6) {
        var filesAmount = filesSelected.files.length;

        var imageobj = {};
        var count = 0;

        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();

            reader.onload = function (event) {

                srcData.push(event.target.result); // <--- data: base64

                var id = count.toString();

                //imageobj['key' + id] = event.target.result;


                //obj.name = "Raj"; 

                src = event.target.result;
                // $scope.Getchooseimages();
                console.log("Length is" + srcData.length);

                //$($.parseHTML('<img>')).attr({
                //    'src': event.target.result
                //}).css({
                //    "width": "100px",
                //    "height": "100px",
                //    "margin-right": "10px",
                //    "border": "1px solid black",
                //    "padding": "5px"
                //}).appendTo(placeToInsertImagePreview);

                imagesjson.push(id);

                $("<span class=\"pip\" id=\"" + (count++) + "\">" +
                    "<img class=\"imageThumb\" src=\"" + event.target.result + "\" title=\"" + "a" + "\"/>" +
                    "<br/><span class=\"remove\">Remove image</span>" +
                    "</span>").appendTo(placeToInsertImagePreview);




                $(".remove").click(function () {
                    var retid = $(this).parent(".pip").attr("id");
                    $(this).parent(".pip").remove();

                    for (j = 0; j < imagesjson.length; j++) {

                        if (imagesjson[j] == retid) {

                            imagesjson.splice(j, 1);

                        }

                        console.log("Length is" + imagesjson.length);
                    }

                    //delete imageobj[retid];
                    //srcData.splice(retid, 1);
                });


                //             $("<span class=\"pip\">" +
                //"<img class=\"imageThumb\" src=\"" + event.target.result + "\" />" +
                //"<br/> <img  class=\"deleteimage\" src=\"../../../assets/images/cancel.png\"/>" +
                //"</span>").appendTo(placeToInsertImagePreview);

                //             $(".deleteimage").click(function () {
                //                 $(this).parent(".pip").remove();
                //             });
            }

            reader.readAsDataURL(filesSelected.files[i]);
        }
    }
    else {
        alert("You can upload maximum of 5 Images only.");
    }

}

function loadImageFileAsURL1() {

    var placeToInsertImagePreview = document.getElementById("gallery_new");

    var filesSelected = document.getElementById("inputFileToLoad1");
    if (filesSelected.files.length < 6) {
        var filesAmount = filesSelected.files.length;
        srcData = [];
        var imageobj = {};


        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();

            reader.onload = function (event) {

                srcData.push(event.target.result); // <--- data: base64

                var id = count.toString();

                //imageobj['key' + id] = event.target.result;


                //obj.name = "Raj"; 

                src = event.target.result;
                // $scope.Getchooseimages();
                console.log("Length is" + srcData.length);

                //$($.parseHTML('<img>')).attr({
                //    'src': event.target.result
                //}).css({
                //    "width": "100px",
                //    "height": "100px",
                //    "margin-right": "10px",
                //    "border": "1px solid black",
                //    "padding": "5px"
                //}).appendTo(placeToInsertImagePreview);

                imagesjson.push(id);

                $("<span class=\"pip\" id=\"" + (count++) + "\">" +
                    "<img class=\"imageThumb\" src=\"" + event.target.result + "\" title=\"" + "a" + "\"/>" +
                    "<br/><img class=\"edittradeimages\" src=\"../../../assets/images/deleteicon_.png\"/>" +
                    "</span>").appendTo(placeToInsertImagePreview);




                $(".edittradeimages").click(function () {
                    var retid = $(this).parent(".pip").attr("id");
                    $(this).parent(".pip").remove();

                    for (j = 0; j < imagesjson.length; j++) {

                        if (imagesjson[j] == retid) {

                            imagesjson.splice(j, 1);

                        }

                        console.log("Length is" + imagesjson.length);
                    }

                    //delete imageobj[retid];
                    //srcData.splice(retid, 1);
                });


                //             $("<span class=\"pip\">" +
                //"<img class=\"imageThumb\" src=\"" + event.target.result + "\" />" +
                //"<br/> <img  class=\"deleteimage\" src=\"../../../assets/images/cancel.png\"/>" +
                //"</span>").appendTo(placeToInsertImagePreview);

                //             $(".deleteimage").click(function () {
                //                 $(this).parent(".pip").remove();
                //             });
            }

            reader.readAsDataURL(filesSelected.files[i]);
        }
    }
    else {
        alert("You can upload maximum of 5 Images only.");
    }


}

(function () {

    angular.module('app').controller('tradeController', ['$http', '$sce', '$scope', '$location', '$timeout', 'authService', 'tradeService', 'chatService', 'salewithusService', '$rootScope', '$state', '$window', '$stateParams', function ($http, $sce, $scope, $location, $timeout, authService, tradeService, chatService, salewithusService, $rootScope, $state, $window, $stateParams) {

        $(".modal-backdrop").hide();

        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;
        $scope.CatId = $stateParams.categoryId;//(parameter Name)
        $scope.TradeId = $stateParams.tradeId;
        $scope.selectedproduct = {};
        $scope.get_lat = 0;
        $scope.get_long = 0;
        $scope.proid = "";
        $scope.showMsgs = false;
        $scope.CheckLogin = function () {
            var UserId = window.localStorage.getItem('UserId');
            var Username = window.localStorage.getItem('userName');
            if (UserId == null) {
                $state.go("index");
                // $("#myModal").show();
                //$state.go("index");
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }
            else {
            }
        };
        $scope.images = [];

        $scope.loadImageFileAsURL = function () {

            var placeToInsertImagePreview = document.getElementById("gallery");

            var filesSelected = document.getElementById("inputFileToLoad");
            if (filesSelected.files.length < 6) {
                var filesAmount = filesSelected.files.length;

                var imageobj = {};
                //var count = 0;
                //var finalsrcdata = [];
                for (i = 0; i < filesAmount; i++) {

                    var reader = new FileReader();

                    reader.onload = function (event) {

                        srcData.push(event.target.result); // <--- data: base64

                        var id = count.toString();


                        src = event.target.result;
                        // $scope.Getchooseimages();
                        console.log("Length is" + srcData.length);

                        //$($.parseHTML('<img>')).attr({
                        //    'src': event.target.result
                        //}).css({
                        //    "width": "100px",
                        //    "height": "100px",
                        //    "margin-right": "10px",
                        //    "border": "1px solid black",
                        //    "padding": "5px"
                        //}).appendTo(placeToInsertImagePreview);

                        imagesjson.push(id);

                        $("<span class=\"pip\" id=\"" + (count++) + "\">" +
                            "<img class=\"imageThumb\" src=\"" + event.target.result + "\" title=\"" + "a" + "\"/>" +
                            "<br/><img class=\"deleteimage\" src=\"../../../assets/images/deleteicon_.png\"/>" +
                            "</span>").appendTo(placeToInsertImagePreview);




                        $(".deleteimage").click(function () {
                            var retid = $(this).parent(".pip").attr("id");
                            $(this).parent(".pip").remove();

                            for (j = 0; j < imagesjson.length; j++) {

                                if (imagesjson[j] == retid) {

                                    imagesjson.splice(j, 1);

                                }

                                console.log("Length is" + imagesjson.length);
                            }

                            //delete imageobj[retid];
                            //srcData.splice(retid, 1);
                        });


                        //             $("<span class=\"pip\">" +
                        //"<img class=\"imageThumb\" src=\"" + event.target.result + "\" />" +
                        //"<br/> <img  class=\"deleteimage\" src=\"../../../assets/images/cancel.png\"/>" +
                        //"</span>").appendTo(placeToInsertImagePreview);

                        //             $(".deleteimage").click(function () {
                        //                 $(this).parent(".pip").remove();
                        //             });
                    }

                    reader.readAsDataURL(filesSelected.files[i]);
                }
            }
            else {
                alert("You can only upload a maximum of 5 Images");
            }

        }

        $scope.loadImageFileAsURL1 = function () {

            var placeToInsertImagePreview = document.getElementById("gallery_new");

            var filesSelected = document.getElementById("inputFileToLoad1");
            if (filesSelected.files.length < 6) {
                var filesAmount = filesSelected.files.length;

                var imageobj = {};
                //var count = 0;
                //var finalsrcdata = [];
                for (i = 0; i < filesAmount; i++) {

                    var reader = new FileReader();

                    reader.onload = function (event) {

                        srcData.push(event.target.result); // <--- data: base64

                        var id = count.toString();


                        src = event.target.result;
                        // $scope.Getchooseimages();
                        console.log("Length is" + srcData.length);

                        //$($.parseHTML('<img>')).attr({
                        //    'src': event.target.result
                        //}).css({
                        //    "width": "100px",
                        //    "height": "100px",
                        //    "margin-right": "10px",
                        //    "border": "1px solid black",
                        //    "padding": "5px"
                        //}).appendTo(placeToInsertImagePreview);

                        imagesjson.push(id);

                        $("<span class=\"pip\" id=\"" + (count++) + "\">" +
                            "<img class=\"imageThumb\" src=\"" + event.target.result + "\" title=\"" + "a" + "\"/>" +
                            "<br/><img class=\"deleteimage\" src=\"../../../assets/images/deleteicon_.png\"/>" +
                            "</span>").appendTo(placeToInsertImagePreview);




                        $(".deleteimage").click(function () {
                            var retid = $(this).parent(".pip").attr("id");
                            $(this).parent(".pip").remove();

                            for (j = 0; j < imagesjson.length; j++) {

                                if (imagesjson[j] == retid) {

                                    imagesjson.splice(j, 1);

                                }

                                console.log("Length is" + imagesjson.length);
                            }

                            //delete imageobj[retid];
                            //srcData.splice(retid, 1);
                        });


                        //             $("<span class=\"pip\">" +
                        //"<img class=\"imageThumb\" src=\"" + event.target.result + "\" />" +
                        //"<br/> <img  class=\"deleteimage\" src=\"../../../assets/images/cancel.png\"/>" +
                        //"</span>").appendTo(placeToInsertImagePreview);

                        //             $(".deleteimage").click(function () {
                        //                 $(this).parent(".pip").remove();
                        //             });
                    }

                    reader.readAsDataURL(filesSelected.files[i]);
                }
            }
            else {
                alert("You can only upload a maximum of 5 Images");
            }

        }


        $scope.Getchooseimages = function () {
            //debugger;
            $scope.images = [];
            //  $scope.imageData = [];

            $scope.images = srcData[0];


        }

        $scope.profiledata = function () {
            //debugger;
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {
                $("#profile").show();
                $("#login").hide();
            }
            else {
                $("#profile").hide();
                $("#login").show();
            }
        };

        $scope.logout = function () {

            window.localStorage.removeItem('UserId');
            window.localStorage.removeItem('userName');
            // window.localStorage.removeItem('UserImage');

            swal({
                title: "Success!",
                text: "Log Out Succesfull!",
                icon: "success",
                button: "Ok!",
            });
            $state.go("index");
            $("#profile").hide();
            $("#login").show();
        };


        $scope.userid = "";


        $scope.showRelatedProducts = function (productcatid) {
            salewithusService.setproductcatid(productcatid);

            $state.go("RelatedProduct", {}, { reload: true });


        };

        $scope.profiledata = function () {
            //debugger;
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {
                $("#profile").show();
                $("#login").hide();
            }
            else {
                $("#profile").hide();
                $("#login").show();
            }
        };



        $scope.imageData = "";
        $scope.TradeID = 0;



        function Cleardata(Trade) {
            //debugger;
            $scope.Trade.TradeId = "";

            $scope.Trade.TradeImages = "";

        };

        $scope.TradeImages = {
            TradeID: 0,
            TradeImages: []
        };

        $scope.GetallTradeImages = function (TradeImage) {
            $scope.allTradeImages = [6];


            $http({
                method: 'GET',
                url: 'api/GetallTradeImages'
            }).then(function success(response) {
                //debugger;
                $scope.allTradeImages = response.data;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                }
            );
        };

        $scope.showRelatedProductsTrade = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);
            salewithusService.setcatid(categoryid);
            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);
            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

                $state.go("Trade", { 'tradeId': TradeId, 'categoryId': categoryid }, { reload: true });
                // $state.go("single", {}, { reload: true });

            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };

        $scope.showProductscharity = function (TradeId, CategoryId) {

            //salewithusService.settradeid(TradeId);
            //window.localStorage.setItem("Tradeid", TradeId);
            //  $scope.usertype_ = window.localStorage.getItem("Usertype_need");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

                // $state.go("Trade", {}, { reload: true });
                // $state.go("single", {}, { reload: true });

                $state.go("Need", { 'tradeId': TradeId, 'categoryId': CategoryId }, { reload: true });
            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };

        $scope.getFullDetailsOfTrade = function () {
            //debugger;
            $scope.GetTradeImages();
        };

        $scope.tradeimagemodel = {
            TradeId: 0,
        };
        $scope.tradeimage2 = [];
        $scope.tradeimage = {
            TradeImage: ""
        }
        $scope.GetTradeImages = function () {
            $scope.TradeImagesByTradeId = [];
            $scope.images = [];
            // $scope.tradeimagemodel.TradeId = salewithusService.gettradeid();

            $scope.tradeimagemodel.TradeId = $scope.TradeId;
            //debugger;
            tradeService.tradeimages($scope.tradeimagemodel).then(function (response) {
                //  $window.location.reload();
                //debugger;
                if (response.data.Status == "Success") {

                    $scope.TradeImagesByTradeId = response.data.Result;
                    if (response.data.Message == "No Records found.") {
                        $scope.tradeimage.TradeImage = "https://api.worldoftrade.com/Imagestorage/default_trade_img.png";

                        //$scope.images = $scope.tradeimage.TradeImage;
                        $scope.images = $scope.tradeimage;

                    }
                    else {
                        $scope.TradeImagesByImageId = response.data.Result[0].ImageId;
                        window.localStorage.getItem('ImageId', response.data.Result.ImageId)
                        for (var i = 0; i < $scope.TradeImagesByTradeId.length; i++) {
                            $scope.images.push($scope.TradeImagesByTradeId[i].TradeImage);
                        }
                    }


                    if (response.data.Message != "No Records found.")
                        chatService.settradeimage(response.data.Result[0].TradeImage);

                    else
                        chatService.settradeimage("https://api.worldoftrade.com/Imagestorage/default_trade_img.png");

                }

            })

            $scope.Getselectedproduct();

        };


        $scope.selectedproductmodel = {
            TradeId: 0,
            UserId: null,
            CategoryId: 0
        }
        $scope.price = "";
        $scope.isbn_number = "";
        $scope.Getselectedproduct = function () {
            //$scope.selectedproduct = [];
            $scope.selectedproduct = {};

            $scope.selectedproductmodel.TradeId = salewithusService.gettradeid();
            $scope.selectedproductmodel.CategoryId = salewithusService.getcatid();
            $scope.selectedproductmodel.TradeId = window.localStorage.getItem("Tradeid");
            $scope.selectedproductmodel.CategoryId = window.localStorage.getItem("single_catid");
            $scope.selectedproductmodel.TradeId = $scope.TradeId;
            $scope.selectedproductmodel.CategoryId = $scope.CatId;
            $scope.selectedproductmodel.UserId = window.localStorage.getItem('UserId');

            salewithusService.seletedproduct($scope.selectedproductmodel).then(function (response) {
                //  $window.location.reload();
                console.log(response.data.Result);
                //debugger;
                if (response.data.Status == "Success") {
                    // $scope.price = response.data.Result.Currency + " " + response.data.Result.c;
                    window.localStorage.setItem('TradeId', response.data.Result.TradeId);
                    window.localStorage.setItem('CategoryId', response.data.Result.CategoryId);
                    window.localStorage.setItem('CategoryName', response.data.Result.CategoryName);
                    window.localStorage.setItem('Related_userid', response.data.Result.UserId);
                    window.localStorage.setItem('ISBN', response.data.Result.ISBN_No);
                    $scope.selectedproduct = response.data.Result;
                    chatService.setcategoryId(response.data.Result.CategoryId);
                    chatService.settradeuserid(response.data.Result.UserId);
                    chatService.settradeuserName(response.data.Result.UserName);
                    chatService.settradeuserImage(response.data.Result.UserImage);
                    chatService.settradename(response.data.Result.ItemName);
                    chatService.settradetime(response.data.Result.CreatedDateTime);
                    Lattitude_ = response.data.Result.Lattitude;
                    Longitude_ = response.data.Result.Longitude;

                    //window.localStorage.setItem('Lattitude', response.data.Result.Lattitude);
                    //window.localStorage.setItem('Longitude', response.data.Result.Longitude);
                    $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                    $scope.latlong();
                    $scope.GetLocationName();
                    $scope.GetRelatedProducts();
                }
                else {
                    alert("Something Went Wrong!!");
                }
            });
        };

        $scope.check_isbn = function () {

            $scope.isbn_number = window.localStorage.getItem('ISBN');
            if ($scope.isbn_number == "") {
                // window.localStorage.removeItem('ISBN')
                return false;
            }
            else {
                //  window.localStorage.removeItem('ISBN')
                return true;
            }
        }

        $scope.checkcollegeId = function (collegeid) {
            if (collegeid != undefined) {
                return true;
            }
            else {
                return false;
            }
        }

        $scope.relatedproductmodel = {
            TradeId: 0,
            UserId: 0,
            CategoryId: 0,
            CategoryName: 0,

        };
        $scope.GetRelatedProducts = function () {
            //debugger;
            $scope.relatedproducts = [6];
            $scope.relatedproductmodel.TradeId = window.localStorage.getItem('TradeId');
            $scope.relatedproductmodel.CategoryId = window.localStorage.getItem('CategoryId');
            $scope.relatedproductmodel.TradeId = $scope.TradeId;
            $scope.relatedproductmodel.UserId = window.localStorage.getItem('UserId');
            //$scope.relatedproductmodel.CategoryId = $scope.CatId;
            $scope.relatedproductmodel.CategoryName = window.localStorage.getItem('CategoryName');


            tradeService.relatedproduct($scope.relatedproductmodel).then(function (response) {
                //  $window.location.reload();
                //debugger;
                if (response.data.Status == "Success") {
                    if (response.data.Message == "No records found.") {
                        $("#norecord_").show();
                    }
                    else {
                        $scope.relatedproducts = response.data.Result;
                    }


                    //swal("  Updated Succesfully!");
                    //debugger;
                    //Cleardata();
                    //$state.go("/*index*/");
                }
                else {
                    // alert("Something Went Wrong!!")
                }
            });


        };

        $scope.TradeData = {
            ItemName: "",
        };

        $scope.trade_model = {
            TradeId: 0,
            UserId: null,
            CategoryId: 0
        }
        $scope.Categoryname_ = "";
        $scope.rateperhour = false;
        $scope.GetTradeData = function () {


            // $scope.Getselectedproduct();
            //debugger;
            $scope.TradeData = [];
            $scope.trade_model.TradeId = window.localStorage.getItem('TradeId');
            $scope.trade_model.CategoryId = salewithusService.getcatidfrommytrades();

            $scope.trade_model.UserId = window.localStorage.getItem('UserId');

            tradeService.gettradedata($scope.trade_model).then(function success(response) {

                console.log(response);
                //debugger;
                $scope.TradeData = response.data.Result;


                console.log($scope.TradeData);
                //var position = $("#inptcate").index();
                //$scope.TradeData.CategoryId = $scope.categoryid[position];
                $("#inptcate").val($scope.TradeData.CategoryId);
                $("#itemname").val($scope.TradeData.ItemName);
                $("#descrt").val($scope.TradeData.Description);
                $("#short_description").val($scope.TradeData.short_description);
                $("#qty").val($scope.TradeData.Quantity);
                $("#long").val($scope.TradeData.Longitude);
                $("#lat").val($scope.TradeData.Lattitude);
                $("#collegename").val($scope.TradeData.CollegeName);
                $("#collegeid").val($scope.TradeData.CollegeId);
                $("#createddatetime").val($scope.TradeData.CreatedDateTime);

                $("#currency").val($scope.TradeData.Currency);
                $("#isbn").val(response.data.Result.ISBN_No);
                console.log("isbn:" + response.data.Result.ISBN_No)
                $scope.rateperhour = $scope.TradeData.IsRatePerHour;
                // $("#short_description").val($scope.TradeData[0].short_description);

                $("#price").val($scope.TradeData.Price);

                $("#categoryname").val($scope.TradeData.CategoryName);
                window.localStorage.setItem("tradedata_categoryname", $scope.TradeData.CategoryName);
                // tradeService.setcategoryname($scope.Categoryname_);
                $.LoadingOverlay("hide"); 
            },
                function error(response) {
                    $.LoadingOverlay("hide"); 
                    console.log("error");
                    // this function will be called when the request returned error status
                });
        };

        $scope.checkcategory_edit = function () {
            $scope.Categoryname_ = $("#categoryname").val();
            if ($scope.Categoryname_ == "Services") {
                return true;
            }
            else {
                return false;
            }
        }
        $scope.isbn = "";

        $scope.checkisbn_ = function () {
            //  $scope.isbn = $("#categoryname").val();
            $scope.isbn = window.localStorage.getItem("tradedata_categoryname");
            // $scope.isbn = $("#categoryname").val();
            if ($scope.isbn == "BOOK" || $scope.isbn == "Books") {


                // window.localStorage.removeItem("tradedata_categoryname")
                return true;
            }
            else {
                // window.localStorage.removeItem("tradedata_categoryname")
                return false;
            }
        }

        //getcharity_details_start//

        $scope.getFullDetailsOfcharity = function () {
            //debugger;
            $scope.GetCharityImages();
        };

        //charity_getneeds//
        $scope.image_ = "";
        $scope.name_ = "";
        $scope.userimage = "";

        $scope.charitymodel = {
            UserId: null
        }

        $scope.GetCharity = function () {

            $scope.charitydata = {};
            $scope.charityname = {};
            $scope.phnnumber = {};
            $scope.charitymodel.UserId = salewithusService.getuserid();
            $scope.charitymodel.UserId = window.localStorage.getItem("single_Userid");

            tradeService.getcharitydata($scope.charitymodel).then(function (response) {
                //  $window.location.reload();
                //debugger;
                if (response.data.Status == "Success") {

                    $scope.charitydata = response.data.Result.UserImage;
                    $scope.charityname = response.data.Result.FirstName;
                    $scope.phnnumber = response.data.Result.PhoneNumber;
                    //swal("  Updated Succesfully!");
                    //debugger;
                    //Cleardata();
                    //$state.go("/*index*/");
                }
                else {

                    // alert("Something Went Wrong!!")
                }
            });

            ////  $scope.image_ = window.localStorage.getItem("CharityImage");
            //  $scope.image_ = salewithusService.getcharityimage();
            // // $scope.name_ = window.localStorage.getItem("CharityName");
            //  $scope.name_ = salewithusService.getcharityname();
            //  $scope.userimage = $sce.trustAsHtml('<img src="' + $scope.image_ + '" id="photo-id" style="width:225px;height:225px;"  >');
            //  $(".charityname").text($scope.name_);
        }

        $scope.needs_ = {
            TradeId: 0,
            CategoryId: null,
            CategoryName: "",
            UserId: null
        }
        $scope.charity_ = [];
        $scope.GetRelatedneeds = function () {

            $scope.charity_ = [];
            // $scope.Getselectedproduct();
            $scope.needs_.TradeId = salewithusService.gettradeid();
            $scope.needs_.TradeId = window.localStorage.getItem("Tradeid");
            $scope.needs_.CategoryId = salewithusService.getcatid();
            $scope.needs_.CategoryId = window.localStorage.getItem("single_catid");
            $scope.needs_.TradeId = $scope.TradeId;
            $scope.needs_.CategoryId = $scope.CatId
            $scope.needs_.CategoryName = salewithusService.getcatname();
            $scope.needs_.UserId = null;

            // window.localStorage.setItem("single_Userid", ID);
            //$scope.needs_.UserId = 1002;
            salewithusService.needs($scope.needs_).then(function (response) {
                if (response.data.Status == "Success") {

                    if (response.data.Message == "No records found.") {
                        $("#norecord_").show();
                    }
                    else {
                        $scope.charity_ = response.data.Result;
                    }



                    // window.localStorage.setItem("trade_userid", response.data.Result[0].UserId);
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");




            });
        }


        $scope.likemodel = {
            TradeId: 0,
            UserId: 0,

        }

        $scope.id = 0;
        $scope.uid = 0;
        $scope.id + "";
        $scope.LikeDislike = function (TradeId, IsLiked) {
            $scope.id = $("#likebtn_" + TradeId);
            if ($($scope.id).attr("class") == "fa fa-heart-o") {
                // alert($($scope.id).attr("class"))
                $scope.Getdislike(TradeId);
            }
            else {
                // alert($($scope.id).attr("class"))

                $scope.Getlike(TradeId);
            }

        }

        $scope.Getlike = function (data) {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {

                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasaunfav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        // $(this).removeClass("fa fa-heart");
                        //$(this).addClass("fa fa-heart-o");
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart-o");
                        //  $scope.Getrecommendedtrades();

                        $scope.getFullDetailsOfTrade();
                        //  $scope.gettradesbycategory();
                        $scope.GetRelatedProducts();
                        $scope.Getalltradeafterlogin();
                        // swal(" Unfavourite !!");

                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };


        $scope.Getdislike = function (data) {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId !== null) {

                $scope.likemodel.TradeId = data;

                $scope.likemodel.UserId = window.localStorage.getItem('UserId');

                salewithusService.addedasafav($scope.likemodel).then(function (response) {


                    if (response.data.Status == "Success") {
                        //$("#likebtn").removeClass("fa fa-heart-o");
                        //$("#likebtn").addClass("fa fa-heart");
                        //$("#likebtn").show();
                        //$("#dislikebtn").hide();
                        //$window.location.reload();
                        $("#likebtn_" + $scope.likemodel.TradeId).removeClass("fa fa-heart-o");
                        $("#likebtn_" + $scope.likemodel.TradeId).addClass("fa fa-heart");
                        //$scope.Getrecommendedtrades();
                        $scope.Getalltradeafterlogin();
                        $scope.getFullDetailsOfTrade();

                        // $scope.gettradesbycategory();
                        $scope.GetRelatedProducts();
                        // $scope.Getalltradeafterlogin();
                        // swal("Added as a favourite !!");

                    }
                    else {
                        swal("Something Went Wrong!!");
                    }

                }, function error(response) {
                    console.log("error");
                });


            }
            else {
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }

        };
        //favourite_code_end

        $scope.usermodel = {
            userid: 0,
        }



        $scope.GetAllProductsCategory = function () {

            //debugger;
            $scope.AllProductsCategory = [];


            $http({
                method: 'GET',
                url: 'api/Category/GetCategoryList'

            }).then(function success(response) {
                //debugger;

                $scope.AllProductsCategory = response.data;
                window.localStorage.setItem('CategoryId', response.data.CategoryId);

                for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

                    if (i < 6) {
                        $scope.Categorylist2.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 6 && i < 12) {
                        $scope.Categorylist3.push($scope.AllProductsCategory[i]);

                    }
                    if (i >= 12 && i < 18) {
                        $scope.Categorylist4.push($scope.AllProductsCategory[i]);

                    }

                }


            },
                function error(response) {
                    console.log("error");

                    // this function will be called when the request returned error status
                });


        };

        $scope.subid = 0;

        $scope.selected_categoryname = "";
        $scope.AllSubCategory2 = [];
        $scope.GetAllSubCategory = function () {

            var selectedCategoryId = $scope.selectedCategory;//$scope.subid = data;
            $scope.subid = selectedCategoryId;
            //debugger;
            $scope.AllSubCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoriesNSubs'

            }).then(function success(response) {
                //debugger;
                $scope.AllSubCategory = response.data.Result;

                //debugger;

                for (var i = 0; i < $scope.AllSubCategory.length; i++) {

                    var obj = $scope.AllSubCategory[i];

                    if ($scope.AllSubCategory[i].CategoryId == $scope.subid) {
                        $scope.selected_categoryname = obj.CategoryName;
                        //if ($scope.selected_categoryname == "Bag") {
                        //    $("#rateperhour").show();
                        //}
                        //else {
                        //    $("#rateperhour").hide();
                        //}
                        salewithusService.setcategoryname($scope.selected_categoryname);
                        if (obj.Subcategories.length > 0) {

                            $('#SubCategoryList').show();
                            $scope.AllSubCategory2 = obj.Subcategories;
                            window.localStorage.setItem("SubCatIsAvailable", "true");

                        }
                        else {
                            window.localStorage.setItem("SubCatIsAvailable", "false");
                            $('#SubCategoryList').hide();
                            swal({
                                text: "No Subcategories are available for this category.",
                                button: "Ok!",
                            });
                        }
                    }
                }


            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });


        };


        $scope.CurrencyType = [];
        $scope.selectedCurrency = "";

        $scope.Getallcurrencytype = function () {

            //debugger;
            $scope.CurrencyType = [];

            $http({
                method: 'GET',
                url: 'api/Trades/GetCurrencyList'

            }).then(function success(response) {
                //debugger;
                $scope.CurrencyType = response.data.Result;

                //debugger;

            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });

        };



        $scope.checkcategory = function () {
            $scope.selected_categoryname = salewithusService.getcategoryname();
            if ($scope.selected_categoryname == "Services") {
                return true;

            }
            else {
                return false;
            }
        }
        $scope.checkcategory_ = function () {
            $scope.selected_categoryname = salewithusService.getcategoryname();
            if ($scope.selected_categoryname == "Books") {
                return true;

            }
            else {
                return false;
            }
        }


        $scope.GetTradeImagesByTradeId = function () {
            $scope.TradeImagesByTradeId = [];
            //$scope.TradeID = $scope.Trade.TradeID = window.localStorage.getItem("TradeId");

            $http({
                method: 'GET',
                url: 'api/Trades/GetTradeImages?TradeId=' + $scope.TradeId

            }).then(function success(response) {
                //debugger;
                $scope.TradeImagesByTradeId = response.data.Status;
            },
                function error(response) {
                    console.log("error");
                    // this function will be called when the request returned error status
                });
        }

        $scope.AllProductsCategory = [];
        $scope.categoryid = [];
        $scope.selectedCategory = 0;
        $scope.GetAllProductsCategory = function () {


            //debugger;
            $scope.AllProductsCategory = [];

            $http({
                method: 'GET',
                url: 'api/Category/GetCategoryList'

            }).then(function success(response) {


                //debugger;
                $scope.AllProductsCategory = response.data;
                //window.localStorage.setItem('CategoryId', response.data.CategoryId);

                $scope.categoryid.push(0);
                for (var i = 0; i < $scope.AllProductsCategory.length; i++) {

                    $scope.categoryid.push($scope.AllProductsCategory[i].CategoryId);
                    // alert($scope.categoryid);

                }


            },
                function error(response) {
                    console.log("error");

                    // this function will be called when the request returned error status
                });


        };
        $scope.email = "";
        $scope.showMsgs_ = false;
        $scope.trademodel = {

            UserId: 0,
            CollegeId: null,
            CategoryId: null,
            CategoryName: "",
            CollegeName: "",
            UserName: "",
            ItemName: "",
            Description: "",
            Longitude: 0.0,
            Lattitude: 0.0,
            Condition: "",
            Quantity: "",
            CreatedDateTime: null,
            ModifiedDateTime: null,
            CreatedBy: "",
            IpAddress: "",
            Size: "",
            Price: null,
            IsActive: null,
            short_description: "",
            TradeImage: "",
            IsRatePerHour: false,
            Currency: "",
            ISBN_No: ""
        };

        //$scope.posttradedata = function (trademodel) {

        //    /* 
        //     public Nullable<int> TradeId { get; set; }



        //     */
        //    $scope.trademodel.UserId = window.localStorage.getItem("UserId");
        //    $scope.trademodel.CollegeId = trademodel.CollegeId;

        //    /* code to get category id */

        //    //var position = $("#inputGroupSelect04 option:selected").index();
        //    //$scope.trademodel.CategoryId = $scope.categoryid[position];

        //    var CategoryId = $scope.selectedCategory;
        //    var SubCategoryId = $scope.selectedSubCategory;

        //        if (SubCategoryId == "") {
        //            $scope.trademodel.CategoryId = CategoryId;
        //        }

        //        else {
        //            $scope.trademodel.CategoryId = SubCategoryId;
        //        }

        //    /* code to get category id */

        //    $scope.trademodel.CategoryName = $("#inputGroupSelect04").val();
        //    $scope.trademodel.ItemName = trademodel.ItemName;
        //    $scope.trademodel.Description = trademodel.Description;
        //    if (SelectedLongitude !== 0) {
        //        $scope.trademodel.Longitude = SelectedLongitude;
        //    }
        //    else {

        //        $scope.trademodel.Longitude = $scope.lan;
        //    }


        //    if (SelectedLatitude !== 0) {
        //        $scope.trademodel.Lattitude = SelectedLatitude;
        //    }
        //    else {

        //        $scope.trademodel.Lattitude = $scope.lat;
        //    }
        //    $scope.trademodel.Quantity = trademodel.Quantity;
        //    $scope.trademodel.Price = trademodel.Price;
        //    $scope.trademodel.short_description = trademodel.short_description;


        //    if (CategoryId && SubCategoryId !== "" || CategoryId || SubCategoryId !== "" ) {
        //        if ($scope.trademodel.Quantity != "") {
        //            if ($scope.trademodel.Price != "") {
        //                tradeService.posttradedata($scope.trademodel).then(function (response) {
        //                    //  $window.location.reload();
        //                    //debugger;
        //                    if (response.data.Status == "Success") {
        //                        TradeId = response.data.Result.TradeId;
        //                        window.localStorage.setItem("TradeId", response.data.Result.TradeId);
        //                        window.localStorage.setItem("CategoryId", response.data.Result.CategoryId);
        //                        //  window.localStorage.setItem("CategoryName", response.data.Result.CategoryName);

        //                        if (confirm('You have posted trade succesfully!')) {
        //                            // Save it!
        //                            Cleardata(trademodel);
        //                            $("#uploadimages_").show();
        //                        } else {
        //                            // Do nothing!
        //                            $("#uploadimages_").hide();
        //                        }
        //                        //swal("You have posted trade succesfully!");
        //                       // Cleardata(trademodel);
        //                        //debugger;


        //                        // $state.go("UserProfile");
        //                    }
        //                    else {
        //                        alert("Something Went Wrong!!")
        //                    }


        //                });
        //            }
        //            else {
        //                $scope.showMsgs_ = true;
        //            }
        //        }
        //        else {
        //            $scope.showMsgs = true;
        //        }
        //    }
        //    else {

        //        //alert("Please select category");
        //    }

        //}



        $scope.posttradedata = function (trademodel) {


            /* 
             public Nullable<int> TradeId { get; set; }
        
             */
            var facbookid = window.localStorage.getItem("FacebookId");
            $scope.trademodel.UserId = window.localStorage.getItem("UserId");
            $scope.email = window.localStorage.getItem("UserName");
            if ($scope.email.includes(".edu") || facbookid == null) {
                $scope.trademodel.CollegeId = window.localStorage.getItem("CollegeId");
            }
            else {
                $scope.trademodel.CollegeId = null;
            }

            /* code to get category id */

            //var position = $("#inputGroupSelect04 option:selected").index();
            //$scope.trademodel.CategoryId = $scope.categoryid[position];

            var CategoryId = $scope.selectedCategory;
            var SubCategoryId = $scope.selectedSubCategory;

            if (SubCategoryId == "") {
                $scope.trademodel.CategoryId = CategoryId;
            }

            else {
                $scope.trademodel.CategoryId = SubCategoryId;
            }

            /* code to get category id */

            $scope.trademodel.CategoryName = $("#inputGroupSelect04").val();
            $scope.trademodel.ItemName = trademodel.ItemName;
            $scope.trademodel.Description = trademodel.Description;
            if (SelectedLongitude !== 0) {
                $scope.trademodel.Longitude = SelectedLongitude;
            }
            else {

                $scope.trademodel.Longitude = $scope.lan;
            }


            if (SelectedLatitude !== 0) {
                $scope.trademodel.Lattitude = SelectedLatitude;
            }
            else {
                $scope.trademodel.Lattitude = $scope.lat;
            }

            $scope.trademodel.Quantity = trademodel.Quantity;
            $scope.trademodel.Price = trademodel.Price;
            $scope.trademodel.Currency = $scope.selectedCurrency;
            $scope.trademodel.ISBN_No = trademodel.ISBN_No;
            $scope.trademodel.short_description = trademodel.short_description;
            if ($('#rateperhour').is(':checked')) {
                $scope.trademodel.IsRatePerHour = true;
            }
            else {
                $scope.trademodel.IsRatePerHour = false;
            }

            var subcatavail = window.localStorage.getItem("SubCatIsAvailable");

            if (subcatavail == "true") {

                if (SubCategoryId == "") {

                    alert("Please select Subcategory");

                }
                else {

                    if ($scope.trademodel.Quantity != "") {
                        if ($scope.trademodel.Price != "") {
                            if ($scope.trade_post.$valid) {

                                tradeService.posttradedata($scope.trademodel).then(function (response) {
                                    //  $window.location.reload();
                                    //debugger;
                                    if (response.data.Status == "Success") {
                                        TradeId = response.data.Result.TradeId;
                                        window.localStorage.setItem("TradeId", response.data.Result.TradeId);
                                        window.localStorage.setItem("CategoryId", response.data.Result.CategoryId);
                                        $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                                        //  window.localStorage.setItem("CategoryName", response.data.Result.CategoryName);

                                        if ($scope.usertype_ == 1) {
                                            if (confirm('You have posted trade succesfully.Do you want to add images for posted trade?')) {
                                                // Save it!
                                                //Cleardata(trademodel);
                                                $('#rateperhour').removeAttr('checked');
                                                // $("#uploadimages_").show();
                                                $state.go("UploadImages");
                                            }
                                            else {

                                                //  $("#uploadimages_").hide();

                                                $state.go("UserProfile");


                                                // $state.go("my_needs");

                                            }
                                        }
                                        else {
                                            if (confirm('You have posted needs succesfully.Do you want to add images?')) {
                                                // Save it!
                                                Cleardata(trademodel);
                                                //   $("#uploadimages_").show();
                                                $state.go("UploadImages");
                                            }
                                            else {

                                                //  $("#uploadimages_").hide();

                                                //    

                                                if ($scope.usertype_ == 1) {
                                                    $state.go("UserProfile");
                                                }
                                                else {
                                                    $state.go("my_needs");

                                                }

                                            }
                                        }

                                    }
                                    else {
                                        alert("Something Went Wrong!!")
                                    }


                                });
                            }
                            else {

                            }

                        }
                        else {
                            $scope.showMsgs_ = true;
                        }
                    }
                    else {
                        $scope.showMsgs = true;
                    }
                }
            }
            else {

                if (CategoryId == "") {

                    alert("Please select category");
                }
                else {
                    if ($scope.trade_post.$valid) {
                        tradeService.posttradedata($scope.trademodel).then(function (response) {
                            //  $window.location.reload();
                            //debugger;
                            if (response.data.Status == "Success") {
                                TradeId = response.data.Result.TradeId;
                                window.localStorage.setItem("TradeId", response.data.Result.TradeId);
                                window.localStorage.setItem("CategoryId", response.data.Result.CategoryId);
                                //  window.localStorage.setItem("CategoryName", response.data.Result.CategoryName);
                                $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                                if ($scope.usertype_ == 1) {
                                    if (confirm('You have posted trade succesfully.Do you want to add images for posted trade?')) {
                                        // Save it!
                                        //Cleardata(trademodel);
                                        $('#rateperhour').removeAttr('checked');
                                        // $("#uploadimages_").show();
                                        $state.go("UploadImages");
                                    }
                                    else {

                                        //  $("#uploadimages_").hide();

                                        $state.go("UserProfile");


                                        // $state.go("my_needs");

                                    }
                                }
                                else {
                                    if (confirm('You have posted needs succesfully.Do you want to add images?')) {
                                        // Save it!
                                        Cleardata(trademodel);
                                        //   $("#uploadimages_").show();
                                        $state.go("UploadImages");
                                    }
                                    else {

                                        //  $("#uploadimages_").hide();

                                        //    

                                        if ($scope.usertype_ == 1) {
                                            $state.go("UserProfile");
                                        }
                                        else {
                                            $state.go("my_needs");

                                        }

                                    }
                                }
                            }
                            else {
                                alert("Something Went Wrong!!")
                            }


                        });
                    }
                    else {

                    }

                }
            }

        }


        //function Cleardata(trademodel) {
        //    //debugger;
        //    $scope.trademodel.CategoryName = "";
        //    $scope.trademodel.ItemName = "";
        //    $scope.trademodel.Description = "";
        //    $scope.trademodel.Longitude = "";
        //    $scope.trademodel.Lattitude = "";
        //    $scope.trademodel.Quantity = "";
        //    $scope.trademodel.Price = "";
        //    $scope.trademodel.ISBN_No = "";
        //    $scope.trademodel.short_description = "";


        //};

        $scope.Tmodel = {

            UserId: 0,
            CollegeId: null,
            CategoryId: null,
            CategoryName: "",
            CollegeName: "",
            UserName: "",
            ItemName: "",
            Description: "",
            Longitude: 0.0,
            Lattitude: 0.0,
            Condition: "",
            Quantity: "",
            CreatedDateTime: null,
            ModifiedDateTime: null,
            CreatedBy: "",
            IpAddress: "",
            Size: "",
            Price: "",
            IsActive: null,
            short_description: "",
            TradeImage: "",
            IsLiked: false,
            PageNumber: 1,
            PageSize: 12
        };
        $scope.AllTrade_ = [];
        $scope.totalcount = 0;
        $scope.Getalltradeafterlogin = function () {
            $scope.AllTrade = [];
            $scope.Tmodel.UserId = window.localStorage.getItem('UserId');
            $scope.Tmodel.PageNumber = pagenumber;


            salewithusService.tradeafterlogin($scope.Tmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.AllTrade = response.data.Result;
                    for (var i = 0; i < $scope.AllTrade.length; i++) {
                        var obj = $scope.AllTrade[i];
                        $scope.totalcount = $scope.AllTrade[i].TotalCount;
                        $scope.AllTrade_.push($scope.AllTrade[i]);
                        //pagenumber = 1;
                        $("#loader").hide();
                        $("#btn_spin").show();
                    }

                    if ($scope.totalcount == $scope.AllTrade_.length) {
                        $("#btn_spin").hide();
                    }
                    else {
                        $("#btn_spin").show();
                    }


                    //salewithusService.settrades(response.data.Result);
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.collegetrade_model = {
            UserId: null,
            PageNumber: 1,
            PageSize: 12
        }
        $scope.collegetrade = [];
        $scope.collegetrades = function () {
            $.LoadingOverlay("show");
            $scope.allcollegetrades = []
            $scope.collegetrade_model.UserId = window.localStorage.getItem('UserId');
            $scope.collegetrade_model.PageNumber = pagenumber;

            tradeService.collegetrades($scope.collegetrade_model).then(function (response) {
                if (response.data.Status == "Success") {
                    $.LoadingOverlay("hide");
                    $scope.allcollegetrades = response.data.Result;

                    for (var i = 0; i < $scope.allcollegetrades.length; i++) {
                        var obj = $scope.allcollegetrades[i];
                        $scope.totalcount = $scope.allcollegetrades[i].TotalCount;
                        $scope.collegetrade.push($scope.allcollegetrades[i]);
                        $("#loader").hide();
                        $("#btn_spin").show();
                    }
                    if ($scope.totalcount == $scope.collegetrade.length) {
                        $("#btn_spin").hide();
                    }
                    else {
                        $("#btn_spin").show();
                    }


                }
                else {
                    swal("Something Went Wrong!!");
                    $.LoadingOverlay("hide");
                }

            }, function error(response) {
                console.log("error");
                $.LoadingOverlay("hide");
            });

        }

        $scope.data = "";
        $scope.check_mail = function () {
            $scope.data = window.localStorage.getItem("UserName");
            if ($scope.data != null || $scope.data != undefined) {
                if ($scope.data.includes(".edu")) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }

        $scope.CollegeId = 0;
        $scope.StartsWith = "";

        $scope.university_model = {
            StartsWith: ""
        }

        $scope.getuniversity = function (StartsWith) {
            $("#list").show();
            $scope.university = [];
            $scope.university_model.StartsWith = StartsWith;
            salewithusService.university($scope.university_model).then(function (response) {


                if (response.data.Status == "Success") {

                    // swal("Updated Successfully!!");
                    $scope.university = response.data.Result;
                    $scope.CollegeId = salewithusService.setcollegeid(response.data.Result.CollegeId);

                }
                else {
                    //  swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.fillTextbox = function (data, collegeid) {
            $scope.StartsWith = data;
            // console.log("sss:"+ $scope.StartsWith);
            window.localStorage.setItem("CollegeId", collegeid);
            salewithusService.setuniversityid(collegeid);
            $scope.university = null;
            $("#list").hide();
        }



        $scope.edittrade = {
            Tradeid: 0,
            UserId: null,
            CollegeId: null,
            CategoryId: null,
            ItemName: "",
            Description: "",
            Longitude: 0.0,
            Lattitude: 0.0,
            Condition: "",
            Quantity: "",
            CreatedDateTime: null,
            ModifiedDateTime: null,
            CreatedBy: "",
            IpAddress: "",
            Size: "",
            Price: 0,
            IsActive: false,
            Short_Description: null,
            IsRatePerHour: false,
            Currency: "",
            ISBN_No: ""
        };


        $scope.GetSaveChanges = function (edittrade) {
            //debugger;
            $scope.edittrade.Tradeid = window.localStorage.getItem('TradeId');
            //  $scope.Tradeid = edittrade.Tradeid;
            $scope.edittrade.UserId = window.localStorage.getItem('UserId');
            $scope.email = window.localStorage.getItem("UserName");
            if ($scope.email.includes(".edu")) {

                if ($scope.edittrade.CollegeId == "") {


                    $scope.edittrade.CollegeId = $("#collegeid").val();
                }
                else {
                    $scope.edittrade.CollegeId = window.localStorage.getItem("CollegeId");
                }

            }
            else {

                $scope.edittrade.CollegeId = null;
            }

            //  $scope.edittrade.CategoryId = edittrade.CategoryId;

            if ($scope.edittrade.CategoryId != null) {
                $scope.edittrade.ItemName = $("#inptcate").val();
            }
            else {
                $scope.edittrade.CategoryId = $("#inptcate").val();

            }



            if ($scope.edittrade.ItemName != null) {
                $scope.edittrade.ItemName = $("#itemname").val();
            }
            else {
                $scope.edittrade.ItemName = edittrade.ItemName;

            }

            // $scope.edittrade.ItemName = edittrade.ItemName;
            if ($scope.edittrade.Description != null) {
                $scope.edittrade.Description = $("#descrt").val();
            }
            else {
                $scope.edittrade.Description = edittrade.Description;

            }
            // $scope.edittrade.Description = edittrade.Description;

            if ($scope.edittrade.Short_Description == null) {
                $scope.edittrade.Short_Description = $("#short_description").val();
            }
            else {
                $scope.edittrade.Short_Description = edittrade.short_description;

            }
            if ($scope.edittrade.Longitude != 0.0) {

                $scope.edittrade.Longitude = SelectedLongitude_;
            }
            else {
                $scope.edittrade.Longitude = $("#long").val();
            }

            if ($scope.edittrade.Lattitude != 0.0) {

                $scope.edittrade.Lattitude = SelectedLatitude_;
            }
            else {
                $scope.edittrade.Lattitude = $("#lat").val();
            }

            //$scope.edittrade.Lattitude = $("#lat").val();
            $scope.edittrade.Condition = edittrade.Condition;
            // $scope.edittrade.Quantity = edittrade.Quantity;
            if ($scope.edittrade.Quantity != null || $scope.edittrade.Quantity != "") {
                $scope.edittrade.Quantity = $("#qty").val();
            }
            else {
                $scope.edittrade.Quantity = edittrade.Quantity;

            }

            $scope.edittrade.CreatedDateTime = $("#createddatetime").val();


            // $scope.edittrade.CreatedDateTime = $("#createddatetime").val;
            $scope.edittrade.ModifiedDateTime = edittrade.ModifiedDateTime;
            $scope.edittrade.CreatedBy = edittrade.CreatedBy;
            $scope.edittrade.IpAddress = edittrade.IpAddress;
            $scope.edittrade.Size = edittrade.Size;
            if ($scope.edittrade.Price != null) {
                $scope.edittrade.Currency = $("#currency").val();

                $scope.edittrade.Price = $("#price").val();
            }
            else {

                $scope.edittrade.Price = edittrade.Price;
                $scope.edittrade.Currency = $scope.selectedCurrency;

            }
            if ($('#rateperhour').is(':checked')) {
                $scope.edittrade.IsRatePerHour = true;
            }
            else {
                $scope.edittrade.IsRatePerHour = false;
            }
            // $scope.edittrade.Price = edittrade.Price;
            $scope.edittrade.IsActive = edittrade.IsActive;

            if ($scope.edittrade.ISBN_No != "") {
                $scope.edittrade.ISBN_No = $("#isbn_number").val();

            }
            else {

                $scope.edittrade.ISBN_No = edittrade.ISBN_No;

            }



            if ($scope.edittrade.ItemName != "") {

                if ($scope.edittrade.Price != null) {
                    tradeService.Updatetrade($scope.edittrade).then(function (response) {
                        //  $window.location.reload();
                        //debugger;
                        if (response.data.Status == "Success") {

                            swal("  Updated Succesfully!");
                            $scope.edittrade.CollegeId = window.localStorage.removeItem("CollegeId");
                            //debugger;
                            // Cleardata();
                            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                            if ($scope.usertype_ == 1) {
                                $state.go("UserProfile");
                            }
                            else {
                                $state.go("my_needs");
                            }

                        }
                        else {
                            alert("Something Went Wrong!!")
                        }
                    });
                }
                else {
                    $scope.message__ = true;
                }

            }
            else {
                $scope.message = true;
            }

        };

        $scope.Trade = {
            TradeId: 0,
            TradeImages: [],

        };

        $scope.imageurl = [];
        //function to save  data //

        $scope.isDisabled = false;
        $scope.saveDataTrade = function () {
            //debugger;
            //$scope.Trade.TradeId = Trade.TradeId;
            //$scope.Trade.UserId = Trade.UserId;
            finalsrcdata = [];
            $scope.isDisabled = true;
            for (k = 0; k < imagesjson.length; k++) {

                var pos = parseInt(imagesjson[k]);

                finalsrcdata.push(srcData[pos]);
            }

            console.log("Length is" + finalsrcdata.length);



            //$scope.Trade.TradeID = 1;
            $scope.Trade.TradeId = TradeId;


            //alert(srcData.length);

            for (var i = 0; i < finalsrcdata.length; i++) {

                $scope.imageData = finalsrcdata[i];

                //if (i == srcData.length - 1) {
                //    $scope.Trade.Image = $scope.Trade.Image + $scope.imageData.substr($scope.imageData.indexOf(',') + 1);
                //}
                //else {
                //    $scope.Trade.Image = $scope.Trade.Image + $scope.imageData.substr($scope.imageData.indexOf(',') + 1) + ",";
                //}
                $scope.imageurl.push($scope.imageData.substr($scope.imageData.indexOf(',') + 1));
            }

            $scope.Trade.TradeImages = $scope.imageurl;

            if ($scope.Trade.TradeId != "") {
                if ($scope.Trade.TradeImages != "") {
                    tradeService.AddTrade($scope.Trade).then(function (response) {
                        //  $window.location.reload();
                        $scope.GetuploadedImages();
                        //debugger;
                        if (response.data.Status == "Success") {
                            // window.localStorage.setItem('')
                            //swal("Uploaded!1");
                            count = 0;
                            imagesjson.shift();
                            srcData.shift();

                            $("#inputFileToLoad").val(null);
                            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                            //debugger;
                            if ($scope.usertype_ == 1) {
                                $state.go("UserProfile");
                            }
                            else {
                                $state.go("my_needs");
                            }
                            // Cleardata(Trade);

                        }
                        else {
                            alert("Something Went Wrong!!")
                        }
                    })
                }
                else {
                    alert("Please select images.");
                }
            }
            else {
                alert("Please fill the above details");
            }

        }

        $scope.usertype_ = 0;
        $scope.saveDataTrade_edited = function () {
            finalsrcdata = [];
            $scope.isDisabled = true;
            //debugger;
            $scope.GetuploadedImages();
            length = imagesdata_.length + imagesjson.length;
            totallength = 5 - imagesdata_.length;
            $scope.Trade.TradeId = window.localStorage.getItem('TradeId');
            //   $scope.TradeImages_ = response.data.Result;
            if (length < 6) {


                for (k = 0; k < imagesjson.length; k++) {

                    var pos = parseInt(imagesjson[k]);

                    finalsrcdata.push(srcData[pos]);
                }

                console.log("Length is" + finalsrcdata.length);

                for (var i = 0; i < finalsrcdata.length; i++) {

                    $scope.imageData = finalsrcdata[i];

                    //if (i == srcData.length - 1) {
                    //    $scope.Trade.Image = $scope.Trade.Image + $scope.imageData.substr($scope.imageData.indexOf(',') + 1);
                    //}
                    //else {
                    //    $scope.Trade.Image = $scope.Trade.Image + $scope.imageData.substr($scope.imageData.indexOf(',') + 1) + ",";
                    //}
                    $scope.imageurl.push($scope.imageData.substr($scope.imageData.indexOf(',') + 1));
                }

                $scope.Trade.TradeImages = $scope.imageurl;

                if ($scope.Trade.TradeImages != "") {
                    tradeService.AddTrade($scope.Trade).then(function (response) {
                        //  $window.location.reload();

                        //debugger;
                        if (response.data.Status == "Success") {
                            // window.localStorage.setItem('')
                            //swal("Uploaded!2");
                            count = 0;
                            imagesjson.shift();
                            srcData.shift();
                            //debugger;
                            //Cleardata(Trade);
                            $scope.usertype_ = window.localStorage.getItem("UserTypeID");
                            if ($scope.usertype_ == 1) {
                                $state.go("UserProfile");
                            }
                            else {
                                $state.go("my_needs");
                            }

                        }
                        else {
                            alert("Something Went Wrong!!")
                        }
                    })
                }
                else {
                    alert("Please select images.")
                }
            }
            else {
                alert("Previously you have uploaded " + " " + imagesdata_.length + " " + "images.You can upload " + " " + totallength + " " + "images.Total images should not be more than 5");
                $scope.isDisabled = false;
                //imagesjson.shift();
                //srcData.shift();

                //var placeToInsertImagePreview = document.getElementById("gallery_new");

                //if (placeToInsertImagePreview.files.length != 0)
                //    filesSelected.files = "";
                //$scope.loadImageFileAsURL1();

            }

        }

        $scope.setlatvalue = [];
        $scope.setlngvalue = [];
        $scope.latlongmodel = {
            lat: 0.0,
            lng: 0.0,

        };
        $scope.latlong = function () {

            $scope.setlatvalue = [];
            $scope.setlngvalue = [];
            //$scope.Getselectedproduct();
            //  $scope.latlongmodel.lat = window.localStorage.getItem('Lattitude');
            $scope.latlongmodel.lat = Lattitude_;

            // $scope.latlongmodel.lng = window.localStorage.getItem('Longitude');
            $scope.latlongmodel.lng = Longitude_;

            $scope.setlatvalue = $scope.latlongmodel.lat;
            $scope.setlngvalue = $scope.latlongmodel.lng;

        }
        $scope.LocationName = "";
        $scope.GetLocationName = function () {
            //debugger;
            $scope.results = [];
            $scope.latlong();
            var lat = parseFloat($scope.setlatvalue);
            var lng = parseFloat($scope.setlngvalue);
            //var geocoder = new google.maps.Geocoder();
            //$scope.results = geocoder.getFromLocation(lat, lng, 1);
            var geocoder = new google.maps.Geocoder();

            var yourLocation = new google.maps.LatLng(lat, lng);

            geocoder.geocode({ 'location': yourLocation }, function (results, status) {
                //debugger;
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                        for (var i = 0; i < results.length; i++) {
                            if (results[i].types[0] === "locality") {
                                var city = results[i].address_components[0].short_name;
                                var state = results[i].address_components[2].short_name;
                                $("#loc_Name").val(city + ", " + state);
                                $scope.LocationName = city + ", " + state;
                            }
                        }
                    }
                    else {
                        //error('Google did not return any results.');
                    }
                }
                else {
                    //error("Reverse Geocoding failed due to: " + status);
                }
            });
        }

        function error(msg) {
            alert(msg);
        }

        $scope.GetLatLong = function () {

            $scope.latlong();
            var lat = parseFloat($scope.setlatvalue);
            var lng = parseFloat($scope.setlngvalue);

            var location = {
                "lat": lat,
                "lng": lng
            }
            map = new google.maps.Map(document.getElementById('trade_map'), {
                //center: { lat: 21.145800, lng: 79.088155 },
                center: { lat: lat, lng: lng },
                zoom: 8
            });
            var marker = new google.maps.Marker({
                map: map,
                position: { lat: lat, lng: lng }
            });
        }
        $scope.BindLocation = function () {
            var input = document.getElementById('input1-pac');
            var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.addListener('place_changed', function () {
                var place = autocomplete.getPlace();
                SelectedLongitude = place.geometry.location.lng();
                SelectedLatitude = place.geometry.location.lat();
            });
        }
        $scope.BindLocation_edit = function () {
            var input = document.getElementById('input1-pac-edit');
            var autocomplete = new google.maps.places.Autocomplete(input);
            autocomplete.addListener('place_changed', function () {
                var place = autocomplete.getPlace();
                SelectedLongitude_ = place.geometry.location.lng();
                SelectedLatitude_ = place.geometry.location.lat();
            });
        }

        $scope.chatWithSeller = function () {
            var UserId = window.localStorage.getItem('UserId');
            if (UserId == null) {
                $state.go("index");
                // $("#myModal").show();
                //$state.go("index");
                swal({
                    title: "Please Login!",
                    text: "You have to login before proceeding!",
                    //icon: "error",
                    button: "Ok!",
                });
            }
            else {
                var chattradeId = window.localStorage.getItem("Tradeid");
                // var chattradeId = salewithusService.gettradeid();
                chatService.settradeid(chattradeId);
                chatService.setfrompage("single");
                chatService.setchatWithSeller("chatWithSeller");

                //$state.go("chat", {}, { reload: true });
                $state.go("chat");
            }
        }

        //get_currect_location_start//
        $scope.mysrclat = "";
        $scope.lat = "";
        $scope.lan = "";
        $scope.nearme = function () {
            //debugger;
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (position) {
                    mysrclat = position.coords.latitude;
                    mysrclong = position.coords.longitude;
                    console.log("lat", mysrclat);
                    console.log("ong", mysrclong);
                    // Use either $scope.$apply() or $scope.evalAsync not both for same result
                    //$scope.$apply()  
                    $scope.$apply(function () {
                        $scope.lat = mysrclat;
                        $scope.lan = mysrclong;
                    })
                    //$scope.$evalAsync()
                    $scope.$evalAsync(function () {
                        $scope.elat = mysrclat;
                        $scope.elan = mysrclong;
                    })


                });
            }

        }
        //get_currect_location_end//
        $scope.TradeImages_ = [];
        $scope.imagemodel = {
            TradeId: 0,
        };
        $scope.imageids = [];
        $scope.TradeImages_ = [];
        $scope.GetuploadedImages = function () {
            $scope.TradeImages_ = [];
            $scope.imagemodel.TradeId = window.localStorage.getItem('TradeId');

            tradeService.tradeimages($scope.imagemodel).then(function (response) {
                //  $window.location.reload();

                if (response.data.Status == "Success") {

                    $scope.TradeImages_ = response.data.Result;
                    imagesdata_ = response.data.Result;
                    $scope.imageids = response.data.Result[0].ImageId;

                }

            })

        };
        $scope.checklength = function () {
            if ($scope.TradeImages_.length != 5) {
                console.log("tradeimages:" + $scope.TradeImages_.length);
                return true;
            }
            else {
                return false;
            }
        }

        $scope.tradeImages_model = {
            ImageIds: [],
            TradeId: 0,

        }
        var ImageId = [];
        $scope.deleteTradeImages = function (data, imageid) {
            $scope.ImageId = [];
            $scope.ImageId = imageid;
            ImageId = $scope.ImageId;
            $scope.tradeImages_model.ImageIds = [ImageId];
            $scope.tradeImages_model.TradeId = data;

            salewithusService.deletetradeImages($scope.tradeImages_model).then(function (response) {

                if (response.data.Status == "Success") {
                    //$window.location.reload();
                    //  $scope.GetTradeByUserId();
                    swal("Trade images Deleted Successfully!!");
                    $scope.GetuploadedImages();
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });
        }

        $scope.$on("fileSelected", function (event, args) {

            var item = args;
            $scope.files.push(item);
            var reader = new FileReader();
            reader.addEventListener("load", function () {
                $scope.$apply(function () {
                    item.src = reader.result;

                });
            }); false();
            if (item.file) {
                reader.readAsDataURL(item.file);
            }

        });

        //offer_start
        $scope.id = 0;
        $scope.userData = [];
        $scope.GetuserData = function () {
            //debugger;
            $scope.userData = [];
            $scope.id = window.localStorage.getItem('UserId');

            $http({
                method: 'GET',
                url: 'api/Login/SearchdataByuserId?UserId=' + $scope.id

            }).then(function success(response) {
                console.log(response);
                //debugger;
                $scope.userData = response.data.Result[0].FirstName;

                console.log($scope.userData);

            },
                function error(response) {

                    console.log("error");
                    // this function will be called when the request returned error status
                });
        };

        $scope.offer_model = {
            FromUserId: 0,
            ToUserId: 0,
            TradeId: 0,
            Message: "",
            CreatedDateTime: "",
            IsRead: false,
            DeletedByUserId: "",
            IsOfferedMsg: false,
        }
        $scope.offer_msg = false;
        $scope.Note = "";
        $scope.offer_ = function (offer_model) {

            var hasNumber = /\d/;
            $scope.offer_model.FromUserId = window.localStorage.getItem("UserId");
            $scope.offer_model.ToUserId = chatService.gettradeuserid();
            $scope.offer_model.TradeId = $scope.TradeId;
            $scope.userData = window.localStorage.getItem("FirstName");
            // $scope.offer_model.Message = $scope.userData + " " + "has offered this trade for" + " " + "$" + offer_model.Message;
            $scope.offer_model.Message = offer_model.Message + " " + $scope.Note;
            if (offer_model.Message != "") {
                if (hasNumber.test(offer_model.Message)) {
                    $scope.offer_model.IsOfferedMsg = true;
                }

                salewithusService.offer_($scope.offer_model).then(function (response) {

                    if (response.data.Status == "Success") {
                        //$window.location.reload();
                        //  $scope.GetTradeByUserId();
                        var chattradeId = salewithusService.gettradeid();
                        chatService.settradeid(chattradeId);
                        chatService.setfrompage("single");
                        swal("Message Sent Successfully!!");
                        $("#modal .close").hide();
                        //$state.go("chat");
                        $("#myOffer").hide();
                        $(".modal-backdrop").hide();

                        $state.go("Chat");
                    }
                    else {
                        $("#modal .close").hide();
                        swal("You cannot offer to yourself !!");
                        $state.go("index");
                        $("body").css("padding", "0px");

                    }

                }, function error(response) {
                    console.log("error");
                });
            }
            else {
                $scope.offer_msg = true;
            }

        }
        $scope.cancel = function () {
            $("#myOffer").hide();
            $state.go("Trade", { 'tradeId': window.localStorage.getItem("TradeId") }, { reload: true });
        }

        $scope.Usertype = function (data) {

            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid) {
                return true;

            }
            else {
                return false;
                swal("Please login before to proceed!!");

            }
        }


        //offer_end
        $scope.showProductsTrade_tradelist = function (TradeId, CategoryId) {

            salewithusService.settradeid(TradeId);
            window.localStorage.setItem("Tradeid", TradeId);
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {
                $state.go("Trade", { 'tradeId': TradeId, 'categoryId': CategoryId }, { reload: true });
                // $state.go("single", {}, { reload: true });

            }
            else {
                $state.go("index", {}, { reload: true });
            }

        };
        //Check loggedin userId
        $scope.IsLoggedInUser = function (fromUserId) {
            var loggedinUserId = window.localStorage.getItem('UserId');
            if (fromUserId == loggedinUserId)
                return true;
            else
                return false;
        };
        //End Check loggedin userId

        $scope.gettradesmodel = {

            UserId: "",

        }

        $scope.GetTradeByUserId = function () {
            $scope.TradeByUserId = [];
            //debugger;

            $scope.gettradesmodel.UserId = window.localStorage.getItem("single_Userid");

            tradeService.gettrades($scope.gettradesmodel).then(function (response) {
                //debugger;

                if (response.data.Status == "Success") {

                    if (response.data.Message == "No records found.") {
                        $("#norecord_").show();
                    }
                    else {
                        $scope.TradeByUserId = response.data.Result;
                    }
                    // $scope.HideSpinner();
                    //if (response.data.Result[0].IsSold == true) {
                    //    $("#soldimage").show();
                    //}
                    //else {
                    //    $("#soldimage").hide();
                    //}
                }
                else {
                    swal("Something Went Wrong!!");

                }

            }, function error(response) {
                console.log("error");
            });

        }

        $scope.previousdata = function () {
            var pagenamefrom = tradeService.getpaymentpage();

            if (pagenamefrom == "paymnentpage") {
                var beforepostdata = JSON.parse(window.localStorage.getItem("Beforepayment_tradedetails"));
                $("#value_").val(beforepostdata.Price);
                // console.log(value);
                $("#comment").val(beforepostdata.Description);
                $("#short_description").val(beforepostdata.short_description);
            }
            else {

            }

        }

        $scope.showProductsTrade_up = function (TradeId, categoryid) {

            salewithusService.settradeid(TradeId);

            salewithusService.setcatid(categoryid);

            window.localStorage.setItem("Tradeid", TradeId);
            window.localStorage.setItem("single_catid", categoryid);

            //  $scope.usertype_ = window.localStorage.getItem("Usertype_need");
            //salewithusService.setcategoryid (TradecategoryId)
            if (TradeId >= 0) {

                // $state.go("Trade", {}, { reload: true });
                // $state.go("single", {}, { reload: true });

                $state.go("Need", { 'tradeId': TradeId, 'categoryId': categoryid }, { reload: true });
            }
            else {
                $state.go("index", {}, { reload: true });
            }


        };
        $scope.usertypefb_ = "";
        $scope.userfb = function (data) {
            $scope.usertypefb_ = window.localStorage.getItem("UserTypeIDfb");
            if (data == $scope.usertypefb_) {
                return true;
            }
            else {
                return false;
            }

        }
        $scope.Usertype = function (data) {
            $scope.usertypefb_ = window.localStorage.getItem("UserTypeIDfb");
            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid || $scope.usertypefb_ == data) {
                return true;

            }
            else {
                return false;


            }
        }
        $scope.mytradesoffer = function (data) {
            tradeService.setmyofferuserid(data);
            $state.go("MyTrades", {}, { reload: true });
        }


        //load_more functionality_start//

        $scope.loadMore = function () {
            $("#loader").show();
            pagenumber = pagenumber + 1;
            $scope.Getalltradeafterlogin();

        };
        $scope.loadMore_collegetrades = function () {
            $("#loader").show();
            pagenumber = pagenumber + 1;
            $scope.collegetrades();

        };

        $scope.paymntstatus = {
            UserId: "",
        }

        $scope.checkpaymentstatus = function (trademodel) {

            window.localStorage.setItem("Beforepayment_tradedetails", JSON.stringify(trademodel));
            $scope.paymntstatus.UserId = window.localStorage.getItem("UserId");

            if ($scope.paymntstatus.UserId != null) {

                /*tradeService.checkpayment($scope.paymntstatus).then(function (response) {*/
                    //debugger;

                    $scope.Username = window.localStorage.getItem("UserName");
                    if ($scope.Username.includes(".edu")) {
                        $scope.collegeid = salewithusService.getuniversityid();

                        if ($scope.collegeid != null || $scope.collegeid != undefined) {
                            $scope.posttradedata(trademodel);
                        }
                        else {
                            $scope.posttradedata(trademodel);
                            //if (response.data.Result.Status == 1) {

                            //    $scope.posttradedata(trademodel);

                            //}


                            //else {
                                /*if (confirm('Looking to add new trade? You can add new trades by getting a monthly subscription of $4.99 and the subscription will be renewed automatically each month.')) {*/
                                //    //salewithusService.settradefrompage("add_trade_detail");
                                  //  window.localStorage.setItem("Pagename", "add_trade_detail");
                                //    // Save it!
                                //    // Cleardata(trademodel);
                                //    // $('#rateperhour').removeAttr('checked');
                                //    // $("#uploadimages_").show();
                                //    //  $state.go("payment_detail");
                                //    // window.open("https://www.worldoftrade.com/#/payment_detail", "", "width=900,height=900");  server  by paras
                                //    //window.open("http://localhost:15719/#/payment_detail", "", "width=900,height=900");
                                //    // window.open("https://web.worldoftrade.com/#/payment_detail", "", "width=900,height=900");

                                //}
                                //else {

                                //  $state.go("index");
                                //}



                            //}
                        }
                    }
                    else {
                        $scope.posttradedata(trademodel);
                        //if (response.data.Result.Status == 1) {

                        //    $scope.posttradedata(trademodel);

                        //}

                        //else {
                        //    if (confirm('Looking to add new trade? You can add new trades by getting a monthly subscription of $4.99 and the subscription will be renewed automatically each month.')) {
                        //        //salewithusService.settradefrompage("add_trade_detail");
                        //        window.localStorage.setItem("Pagename", "add_trade_detail");
                        //        // Save it!
                        //        // Cleardata(trademodel);
                        //        // $('#rateperhour').removeAttr('checked');
                        //        // $("#uploadimages_").show();
                        //        //  $state.go("payment_detail");
                        //        //window.open("https://www.worldoftrade.com/#/payment_detail", "", "width=900,height=900"); server  by paras
                        //        //window.open("http://localhost:15719/#/payment_detail", "", "width=900,height=900");
                        //        //window.open("https://web.worldoftrade.com/#/payment_detail", "", "width=900,height=900");
                        //    }
                        //    else {

                        //        $state.go("index");
                        //    }



                        //}
                    }



                //}, function error(response) {
                //    console.log("error");
                //});
            }



        }
        //load_more functionality_end//
    }]);

}())
;
(function () {
    'use strict';
    angular.module('app').controller('chatController', ['$http', '$scope', '$sce', '$rootScope', '$state', '$stateParams', '$location', 'authService', 'chatService', 'salewithusService', '$window', 'toaster', '$interval', function ($http, $scope, $sce, $rootScope, $state, $location, $stateParams, authService, chatService, salewithusService, $window, toaster, $interval) {

        $(".modal-backdrop").hide();

        document.body.scrollTop = 0;
        document.documentElement.scrollTop = 0;

        // On enter key press send message
        $scope.onEnterKeyPress = function (event, Chatmodel) {
            if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
            {
                if ($.trim($("#txtmsg").val()) != "") {
                    $scope.SendMessage(Chatmodel);
                }
                else
                    return;
            }
        }

        $scope.Timer = null;
        //chat model
        $scope.Chatmodel = {
            ChatId: 0,
            TradeId: 0,
            FromUserId: 0,
            ToUserId: 0,
            Message: "",
            CreatedDateTime: null,
            IsRead: false,
            DeletedByUserId: "",
            UserName: "",
            UserImage: ""
        };

        $scope.Cmodel = {
            TradeId: 0,
            ToUserId: 0
        };

        //Declare variables 
        $scope.ChatMessages = {};
        $scope.UserName = "";
        $scope.UserImage = "";
        $scope.ChatUsersList = [];
        $scope.frompageName = "";
        $scope.lastMessagetime = "";
        $scope.IsOfferedMessage = "false";
        $scope.MessagesList = [];


        $interval(function () { $scope.GetChatMessagesbyTime(); }, 8000);

        //Send message
        $scope.SendMessage = function (Chatmodel) {

            $scope.Chatmodel.FromUserId = window.localStorage.getItem("UserId");
            $scope.Chatmodel.TradeId = chatService.gettradeid();
            $scope.Chatmodel.ToUserId = chatService.gettradeuserid();
            $scope.Chatmodel.Message = Chatmodel.Message;

            chatService.SendMessage($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $("#txtmsg").val("");
                    Chatmodel.Message = "";

                    if ($scope.lastMessagetime == ""){
                        $scope.GetChatMessages();
                    }

                    //$scope.GetChatMessages();
                    //$scope.GetChatUsersList();
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });

        }


        // chat users list
        $scope.GetChatUsersList = function () {
            $scope.ChatUsersList = []
            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');

            chatService.GetChatUsersList($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.ChatUsersList = response.data.Result;
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });
        }

        //get all messages 
        $scope.GetChatMessages = function () {

            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');
            $scope.Chatmodel.TradeId = chatService.gettradeid();
            $scope.Chatmodel.ToUserId = chatService.gettradeuserid();

            $scope.UserName = chatService.gettradeuserName();
            $scope.UserImage = $sce.trustAsHtml('<img src="' + chatService.gettradeuserImage() + '" class="img-fluid profile-img" >');
            chatService.GetChatMessages($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {

                    $scope.ChatMessages = response.data.Result;

                    if ($scope.ChatMessages.ItemName == undefined)
                        $scope.ChatMessages.ItemName = chatService.gettradename();

                    if ($scope.ChatMessages.Tradeimage == undefined)
                        $scope.ChatMessages.Tradeimage = chatService.gettradeimage();

                    if ($scope.ChatMessages.TradeId == undefined)
                        $scope.ChatMessages.TradeId = chatService.gettradeid();

                    if ($scope.ChatMessages.CreatedDateTime == undefined)
                        $scope.ChatMessages.CreatedDateTime = chatService.gettradetime();

                    $scope.MessagesList = $scope.ChatMessages.MessageList;

                    var offermessage = $scope.MessagesList.some(element => element.IsOfferedMsg == true);
                    window.localStorage.setItem('OfferedMsg', offermessage);

                    //// for (var i = 0; i < $scope.MessagesList.length; i++);
                    //console.log("last value" + i);

                    //   $scope.lastMessagetime = $scope.MessagesList[i - 1].CreatedDateTime;
                    // console.log("lastMessagetime" + $scope.lastMessagetime);

                    if ($scope.MessagesList.length > 0) {
                        for (var i = 0; i < $scope.MessagesList.length; i++) {
                            $scope.lastMessagetime = $scope.MessagesList[i].CreatedDateTime;
                        }
                    }

                    console.log("time1" + $scope.lastMessagetime);
                    $scope.GetUnreadMessageCount();
                    $scope.GetChatUsersList();
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });
        }

        $scope.GetChatMessagesbyTime = function () {
            //$scope.ChatMessages = []


            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');
            $scope.Chatmodel.TradeId = chatService.gettradeid();
            $scope.Chatmodel.ToUserId = chatService.gettradeuserid();

            if ($scope.Chatmodel.TradeId == undefined)
                $scope.Chatmodel.TradeId = chatService.gettradeidfromList();
            if ($scope.Chatmodel.ToUserId == undefined)
                $scope.Chatmodel.ToUserId = chatService.gettradeuseridfromList();

            $scope.Chatmodel.CreatedDateTime = $scope.lastMessagetime;
            //console.log($scope.Chatmodel.CreatedDateTime)

            chatService.GetChatMessagesbyTime($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {

                    //$scope.ChatMessages = response.data.Result;
                    //$scope.MessagesList =response.data.Result;

                    for (var i = 0; i < response.data.Result.length; i++) {
                        $scope.MessagesList.push(response.data.Result[i]);
                    }

                    if ($scope.MessagesList.length > 0) {
                        for (var i = 0; i < $scope.MessagesList.length; i++) {
                            $scope.lastMessagetime = $scope.MessagesList[i].CreatedDateTime;
                        }
                    }

                    $scope.GetUnreadMessageCount();
                    //$scope.GetChatUsersList();

                    //if (angular.isDefined($scope.Timer)) {
                    //    $interval.cancel($scope.Timer);

                    //}

                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });
        }

        //   if($scope.MessagesList.length > 0)
        //   {
        //                    for (var i = 0; i < $scope.MessagesList.length; i++)
        //                    {
        //                        $scope.lastMessagetime = $scope.MessagesList[i].CreatedDateTime;
        //					}
        //       
        //					console.log("time2" + $scope.lastMessagetime);
        //   }				


        $scope.GetUnreadMessageCount = function () {
            $scope.UnreadMessageCount = 0;
            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');
            chatService.GetUnreadMessageCount($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    //chatService.setunreadcount(response.data.Result);
                    $scope.UnreadMessageCount = response.data.Result;
                }
                else {
                    swal("Something Went Wrong!!");
                }

            }, function error(response) {
                console.log("error");
            });
        }

        $scope.DeleteChatList = function (user) {

            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');
            $scope.Chatmodel.TradeId = user.TradeId;
            $scope.Chatmodel.ToUserId = user.UserId;
            chatService.DeleteChatList($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.GetChatUsersList();
                }
                else {
                    swal("Something Went Wrong!!");
                }
            }, function error(response) {
                console.log("error");
            });
        }

        $scope.DeleteChatMessage = function (message) {
            //debugger;
            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');
            $scope.Chatmodel.ChatId = message.ChatId;

            chatService.DeleteChatMessage($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    $scope.GetChatMessages();
                    //$(".chatting").refresh();
                }
                else {
                    swal("Something Went Wrong!!");
                }
            }, function error(response) {

                console.log("error");
            });

        }

        $scope.closeChatWindow = function () {
            $(".chatting").hide();
        }


        $scope.ShowChatDiv = function (user) {
            $(".chatting").show();

            $scope.lastMessagetime = "";
            $scope.MessagesList = [];

            // $interval(function () { $scope.GetChatMessagesbyTime(); }, 1000);
            $scope.frompageName = "single";
            $scope.IsFromTradePage('single');
            chatService.settradeid(user.TradeId);
            chatService.settradeuserid(user.UserId);
            chatService.settradeuserName(user.UserName);
            chatService.settradeuserImage(user.UserImage);
            chatService.settradename(user.TradeName);
            chatService.settradetime(user.CreatedDateTime);
            chatService.settradeimage(user.TradeImage);
            chatService.setTradeOwnerId(user.TradeOwnerId);
            chatService.setIsSold(user.IsSold);
            chatService.setIsAccepted(user.IsAccepted);
            chatService.setTradeBuyerId(user.TradeBuyerId);
            chatService.setUserTypeId(user.UserTypeId);

            $scope.GetChatMessages();
        }

        $scope.showProductDetail = function (tradeId, CategoryId) {
            //debugger;
            if (tradeId == undefined)
                tradeId = chatService.gettradeidfromList();
            else if (tradeId >= 0) {
                window.localStorage.setItem("Tradeid", tradeId);

                if (CategoryId == undefined)
                    CategoryId = chatService.getcategoryId();

                $state.go("Trade", { 'tradeId': tradeId, 'categoryId': CategoryId }, { reload: true });
                // $state.go("single", {}, { reload: true });
            }
            else {
                $state.go("index", {}, { reload: true });
            }
        }

        $scope.IsLoggedInUser = function (fromUserId) {
            var loggedinUserId = window.localStorage.getItem('UserId');
            if (fromUserId == loggedinUserId)
                return true;
            else
                return false;
        };

        $scope.IsDeletedMessage = function (deletedUserId) {
            var loggedinUserId = window.localStorage.getItem('UserId');
            if (deletedUserId.includes(String(loggedinUserId)))
                return true;
            else
                return false;
        }

        $scope.IsFromTradePage = function (pagename) {
            if ($scope.frompageName == "")
                $scope.frompageName = chatService.getfrompage();
            if ($scope.frompageName == pagename)
                return true;
            else
                return false;
        }

        $scope.IsOfferedMessageInList = function () {

            //var OfferedMsg = chatService.getOfferMsg();
            var OfferedMsg = localStorage.getItem("OfferedMsg");
            console.log(OfferedMsg);
            if (OfferedMsg == "true") {
                return true;
                // localStorage.removeItem("OfferedMsg");              
            }
            else {
                return false;
                localStorage.removeItem("OfferedMsg");
            }
        }

        $scope.dateOf = function (utcDateStr) {
            utcDateStr = utcDateStr + "Z"
            return new Date(utcDateStr);
        }

        $scope.showButton = function () {
            if ($.trim($("#txtmsg").val()) != "")
                return true;
            else
                return false;
        }

        $scope.acceptOffer = function () {
            $scope.Chatmodel.FromUserId = window.localStorage.getItem('UserId');
            $scope.Chatmodel.TradeId = chatService.gettradeid();
            $scope.Chatmodel.ToUserId = chatService.gettradeuserid();

            chatService.AcceptOffer($scope.Chatmodel).then(function (response) {
                if (response.data.Status == "Success") {
                    swal("Offer accepted successfully");
                    $scope.GetChatMessages();
                    //$(".chatting").refresh();
                    //$("#acceptOffer").hide();
                }
                else {
                    swal("Something Went Wrong!!");
                }
            }, function error(response) {

                console.log("error");
            });
        }

        $scope.Usertype = function (data) {

            Uid = window.localStorage.getItem("UserTypeID");
            if (data == Uid) {
                return true;
            }
            else {
                return false;
            }
        }

        $scope.urlify = function (text) {
            var urlRegex = /(https?:\/\/[^\s]+)/g;
            return text.replace(urlRegex, function (url) {
                return '<a href="' + url + '">' + url + '</a>';
            })
            // or alternatively
            // return text.replace(urlRegex, '<a href="$1">$1</a>')
        }


        //shippingInfo start
        
        $scope.IsTradeOwner = function () {
            
            var loggedinUserId = window.localStorage.getItem('UserId');
            var OwnerId = chatService.getTradeOwnerId();
            var IsSoldTrade = chatService.getIsSold();
            var IsAcceptedTrade = chatService.getIsAccepted();
            if ( OwnerId == loggedinUserId)
                return true;
            else
                return false;
        }
        //$scope.CheckTradeBuyer = function () {

        //    var loggedinUserId = window.localStorage.getItem('UserId');
        //    var OwnerId = chatService.getTradeOwnerId();
        //    var IsSoldTrade = chatService.getIsSold();
        //    var IsAcceptedTrade = chatService.getIsAccepted();
        //    if (OwnerId != loggedinUserId)
        //        return true;
        //    else
        //        return false;
        //}

        $scope.IsCharityUser = function () {
            var loggedinUserId = window.localStorage.getItem('UserId');
            var UserTypeId = window.localStorage.getItem('UserTypeID');
            var OwnerId = chatService.getTradeOwnerId();
            if (OwnerId == loggedinUserId && UserTypeId == 3)
                return true;
            else
                return false;
        }

        $scope.IsCharityUserTypeId = function () {
            var UserTypeId = chatService.getUserTypeId();
            if (UserTypeId == 3)
                return true;
            else
                return false;
        }

        
        $scope.CheckInfoAdded = function (shippingmodel) {

            if (shippingmodel.Carrier == "" || shippingmodel.TrackingNo =="" || shippingmodel.TrackingUrl =="" || shippingmodel.ShippingType == "")
                return false;
            else
                return true;
        }


        $scope.shippingmodel = {
            TradeId: 0,
            TradeOwnerId: 0,
            TradeBuyerId: 0,
            Carrier: "",
            TrackingNo: "",
            TrackingUrl: "",
            ShippingType:"",
            CreatedDateTime: null
        };
        $scope.AddInfo = function (shippingmodel) {
            //debugger;
            $scope.shippingmodel.TradeId = chatService.gettradeid();
            $scope.shippingmodel.TradeOwnerId = chatService.getTradeOwnerId();
            $scope.shippingmodel.TradeBuyerId = chatService.getTradeBuyerId();
            $scope.shippingmodel.Carrier = shippingmodel.Carrier;
            $scope.shippingmodel.TrackingNo = shippingmodel.TrackingNo;
            $scope.shippingmodel.TrackingUrl = shippingmodel.TrackingUrl;
            $scope.shippingmodel.ShippingType = shippingmodel.ShippingType;
         
            salewithusService.Add_ShippingInfo($scope.shippingmodel).then(function (response) {
              //  debugger;
                    if (response.data.Status == "Success") {
                        
                        $("#modal .close").hide();
                        //$state.go("chat");
                        $("#shipInfo").hide();
                        $(".modal-backdrop").hide();
                        swal("Shipping Info added Successfully!!");
                        //$state.go("Chat");
                    }

                }, function error(response) {
                    console.log("error");
                });
            }
           
        $scope.GetInfo = function () {
            //debugger;
            //alert("hi");
           
            $scope.shippingmodel.TradeId = chatService.gettradeid();
            $scope.shippingmodel.TradeOwnerId = chatService.getTradeOwnerId();
            $scope.shippingmodel.TradeBuyerId = chatService.getTradeBuyerId();

            salewithusService.Get_ShippingInfo($scope.shippingmodel).then(function (response) {

                if (response.data.Status == "Success") {
                    //debugger;
                    $scope.shippingmodel.TradeId = response.data.Result.TradeId;
                    $scope.shippingmodel.TradeOwnerId = response.data.Result.TradeOwnerId;
                    $scope.shippingmodel.TradeBuyerId = response.data.Result.TradeBuyerId;
                    $scope.shippingmodel.Carrier = response.data.Result.Carrier;
                    $scope.shippingmodel.TrackingNo = response.data.Result.TrackingNo;
                    $scope.shippingmodel.TrackingUrl = response.data.Result.TrackingUrl;
                    $scope.shippingmodel.ShippingType = response.data.Result.ShippingType;
                }
                //else {
                //    var loggedinUserId = window.localStorage.getItem('UserId');
                //    var UserTypeId = window.localStorage.getItem('UserTypeID');
                //    var CharityUserTypeId = chatService.getUserTypeId();
                //    var OwnerId = chatService.getTradeOwnerId();
                //    if (loggedinUserId == OwnerId)
                //    {
                //        if(UserTypeId == 3)
                //        {
                //            alert("Data not found. You can ask the donar to add shipment information if you have accepted the donation.");
                //        }
                //        else
                //        {
                //            alert("Data not found. You can add trade shipment information if you are done with the bartering-offering process.");
                //        }
                //    }
                       
                //    if (loggedinUserId != OwnerId)
                //    {
                //        if(CharityUserTypeId == 3)
                //        {
                //            alert("Data not found. You can add shipment information for donated item if you are done with the donation process.");
                //        }
                //        else
                //        {
                //            alert("Data not found. You can ask the trade owner to add trade shipment information if you are done with the  bartering-offering process.");
                //        }
                //    }
                //}
            }, function error(response) {
                console.log("error");
            });
        }     

        $scope.cancel = function () {
            //debugger;
            $("#modal .close").hide();
            $("#shipInfo").hide();
            $(".modal-backdrop").hide();
        }
        //shippingInfo end

    }]);

}())



;
