eventComboApp.service("footerService", function ($http) {

    this.getCategory = function () {
        return $http.get("/NotificationAPI/GetCategory");
    };

    this.sendContactMessage = function (contactMessageViewModel) {
        var response = $http({
            method: "post",
            url: "/NotificationAPI/SendContactEmail",
            data: JSON.stringify(contactMessageViewModel),
            dataType: "json"
        });
        return response;
    }

    this.sendOrganizerMessage = function (contactMessageViewModel) {
        var response = $http({
            method: "post",
            url: "/NotificationAPI/SendOrganizer",
            data: JSON.stringify(contactMessageViewModel),
            dataType: "json"
        });
        return response;
    }

    this.sendFriendsMessage = function (friendNotificationViewModel) {
        var response = $http({
            method: "post",
            url: "/NotificationAPI/ShareFriends",
            data: JSON.stringify(friendNotificationViewModel),
            dataType: "json"
        });
        return response;
    }

    this.sendFriendToFriendMessage = function (friendNotificationViewModel) {
        return $http({
            method: "post",
            url: "/NotificationAPI/ShareFriendToFriend",
            data: JSON.stringify(friendNotificationViewModel),
            dataType: "json"
        });
    }
});
eventComboApp.service("organizerService", function ($http) {

  this.getOrganizerEvent = function (isUE, oId) {
    var response = $http({
      method: "get",
      datatype: "data.json",
      url: "/OrganizerInfo/OrganizerEvent",
      params: {
        isUpcomingEvent: isUE,
        organizerId: oId
      }
    });
    return response;
  };
    this.getOrganizerEvents = function (isUE, oId, includePrivateEvents) {
    var response = $http({
      method: "get",
      datatype: "data.json",
      url: "/OrganizerInfo/OrganizerEvents",
      params: {
        isUpcomingEvent: isUE,
          organizerId: oId,
          includePrivateEvents: includePrivateEvents
      }
    });
    return response;
  };

  this.getOrganizers = function () {
    var response = $http({
      method: "get",
      datatype: "data.json",
      url: "/Account/GetOrganizers",
      params: {
        isEdit: false
      }
    });
    return response;
  };
  this.getCountry = function () {
    var response = $http({
      method: "get",
      datatype: "data.json",
      url: "/Account/GetCountry"
    });
    return response;
  };
  this.getMembershipInfo = function (id) {
    var response = $http({
      method: "GET",
      datatype: "data.json",
      url: "/Membership/GetOrganizerMemberships",
      params: {
        orgId: id
      }
    });
    return response;
  };
  this.getStates = function () {
    var response = $http({
      method: "get",
      datatype: "data.json",
      url: "/Account/GetStates"
    });
    return response;
  };
  this.updateOrganizer = function (organizer, $scope) {
    var response = $http({
      method: "post",
      datatype: "data.json",
      data: { Organizer: organizer },
      url: "/Account/UpdateOrganizer",
      headers: {
        'RequestVerificationToken': $scope.AntiForgeryToken,
      }
    });
    return response;
  };
  this.addOrganizer = function (organizer, $scope) {
    var response = $http({
      method: "post",
      datatype: "data.json",
      data: { Organizer: organizer },
      url: "/Account/AddOrganizer",
      headers: {
        'RequestVerificationToken': $scope.AntiForgeryToken,
      }
    });
    return response;
  };
  this.enableDisableOrganizer = function (oId, iEnable, $scope) {
    var response = $http({
      method: "post",
      datatype: "data.json",
      data: { organizerId: oId, isEnabled: iEnable },
      url: "/Account/EnableDisableOrganizer",
      headers: {
        'RequestVerificationToken': $scope.AntiForgeryToken,
      }
    });
    return response;
  };
  this.deleteOrganizer = function (oId, $scope) {
    var response = $http({
      method: "post",
      datatype: "data.json",
      data: { OrganizerId: oId },
      url: "/Account/DeleteOrganizer",
      headers: {
        'RequestVerificationToken': $scope.AntiForgeryToken,
      }
    });
    return response;
  };

    this.getCommunityInfo = function (id,activityCount) {
        return $http({
            method: "GET",
            datatype: "data.json",
            url: "/Community/GetCommunityInfo",
            params: {
                organizerId: id, activityCount: activityCount
            }
        });
    };

    this.organizerMemberListData = function (id) {
        return $http({
            method: "GET",
            datatype: "data.json",
            url: "/OrganizerInfo/GetOrganizerMemberListData",
            params: {
                organizerId: id
            }
        });
    };

    this.organizerSponserList = function (id) {
        return $http({
            method: "GET",
            datatype: "data.json",
            url: "/OrganizerInfo/GetSponserList",
            params: {
                organizerId: id
            }
        });
    };

    this.organizerTestimonialList = function (id) {
        return $http({
            method: "GET",
            datatype: "data.json",
            url: "/OrganizerInfo/GetTestimonialList",
            params: {
                organizerId: id
            }
        });
    };

    this.organizerMemberList = function (id,isForAll) {
        return  $http({
            method: "GET",
            datatype: "data.json",
            url: "/Membership/GetOrganizerMemberList",
            params: {
                organizerId: id,
                isForAll: isForAll
            }
        });
    };

    this.AddMemberConnection = function (userId, communityConnectionId, communityId, orgId) {
        var model = {};
        model.MemberUserId = userId;
        model.CommunityConnectionId = communityConnectionId;
        model.CommunityId = communityId;
        model.OrganizerId = orgId;

        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model},
            url: "/Membership/AddMemberConnection"
        });
    };

    this.AcceptMemberConnection = function (userId, communityConnectionId, communityId, orgId) {
        var model = {};
        model.MemberUserId = userId;
        model.CommunityConnectionId = communityConnectionId;
        model.CommunityId = communityId;
        model.OrganizerId = orgId;

        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model },
            url: "/Membership/AcceptMemberConnection"
        });
    };

    this.ResendMemberConnection = function (userId, communityConnectionId, communityId, orgId) {
        var model = {};
        model.MemberUserId = userId;
        model.CommunityConnectionId = communityConnectionId;
        model.CommunityId = communityId;
        model.OrganizerId = orgId;

        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model },
            url: "/Membership/ResendMemberConnection"
        });
    };

    this.RemoveMemberConnection = function (userId, communityConnectionId, communityId, orgId) {
        var model = {};
        model.MemberUserId = userId;
        model.CommunityConnectionId = communityConnectionId;
        model.CommunityId = communityId;
        model.OrganizerId = orgId;

        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model },
            url: "/Membership/RemoveMemberConnection"
        });
    };

    this.BlockMemberConnection = function (userId, communityConnectionId, communityId, orgId) {
        var model = {};
        model.MemberUserId = userId;
        model.CommunityConnectionId = communityConnectionId;
        model.CommunityId = communityId;
        model.OrganizerId = orgId;

        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model },
            url: "/Membership/BlockMemberConnection"
        });
    };
    this.UnBlockMemberConnection = function (userId, communityConnectionId, communityId, orgId) {
        var model = {};
        model.MemberUserId = userId;
        model.CommunityConnectionId = communityConnectionId;
        model.CommunityId = communityId;
        model.OrganizerId = orgId;

        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model },
            url: "/Membership/UnblockMemberConnection"
        });
    };
    this.AddFollower = function (organizerId) {
       return  $http({
            method: "POST",
            datatype: "data.json",
            data: { OrganizerId: organizerId},
            url: "/Membership/AddFollower"
        });
    };

    this.RemoveFollower = function (organizerId) {
       return $http({
            method: "POST",
            datatype: "data.json",
            data: { OrganizerId: organizerId },
            url: "/Membership/RemoveFollower"
        });
    };

    this.AcceptDeclineMemberRequest = function (orgnizer_Id, memberConnectionId, isAccept) {
        var model = {};
        model.OrganizerId = orgnizer_Id;
        model.MemberConnectionId = memberConnectionId;
        model.IsAccept = isAccept;
        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: model},
            url: "/Membership/AcceptDeclineMemberRequest"
        });
    }

    this.GoToUserProfile = function (userId) {
        return $http({
            method: "POST",
            datatype: "data.json",
            data: { userId: userId },
            url: "/Membership/GoToUserProfile"
        });
    }

    this.CreatePostForCommunity = function (data) {
        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: data },
            url: "/Membership/CreatePostForCommunity"
        });
    }

    this.CreateCommentForPost = function (data) {
        return $http({
            method: "POST",
            datatype: "data.json",
            data: { model: data },
            url: "/Membership/CreateCommentForPost"
        });
    }

    this.AddActivityLike = function (communityActivityId, isLike) {
        return $http({
            method: "POST",
            datatype: "data.json",
            data: { communityActivityId: communityActivityId, isLike: isLike },
            url: "/Membership/AddActivityLike"
        });
    }
    this.GetCommunityActivities = function (communityId, takePage, skipPage) {
        return $http({
            method: "POST",
            datatype: "data.json",
            data: { communityId: communityId, takePage: takePage, skipPage: skipPage },
            url: "/Community/GetCommunityActivities"
        });
    }

});

var dates = [
    'Today',
    'Tomorrow',
    'This Week',
    'This Weekend',
    'Next Week',
    'This Month',
    'Custom Date',
    'All Dates'
];

eventComboApp.factory('MenuService', function () {
  return {
    navigation: [
      { id: 1, text: 'In-Person', link: '/howitworks', class: '', loginlink: '' },
      { id: 2, text: 'Fireworks', link: '/fireworks', class: '', loginlink: '' },
      { id: 3, text: 'Community', link: '/community', class: '', loginlink: '' },
      { id: 4, text: 'Host Event', link: '/eventmanagement/createevent', class: 'createevent', loginlink: '/eventmanagement/createevent' }
    ],
    selectedMenu: 0
  };
});

eventComboApp.factory('SolutionMenuService', function () {
  return {
    subnav: [
      { id: 1, text: 'Associations', link: '/solution/associations'},
      { id: 2, text: 'Education', link: '/solution/education'},
      { id: 3, text: 'Financial Services', link: '/solution/financialservices'},
      { id: 4, text: 'Government', link: '/solution/government'},
      { id: 5, text: 'Legal Services', link: '/solution/legalservices'},
      { id: 6, text: 'Life Sciences', link: '/solution/lifesciences'},
      { id: 7, text: 'Manufacturing Industry', link: '/solution/manufacturingindustry'},
      { id: 8, text: 'Media Services', link: '/solution/mediaservices'},
      { id: 9, text: 'Professional Services', link: '/solution/professionalservices'},
      { id: 10, text: 'Tech Services', link: '/solution/technology' }
    ],
    selectedSubMenu: 0
  };
});

eventComboApp.controller('HeaderController', ['$scope', 'MenuService', 'SolutionMenuService', 'broadcastService', 'accountService', '$mdDialog', '$mdToast', 'vcRecaptchaService', ctrlHeaderFunction]);
function ctrlHeaderFunction($scope, MenuService, SolutionMenuService, broadcastService, accountService, $mdDialog, $mdToast, vcRecaptchaService) {
  $scope.navigation = MenuService.navigation; // Top navigation menu data
  $scope.subnav = SolutionMenuService.subnav; // Top navigation menu data

  $scope.$on('LoggedIn', function (event, param) {
    var paramArray = param.split('_');
    var link = paramArray[paramArray.length - 1];
    if (paramArray[0] === 'HeaderMenu') {
      broadcastService.ReloadPage(link);
    }
  });

  $scope.clickLink = function (link, e) {
    if (!link || $scope.userRegistered)
      return;
    accountService.StartLogin('HeaderMenu_' + link);
    e.preventDefault();
  }

  $scope.contactEventcombo = function (event, param) {
    $mdDialog.show({
      controller: ['$scope', '$mdDialog', '$mdConstant', '$mdToast', '$timeout', '$filter', 'vcRecaptchaService', 'footerService', 'parentScope', DialogContactEventComboController],
      templateUrl: 'eventcombo.tmpl.html',
      parent: angular.element(document.body),
      targetEvent: event,
      locals: {
        parentScope: $scope
      },
      clickOutsideToClose: true,
      autofocus: false
    });
  };
}

function DialogContactEventComboController($scope, $mdDialog, $mdConstant, $mdToast, $timeout, $filter, vcRecaptchaService, footerService, parentScope) {
  $scope.showHints = true;
  $scope.submitted = false;
  $scope.sendTo = [];
  $scope.Categories = [];
  $scope.SubCategories = [];
  $scope.SelectedCategory = {
    CategoryId: 0,
    SubCategoryId: 0,
    Category: null,
    SubCategory: null
  }
  $scope.response = null;
  $scope.widgetId = null;

  $scope.setResponse = function (response) {
    $scope.response = response;
  };
  $scope.setWidgetId = function (widgetId) {
    $scope.widgetId = widgetId;
    $timeout(function () {
      angular.element(document.getElementsByClassName('g-recaptcha-bubble-arrow')).parent().css("position", "fixed");
    }, 1000);
  };
  $scope.cbExpiration = function () {
    vcRecaptchaService.reload($scope.widgetId);
    $scope.response = null;
  };

  $scope.showSimpleToast = function (theme, message) {
    $mdToast.show(
      $mdToast.simple()
        .textContent(message)
        .position('bottom right')
        .hideDelay(3000)
        .theme(theme)
    );
  };

  $scope.getCategoryById = function (list, id) {
    var categories = $filter('filter')(list, { Id: id });
    if (categories && categories.length > 0)
      return categories[0];
    return null;
  }

  $scope.updateCategory = function () {
    $scope.SelectedCategory.Category = $scope.getCategoryById($scope.Categories, $scope.SelectedCategory.CategoryId);
    if ($scope.SelectedCategory.Category)
      $scope.SubCategories = $scope.SelectedCategory.Category.SubCategories;
    else
      $scope.SubCategories = [];
    $scope.SelectedCategory.SubCategoryId = undefined;
    $scope.SelectedCategory.SubCategory = null;
  }

  $scope.updateSubCategory = function () {
    $scope.SelectedCategory.SubCategory = $scope.getCategoryById($scope.SubCategories, $scope.SelectedCategory.SubCategoryId);
  }

  function getCategory() {
    var getCategoryData = footerService.getCategory();
    getCategoryData.then(function (response) {
      $scope.Categories = response.data;
    }, function (error) {
      console.error(error);
      parentScope.showInfoMessage(true, "Error in getting category records");
    });
  };

  $scope.getSubCategories = function () {
    var result = $filter('filter')($scope.Categories, { 'Id': $scope.cntCategory });
    if (result && result.length > 0)
      $scope.SubCategories = result[0].SubCategories;
  }
  getCategory();

  $scope.sendContactMessageEventcombo = function (form) {
    if (!$scope.response) {
      $scope.showSimpleToast('error-toast', 'You need to complete reCapthca verification');
      return;
    }

    if ($scope[form].$valid) {
      $mdDialog.hide();
      var contactMessageViewModel = {
        Name: $scope.cntName,
        Email: $scope.cntEmail,
        PhoneNo: $scope.cntPhone,
        Category: $scope.SelectedCategory.Category.Title,
        SubCategory: $scope.SelectedCategory.SubCategory.Title,
        Message: $scope.cntMessage,
        captcha: $scope.response
      };
      parentScope.showLoadingMessage(true, 'Sending message');
      var getMessageData = footerService.sendContactMessage(contactMessageViewModel);
      getMessageData.then(function (d) {
        $scope.cntName = "";
        $scope.cntEmail = "";
        $scope.cntPhone = "";
        $scope.SelectedCategory = {
          CategoryId: 0,
          SubCategoryId: 0,
          Category: null,
          SubCategory: null
        }
        $scope.cntMessage = "";
        parentScope.showLoadingMessage(false, '');
        $scope.showSimpleToast('success-toast', "Your message was sent. Please look out for a response ASAP.");
      }, function () {
        $scope.showSimpleToast('error-toast', 'Error while sending message');
        parentScope.showLoadingMessage(false, '');
        parentScope.popServerError = true;
      });
    } else {
      $scope.submitted = true;
      $scope.eventcomboForm.cntCategory.$setTouched();
      $scope.eventcomboForm.cntSubCategory.$setTouched();
    }
  };

  $scope.hide = function () {
    $mdDialog.hide();
  };

  $scope.cancel = function () {
    $mdDialog.cancel();
  };

  $scope.chipValidation = function (chipText) {
    var reg = /^.+@.+\..+$/;
    if (reg.test(chipText)) {
      $scope.isEmailValid = false;
      return chipText;
    }
    else {
      $scope.isEmailValid = true;
      return null;
    }
  }
}

eventComboApp.controller('SearchEventController', ['$scope', '$window', '$http', '$q', '$cookies', '$timeout', 'broadcastService', 'geoService',
  function ($scope, $window, $http, $q, $cookies, $timeout, broadcastService, geoService) {

    $scope.foundCities = [];
    $scope.allowRedirect = false;
    $scope.initCity = "";

    $scope.gmapsService = new google.maps.places.AutocompleteService();
    $scope.placeService = new google.maps.places.PlacesService(document.getElementById('search').appendChild(document.createElement('div')));

    $scope.setCity = function (cityname) {
      $scope.initCity = cityname;
      $scope.$broadcast('angucomplete-alt:changeInput', 'acCitySearch', cityname);
    }

    function setCityByCoordinates(lat, lng) {
      geoService.GetCityByCoordinates(lat, lng, $scope.setCity);
    }

    $scope.$on('CurrentCoordinatesChanged', function (event, val) {
      if ($scope.allowRedirect) {
        var coords = geoService.GetCoordinates();
        if (coords) 
          $window.location = '/et/evt/evc/all/page/' + coords.latitude + '/' + coords.longitude + '/rel/none';
      }
      else
        geoService.GetCurrentCity($scope.setCity);
    });

    $scope.$on('SetCitySearchRedirect', function (event, val) {
      $scope.allowRedirect = val;
    });

    geoService.GetCurrentCity($scope.setCity);

    $scope.DiscoverByEvent = function (item) {
      var coords = geoService.GetCoordinates();
      if (item.originalObject) {
        var data = {
          EventId: 0,
          RecordTypeId: 5,
          EventTitle: '',
          Latitude: coords.latitude,
          Longitude: coords.longitude,
        }
        if (typeof (item.originalObject) === 'object') {
          data.EventId = item.originalObject.EventId;
          data.EventTitle = item.originalObject.EventTitle;
          data.RecordTypeId = item.originalObject.RecordTypeId;
        }
        else if (typeof (item.originalObject) === 'string') {
          data.EventTitle = item.originalObject;
        }

        $http.get('/home/SearchEvents', { params: { json: angular.toJson(data) } }).then(function (response) {
          if (response.data)
            $window.location = response.data;
        }, function (error) { });
      }
    }

    $scope.eventSearch = function (str, timeoutPromise) {
      return $http.get("/commonAPI/FilterEventsByTitle", { params: { title: str } }).then(function (response) {
        return response.data;
      });
    }

    $scope.citySearch = function (str, timeoutPromise) {
      var deferred = $q.defer();
      $scope.getCitySearchResults(str).then(
        function (predictions) {
          $scope.foundCities = predictions ? predictions : [];
          $scope.foundCities.forEach(function (res) {
            if (res.terms.length > 1) {
              var pos = res.terms[res.terms.length - 1].offset;
              res.description = res.description.substring(0, pos - 2);
            }
          });
          deferred.resolve($scope.foundCities);
        }
      );
      return deferred.promise;
    }

    $scope.getCitySearchResults = function (str) {
      var deferred = $q.defer();
      $scope.gmapsService.getPlacePredictions({
        input: str, types: ['(regions)']
      }, function (data) {
        deferred.resolve(data);
      });
      return deferred.promise;
    }

    $scope.DiscoverByCity = function (item) {
      if ((!$scope.foundCities) || (!Array.isArray($scope.foundCities)) || (!$scope.foundCities.length) || (!item) || (!item.originalObject))
        return;

      if (typeof (item.originalObject) === 'object') {
        $scope.placeService.getDetails({ placeId: item.originalObject.place_id },
          function(city) {
            $scope.allowRedirect = true;
            geoService.SetCoordinates(city.geometry.location.lat(), city.geometry.location.lng(), "", false);
          });
      } else if (typeof (item.originalObject) === 'string') {
        var promise = $scope.citySearch(item.originalObject);
        promise.then(function (result) {
          if (Array.isArray(result) && (result.length)) {
            $scope.placeService.getDetails({ placeId: result[0].place_id },
              function(city) {
                $scope.allowRedirect = true;
                geoService.SetCoordinates(city.geometry.location.lat(), city.geometry.location.lng(), "", false);
              });
          }
        });
      }
    }

    $scope.ClearCity = function () {
      $timeout(function () {
        $scope.$broadcast('angucomplete-alt:clearInput', 'acCitySearch');
      });
    }

  }]);

eventComboApp.directive('pressEnter', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      element.bind("keydown keypress", function (event) {
        if (event.which === 13) {
          scope.$apply(function () {
            scope.$eval(attrs.pressEnter);
          });
          event.preventDefault();
        }
      });
    }
  }
});

eventComboApp.service('anchorSmoothScroll', function () {
  // Smoothly scroll to target anchor id
  this.scrollTo = function (eID, offsettop) {
    var startY = currentYPosition();
    var stopY = elmYPosition(eID) - offsettop;
    var distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
      scrollTo(0, stopY); return;
    }
    var speed = Math.round(distance / 100);
    if (speed >= 20) speed = 20;
    var step = Math.round(distance / 25);
    var leapY = stopY > startY ? startY + step : startY - step;
    var timer = 0;
    if (stopY > startY) {
      for (var i = startY; i < stopY; i += step) {
        setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
        leapY += step; if (leapY > stopY) leapY = stopY; timer++;
      } return;
    }
    for (var i = startY; i > stopY; i -= step) {
      setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed);
      leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
    }

    function currentYPosition() {
      // Firefox, Chrome, Opera, Safari
      if (self.pageYOffset) return self.pageYOffset;
      // Internet Explorer 6 - standards mode
      if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
      // Internet Explorer 6, 7 and 8
      if (document.body.scrollTop) return document.body.scrollTop;
      return 0;
    }

    function elmYPosition(eID) {
      var elm = document.getElementById(eID);
      var y = elm.offsetTop;
      var node = elm;
      while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
      } return y;
    }

  };
});

eventComboApp.controller('FooterController', ['$scope', 'geoService', '$mdDialog', '$mdToast', 'vcRecaptchaService', 'broadcastService', 'accountService',
    function ($scope, geoService, $mdDialog, $mdToast, vcRecaptchaService, broadcastService, accountService) {

        $scope.cCoords = geoService.GetCoordinates();

        $scope.showLoadingMessage = function (show, message) {
            $scope.popLoading = show;
            $scope.LoadingMessage = message;
        };

        $scope.showInfoMessage = function (show, message) {
            $scope.popInfoMessage = show;
            $scope.InfoMessage = message;
        };

        $scope.$on('LoggedIn', function (event, param) {
            var paramArray = param.split('_');
            var link = paramArray[paramArray.length - 1];
            if (paramArray[0] === 'HeaderMenu') {
                broadcastService.ReloadPage(link);
            }
        });

        $scope.clickLink = function (link, e) {
            if (!link || $scope.userRegistered)
                return;
            accountService.StartLogin('HeaderMenu_' + link);
            $scope.displayPopups = "block";
            $scope.popLogin = true;
            e.preventDefault();
        }

        $scope.showSimpleToast = function (theme, message) {
            $mdToast.show(
                $mdToast.simple()
                    .textContent(message)
                    .position('bottom right')
                    .hideDelay(3000)
                    .theme(theme)
            );
        };

        $scope.closeLightBoxWithEsc = function () {
            $scope.popLoading = false;
            $scope.popServerError = false;
            $scope.popInfoMessage = false;
            $scope.popLogin = false;
        };

        $scope.onCityClick = function (lat, lng) {
            var coords = geoService.SetCoordinates(lat, lng, "", true);
        }

        $scope.contactOrganizer = function (event) {
            $scope.CMessage = {
                Email: '',
                Name: '',
                Phone: '',
                Message: '',
                EventId: 0,
                OrganizerId: 0,
                EventName: '',
                OrganizerName: ''
            }
            $mdDialog.show({
                controller: ['$scope', '$mdDialog', '$mdConstant', '$mdToast', '$timeout', 'vcRecaptchaService', 'footerService', 'eventId', 'organizerId', 'eventName', 'organizerName', DialogContactOrganizerController],
                templateUrl: 'organizer.tmpl.html',
                parent: angular.element(document.body),
                targetEvent: event,
                scope: $scope,
                preserveScope: true,
                clickOutsideToClose: true
            });
        };

        $scope.contactEventcombo = function (event, param) {
            $mdDialog.show({
                controller: ['$scope', '$mdDialog', '$mdConstant', '$mdToast', '$timeout', '$filter', 'vcRecaptchaService', 'footerService', 'parentScope', DialogContactEventComboController],
                templateUrl: 'eventcombo.tmpl.html',
                parent: angular.element(document.body),
                targetEvent: event,
                locals: {
                    parentScope: $scope
                },
                clickOutsideToClose: true,
                autofocus: false
            });
        };

        $scope.forwardFriend = function (event) {
            $mdDialog.show({
                controller: ['$scope', '$mdDialog', '$mdConstant', '$mdToast', '$timeout', 'vcRecaptchaService', 'footerService', 'id', 'title', 'type', DialogForwardFriendController],
                templateUrl: 'forwardfriend.tmpl.html',
                parent: angular.element(document.body),
                targetEvent: event,
                scope: $scope,
                preserveScope: true,
                clickOutsideToClose: true
            });
        };

        $scope.eventSubmit = function (params) {
            $mdDialog.show({
                controller: ['$scope', '$mdDialog', 'eventService', 'socialService', 'params', DialogEventSubmitController],
                templateUrl: 'eventsubmit.tmpl.html',
                parent: angular.element(document.body),
                targetEvent: null,
                locals: { params: params },
                clickOutsideToClose: false,
            });
        };

        $scope.openCertificates = function (event) {
            $mdDialog.show({
                controller: ['$scope', '$mdDialog', DialogCertificateController],
                templateUrl: 'certifications.tmpl.html',
                parent: angular.element(document.body),
                targetEvent: event,
                clickOutsideToClose: true
            });
        };

        $scope.$on('EventPublished', function (event, params) {
            $scope.eventSubmit(params);
        });

        $scope.$on('ShowEventComboContactDialog',
            function (event) {
                $scope.contactEventcombo(event);
          });

      $scope.toggleStatus1 = true;
      $scope.toggleStatus2 = true;
      $scope.toggleStatus3 = true;
      $scope.toggleStatus4 = true;
      $scope.toggleStatus5 = true;

      if (window.innerWidth < 821) {

        $scope.toggleStatus1 = false;
        $scope.toggleStatus2 = false;
        $scope.toggleStatus3 = false;
        $scope.toggleStatus4 = false;
        $scope.toggleStatus5 = false;
        $scope.showLinkToggle = function (type) {
          if (!$scope.toggleStatus1 && type === 'Company') {
            $scope.toggleStatus1 = true;
          } else {
            $scope.toggleStatus1 = false;
          }
          if (!$scope.toggleStatus2 && type === 'Products') {
            $scope.toggleStatus2 = true;
          } else {
            $scope.toggleStatus2 = false;
          }
          if (!$scope.toggleStatus3 && type === 'Resources') {
            $scope.toggleStatus3 = true;
          } else {
            $scope.toggleStatus3 = false;
          }
          if (!$scope.toggleStatus4 && type === 'Mobile Apps') {
            $scope.toggleStatus4 = true;
          } else {
            $scope.toggleStatus4 = false;
          }
          if (!$scope.toggleStatus5 && type === 'Featured') {
            $scope.toggleStatus5 = true;
          } else {
            $scope.toggleStatus5 = false;
          }
        }
      }

    }]);

function DialogContactOrganizerController($scope, $mdDialog, $mdConstant, $mdToast, $timeout, vcRecaptchaService, footerService, eventId, organizerId, eventName, organizerName) {
    $scope.showHints = true;
    $scope.submitted = false;
    $scope.sendTo = [];
    $scope.CMessage = {
        Email: '',
        Name: '',
        Phone: '',
        Message: '',
        EventId: 0,
        OrganizerId: 0,
        EventName: '',
        OrganizerName: ''
    }
    $scope.CMessage.EventId = eventId;
    $scope.CMessage.OrganizerId = organizerId;
    $scope.CMessage.EventName = eventName;
    $scope.CMessage.OrganizerName = organizerName;

    $scope.response = null;
    $scope.widgetId = null;

    $scope.setResponse = function (response) {
        $scope.response = response;
    };
    $scope.setWidgetId = function (widgetId) {
        $scope.widgetId = widgetId;
        $timeout(function () {
            angular.element(document.getElementsByClassName('g-recaptcha-bubble-arrow')).parent().css("position", "fixed");
        }, 1000);
    };
    $scope.cbExpiration = function () {
        vcRecaptchaService.reload($scope.widgetId);
        $scope.response = null;
    };

    $scope.showSimpleToast = function (theme, message) {
        $mdToast.show(
            $mdToast.simple()
                .textContent(message)
                .position('bottom right')
                .hideDelay(3000)
                .theme(theme)
        );
    };

    $scope.sendOrganizerMessage = function (form) {
        if (!$scope.response) {
            $scope.showSimpleToast('error-toast', 'You need to complete reCapthca verification');
            return;
        }
        $scope.CMessage.Captcha = $scope.response;

        if ($scope[form].$valid) {
            $mdDialog.hide();
            var data = {
                json: angular.toJson($scope.CMessage)
            };
            $scope.showLoadingMessage(true, 'Sending message');
            var getMessageData = footerService.sendOrganizerMessage(data);
            getMessageData.then(function (d) {
                $scope.showLoadingMessage(false, '');
                $scope.showSimpleToast('success-toast', 'Your message was sent. Please look out for a response ASAP.');
            }, function () {
                $scope.showSimpleToast('error-toast', 'Error while sending message');
                $scope.showLoadingMessage(false, '');
                $scope.popServerError = true;
            });
        } else {
            $scope.submitted = true;
        }
    };

    $scope.hide = function () {
        $mdDialog.hide();
    };

    $scope.cancel = function () {
        $mdDialog.cancel();
    };

    $scope.chipValidation = function (chipText) {
        var reg = /^.+@.+\..+$/;
        if (reg.test(chipText)) {
            $scope.isEmailValid = false;
            return chipText;
        }
        else {
            $scope.isEmailValid = true;
            return null;
        }
    }
}

function DialogContactEventComboController($scope, $mdDialog, $mdConstant, $mdToast, $timeout, $filter, vcRecaptchaService, footerService, parentScope) {
    $scope.showHints = true;
    $scope.submitted = false;
    $scope.sendTo = [];
    $scope.Categories = [];
    $scope.SubCategories = [];
    $scope.SelectedCategory = {
        CategoryId: 0,
        SubCategoryId: 0,
        Category: null,
        SubCategory: null
    }
    $scope.response = null;
    $scope.widgetId = null;

    $scope.setResponse = function (response) {
        $scope.response = response;
    };
    $scope.setWidgetId = function (widgetId) {
        $scope.widgetId = widgetId;
        $timeout(function () {
            angular.element(document.getElementsByClassName('g-recaptcha-bubble-arrow')).parent().css("position", "fixed");
        }, 1000);
    };
    $scope.cbExpiration = function () {
        vcRecaptchaService.reload($scope.widgetId);
        $scope.response = null;
    };

    $scope.showSimpleToast = function (theme, message) {
        $mdToast.show(
            $mdToast.simple()
                .textContent(message)
                .position('bottom right')
                .hideDelay(3000)
                .theme(theme)
        );
    };

    $scope.getCategoryById = function (list, id) {
        var categories = $filter('filter')(list, { Id: id });
        if (categories && categories.length > 0)
            return categories[0];
        return null;
    }

    $scope.updateCategory = function () {
        $scope.SelectedCategory.Category = $scope.getCategoryById($scope.Categories, $scope.SelectedCategory.CategoryId);
        if ($scope.SelectedCategory.Category)
            $scope.SubCategories = $scope.SelectedCategory.Category.SubCategories;
        else
            $scope.SubCategories = [];
        $scope.SelectedCategory.SubCategoryId = undefined;
        $scope.SelectedCategory.SubCategory = null;
    }

    $scope.updateSubCategory = function () {
        $scope.SelectedCategory.SubCategory = $scope.getCategoryById($scope.SubCategories, $scope.SelectedCategory.SubCategoryId);
    }

    function getCategory() {
        var getCategoryData = footerService.getCategory();
        getCategoryData.then(function (response) {
            $scope.Categories = response.data;
        }, function (error) {
            console.error(error);
            parentScope.showInfoMessage(true, "Error in getting category records");
        });
    };

    $scope.getSubCategories = function () {
        var result = $filter('filter')($scope.Categories, { 'Id': $scope.cntCategory });
        if (result && result.length > 0)
            $scope.SubCategories = result[0].SubCategories;
    }
    getCategory();

    $scope.sendContactMessageEventcombo = function (form) {
        if (!$scope.response) {
            $scope.showSimpleToast('error-toast', 'You need to complete reCapthca verification');
            return;
        }

        if ($scope[form].$valid) {
            $mdDialog.hide();
            var contactMessageViewModel = {
                Name: $scope.cntName,
                Email: $scope.cntEmail,
                PhoneNo: $scope.cntPhone,
                Category: $scope.SelectedCategory.Category.Title,
                SubCategory: $scope.SelectedCategory.SubCategory.Title,
                Message: $scope.cntMessage,
                captcha: $scope.response
            };
            parentScope.showLoadingMessage(true, 'Sending message');
            var getMessageData = footerService.sendContactMessage(contactMessageViewModel);
            getMessageData.then(function (d) {
                $scope.cntName = "";
                $scope.cntEmail = "";
                $scope.cntPhone = "";
                $scope.SelectedCategory = {
                    CategoryId: 0,
                    SubCategoryId: 0,
                    Category: null,
                    SubCategory: null
                }
                $scope.cntMessage = "";
                parentScope.showLoadingMessage(false, '');
                $scope.showSimpleToast('success-toast', "Your message was sent. Please look out for a response ASAP.");
            }, function () {
                $scope.showSimpleToast('error-toast', 'Error while sending message');
                parentScope.showLoadingMessage(false, '');
                parentScope.popServerError = true;
            });
        } else {
            $scope.submitted = true;
            $scope.eventcomboForm.cntCategory.$setTouched();
            $scope.eventcomboForm.cntSubCategory.$setTouched();
        }
    };

    $scope.hide = function () {
        $mdDialog.hide();
    };

    $scope.cancel = function () {
        $mdDialog.cancel();
    };

    $scope.chipValidation = function (chipText) {
        var reg = /^.+@.+\..+$/;
        if (reg.test(chipText)) {
            $scope.isEmailValid = false;
            return chipText;
        }
        else {
            $scope.isEmailValid = true;
            return null;
        }
    }
}

function DialogForwardFriendController($scope, $mdDialog, $mdConstant, $mdToast, $timeout, vcRecaptchaService, footerService, id, title, type) {
    $scope.currencyVal;
    $scope.showHints = true;
    $scope.submitted = false;
    $scope.CMessage = {
        Email: '',
        Name: '',
        Phone: '',
        Message: '',
        Id: 0,
        Type: '',
        Subject: '',
        To: []
    }
    $scope.CMessage.Id = id;
    $scope.CMessage.Type = type;
    $scope.CMessage.Title = title;
    $scope.CMessage.Subject = "";

    $scope.response = null;
    $scope.widgetId = null;

    $scope.setResponse = function (response) {
        $scope.response = response;
    };
    $scope.setWidgetId = function (widgetId) {
        $scope.widgetId = widgetId;
        $timeout(function () {
            angular.element(document.getElementsByClassName('g-recaptcha-bubble-arrow')).parent().css("position", "fixed");
        }, 1000);
    };
    $scope.cbExpiration = function () {
        vcRecaptchaService.reload($scope.widgetId);
        $scope.response = null;
    };

    $scope.showSimpleToast = function (theme, message) {
        $mdToast.show(
            $mdToast.simple()
                .textContent(message)
                .position('bottom right')
                .hideDelay(3000)
                .theme(theme)
        );
    };

    $scope.sendFriendMessage = function (form) {
        if (!$scope.response) {
            $scope.showSimpleToast('error-toast', 'You need to complete reCapthca verification');
            return;
        }
        $scope.CMessage.captcha = $scope.response;

        if ($scope[form].$valid) {
            if ($scope.CMessage.To.length == 0) {
                $scope.CMessage.IsEmailRequired = true;
            } else {
                $mdDialog.hide();
                var data = {
                    json: angular.toJson($scope.CMessage)
                };
                $scope.showLoadingMessage(true, 'Sending message');
                var getMessageData = footerService.sendFriendsMessage(data);
                getMessageData.then(function (d) {
                    $scope.showLoadingMessage(false, '');
                    $scope.showSimpleToast('success-toast', 'Your message was sent.');
                }, function () {
                    $scope.showSimpleToast('error-toast', 'Error while sending message');
                    $scope.showLoadingMessage(false, '');
                    $scope.popServerError = true;
                });
            }
        } else {
            $scope.submitted = true;
        }
    };

    $scope.hide = function () {
        $mdDialog.hide();
    };

    $scope.cancel = function () {
        $mdDialog.cancel();
    };

    $scope.chipValidation = function (chipText) {
        var reg = /^.+@.+\..+$/;
        if (reg.test(chipText)) {
            $scope.isEmailValid = false;
            return chipText;
        }
        else {
            $scope.isEmailValid = true;
            return null;
        }
    }
}


function DialogFriendToFriendController($scope, $mdDialog, $mdConstant, $mdToast, $timeout, vcRecaptchaService, footerService, id, title, orgName,userId,email, type) {
    $scope.currencyVal;
    $scope.showHints = true;
    $scope.submitted = false;
    $scope.CMessage = {
        Email: '',
        Name: '',
        Phone: '',
        Message: '',
        Id: 0,
        Type: '',
        Subject: '',
        To: [],
        UserId:'',
    }
    $scope.CMessage.Id = id;
    $scope.CMessage.Email = email;
    $scope.CMessage.UserId = userId;
    $scope.CMessage.Type = type;
    $scope.CMessage.Title = title;
    //$scope.CMessage.Subject = orgName;
    $scope.response = null;
    $scope.widgetId = null;

    $scope.setResponse = function (response) {
        $scope.response = response;
    };
    $scope.setWidgetId = function (widgetId) {
        $scope.widgetId = widgetId;
        $timeout(function () {
            angular.element(document.getElementsByClassName('g-recaptcha-bubble-arrow')).parent().css("position", "fixed");
        }, 1000);
    };
    $scope.cbExpiration = function () {
        vcRecaptchaService.reload($scope.widgetId);
        $scope.response = null;
    };

    $scope.showSimpleToast = function (theme, message) {
        $mdToast.show(
            $mdToast.simple()
                .textContent(message)
                .position('bottom right')
                .hideDelay(3000)
                .theme(theme)
        );
    };

    $scope.sendFriendToFriendMessage = function (form) {
        if (!$scope.response) {
            $scope.showSimpleToast('error-toast', 'You need to complete reCapthca verification');
            return;
        }
        $scope.CMessage.captcha = $scope.response;

        if ($scope[form].$valid) {
            $mdDialog.hide();
            var data = {
                json: angular.toJson($scope.CMessage)
            };
            $scope.showLoadingMessage(true, 'Sending message');
            var getMessageData = footerService.sendFriendToFriendMessage(data);
            getMessageData.then(function (d) {
                $scope.showLoadingMessage(false, '');
                $scope.showSimpleToast('success-toast', 'Your message was sent.');
            }, function () {
                $scope.showSimpleToast('error-toast', 'Error while sending message');
                $scope.showLoadingMessage(false, '');
                $scope.popServerError = true;
            });
        } else {
            $scope.submitted = true;
        }
    };

    $scope.hide = function () {
        $mdDialog.hide();
    };

    $scope.cancel = function () {
        $mdDialog.cancel();
    };

    $scope.chipValidation = function (chipText) {
        var reg = /^.+@.+\..+$/;
        if (reg.test(chipText)) {
            $scope.isEmailValid = false;
            return chipText;
        }
        else {
            $scope.isEmailValid = true;
            return null;
        }
    }
}

function DialogEventSubmitController($scope, $mdDialog, eventService, socialService, params) {
    $scope.EventParameters = params;

    $scope.hide = function () {
        $mdDialog.hide();
    };

    $scope.cancel = function () {
        $mdDialog.cancel();
    };

    $scope.editEvent = function () {
        eventService.EditEvent($scope.EventParameters.EventId);
        $scope.cancel();
    }

    $scope.showDashboard = function () {
        if ($scope.EventParameters.IsInviteOnly == 'Y')
            eventService.EventInvite($scope.EventParameters.EventId);
        else
            eventService.EventDashboard($scope.EventParameters.EventId);
        $scope.cancel();
    }

    $scope.shareEvent = function () {
        socialService.FacebookShare($scope.EventParameters.EventUrl);
    }
}

function DialogCertificateController($scope, $mdDialog) {
    $scope.cancel = function () {
        $mdDialog.cancel();
    };
}

eventComboApp.directive('telMaskWithoutModel', function ($filter, $browser) {
    return {
        link: function ($scope, $element, $attrs) {
            var listener = function () {
                var value = $element.val().replace(/[^0-9]/g, '');
                $element.val($filter('tel')(value, false));
            };
            $element.bind('change', listener);
            $element.bind('keydown', function (event) {
                var key = event.keyCode;
                if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
                    return;
                }
                $browser.defer(listener);
            });
            $element.bind('paste cut', function () {
                $browser.defer(listener);
            });
        }
    };
});

eventComboApp.directive('telMask', function ($filter, $browser) {
    return {
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            var listener = function () {
                var value = $element.val().replace(/[^0-9]/g, '');
                $element.val($filter('tel')(value, false));
            };

            // This runs when we update the text field
            ngModelCtrl.$parsers.push(function (viewValue) {
                ngModelCtrl.$setValidity("phonePattern", true);
                return viewValue.slice(0, 12);
            });

            // This runs when the model gets updated on the scope directly and keeps our view in sync
            ngModelCtrl.$render = function () {
                $element.val($filter('tel')(ngModelCtrl.$viewValue, false));
            };

            var listenerOverride = function () {
                var regex = /^$|^[0-9]{3}-?[0-9]{3}-?[0-9]{4}$/;
                if (!regex.test($element.val())) {
                    ngModelCtrl.$setValidity("phonePattern", false);
                    return false;
                }
            };

            $element.bind('change', listener);
            $element.bind('blur', listenerOverride);
            $element.bind('keydown', function (event) {
                var key = event.keyCode;
                // If the keys include the CTRL, SHIFT, ALT, or META keys, or the arrow keys, do nothing.
                // This lets us support copy and paste too
                if (key == 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) {
                    return;
                }
                $browser.defer(listener); // Have to do this or changes don't get picked up properly
            });

            $element.bind('paste cut', function () {
                $browser.defer(listener);
            });
        }

    };
});

eventComboApp.filter('tel', function () {
    return function (tel) {
        if (!tel) { return ''; }

        var value = tel.toString().trim().replace(/^\+/, '');

        if (value.match(/[^0-9]/)) {
            return tel;
        }

        var slice1, slice2, slice3;

        switch (value.length) {

            default:
                slice1 = value.slice(0, 3);
                slice2 = value.slice(3, 6);
                slice3 = value.slice(6, 10);
        }

        if (slice1 && slice2 && slice3) {
            return (slice1 + "-" + slice2 + "-" + slice3).trim();
        }
        else if (slice1 && slice2) {
            return (slice1 + "-" + slice2).trim();
        } else if (slice1) {
            return (slice1).trim();
        }

    };
});


function copyToClipboard(copyId) {
    elem = document.getElementById(copyId);
    target = elem;
    var targetId = "_hiddenCopyText_";
    // must use a temporary form element for the selection and copy
    target = document.getElementById(targetId);
    if (!target) {
        var target = document.createElement("textarea");
        target.style.position = "absolute";
        target.style.left = "-9999px";
        target.style.top = "0";
        target.id = targetId;
        document.body.appendChild(target);
    }
    target.textContent = elem.textContent;
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);

    // copy the selection
    var succeed;
    try {
        succeed = document.execCommand("copy");
        clipboardMessage('#clipboardMessage');
    } catch (e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    // clear temporary content
    target.textContent = "";
    return succeed;
}
function clipboardMessage(e) {
    var scope = angular.element(document.getElementById('createEventContainer')).scope();
    scope.showSimpleToast('success-toast', 'Your event link successfully copied to clipboard!');
}

eventComboApp.controller('AccountController', ['$scope', '$http', '$window', '$attrs', '$filter', 'broadcastService', 'accountService',
  function ($scope, $http, $window, $attrs, $filter, broadcastService, accountService) {
    $scope.displayPopups = 'block';
    $scope.email = '';
    $scope.loginPassword = '';
    $scope.loginRememberMe = false;
    $scope.loginError = 'Incorrect password, retry or use Forgot Password.';
    $scope.callerId = null;
    $scope.UserName = accountService.UserName;
    $scope.UserRegistered = accountService.UserRegistered;
    $scope.UserImage = accountService.UserImage;

    $window.loginCallback = function (success, returnUrl) {
      if (success) {
        var ctrl = document.getElementById('accountControllerDiv');
        var service = angular.element(ctrl).injector().get('broadcastService');
        service.CompleteExternalLogin(returnUrl);
      }
      else {
        var ctrl = document.getElementById('accountControllerDiv');
        var service = angular.element(ctrl).injector().get('broadcastService');
        service.ErrorExternalLogin('Login Unsuccessful');
      }
    }

    $scope.$on('ErrorExternalLogin', function (event, mess) {
      $scope.closeLightBoxWithEsc();
      $scope.showInfoMessage(true, mess);
      $scope.$apply();
    });

    $scope.$on('CompleteExternalLogin', function (event, param) {
      $scope.finishLogin();
    });

    $scope.$on('CallLogin', function (event, param) {
      $scope.showLoginForm(param);
    });

    $scope.$on('CallLogout', function (event, param) {
      $scope.logout();
    });

    $scope.$on('ReloadPage', function (event, param) {
      $scope.reloadPage(param);
    });

    $scope.finishLogin = function () {
      $scope.closeLightBoxWithEsc();
      if ($scope.callerId)
        broadcastService.LoggedIn($scope.callerId);
      else
        $scope.reloadPage();
    }

    $scope.showLoadingMessage = function (show, message) {
      $scope.popLoading = show;
      $scope.LoadingMessage = message;
    }

    $scope.showInfoMessage = function (show, message) {
      $scope.popInfoMessage = show;
      $scope.InfoMessage = message;
    }

    $scope.resetForm = function (form) {
      form.$setPristine();
      form.$setUntouched();
    }

    $scope.reloadPage = function (redirectUrl) {
      if (redirectUrl)
        window.location.href = redirectUrl;
      else
        $window.location.reload();
    }

    $scope.showLoginForm = function (info) {
      if (info)
        $scope.callerId = info;
      else
        $scope.callerId = null;
      $scope.popLogin = true;
    }

    $scope.showPasswordForm = function () {
      $scope.loginPassword = '';
      $scope.resetForm($scope.loginPasswordForm);
      $scope.popLoginPassword = true;
    }

    $scope.showRegisterForm = function () {
      $scope.password = '';
      $scope.resetForm($scope.registerForm);
      $scope.popRegister = true;
    }

    $scope.showForgetPasswordForm = function () {
      $scope.popLoginPassword = false;
      otpPassword = "";
      $scope.resetForm($scope.otpPasswordForm);
      $scope.showLoadingMessage(true, 'Sending code');
      $http.get('/account/forgotPasswordAPI', { params: { email: $scope.email } }).then(
        function (response) {
          $scope.showLoadingMessage(false, '');
          $scope.popForgetPassword = response.data.Success;
          if (!response.data.Success)
            $scope.showInfoMessage(true, response.data.ErrorMessage);
        }, function (error) {
          $scope.showLoadingMessage(false, '');
          $scope.popServerError = true;
        });
    }

    $scope.showCreatePasswordForm = function () {
      $scope.newPassword = "";
      $scope.repeatPassword = "";
      $scope.resetForm($scope.newPasswordForm);
      $scope.popCreatePassword = true;
    }

    // logout submit
    $scope.logout = function () {
      $scope.showLoadingMessage(true, 'Logging out');
      $http.post('/account/logoutAPI', {}).then(function (response) {
        $scope.showLoadingMessage(false, '');
        $scope.callerId = null;
        $scope.reloadPage();
      }, function (response) {
        $scope.showLoadingMessage(false, '');
        $scope.callerId = null;
        $scope.reloadPage();
      });
    }

    // signin submit
    $scope.signInNext = function (form) {
      if ($scope[form].$valid) {
        $scope.submitted = false;
        $scope.popLogin = false;
        $scope.showLoadingMessage(true, 'Checking email');
        $http.get('/account/checkusername', { params: { userName: $scope.email } }).then(function (response) {
          $scope.showLoadingMessage(false, '');
          var result = response.data.Success;
          if (result) { $scope.showPasswordForm(); }
          else { $scope.showRegisterForm(); }
        }, function (error) {
          $scope.showLoadingMessage(false, '');
          $scope.popServerError = true;
        });
      } else { $scope.submitted = true; }
    };

    // login password submit
    $scope.loginPasswordNext = function (form) {
      if ($scope[form].$valid) {
        $scope.popLoginPassword = false;
        $scope.showLoadingMessage(true, 'Logging in');
        $http.post('/account/loginAPI', {
          json: angular.toJson({
            Email: $scope.email,
            Password: $scope.loginPassword,
            RememberMe: $scope.loginRememberMe
          })
        }).then(function (response) {
          $scope.showLoadingMessage(false, '');
          var result = response.data.Success;
          if (result) 
            $scope.finishLogin();
          else {
            $scope.popLoginPassword = true;
            $scope.loginError = response.data.ErrorMessage;
            $scope.IncorrectPassword = true;
          }
        }, function (error) {
          $scope.showLoadingMessage(false, '');
          $scope.popServerError = true;
        });
      }
      else {
        if ($scope[form].loginPassword.$error.required) { $scope.loginPasswordRequired = true; }
      }
    };

    // register submit
    $scope.registerNext = function (form) {
      if ($scope[form].$valid) {
        $scope.popRegister = false;
        $scope.showLoadingMessage(true, 'Registering');
        $http.post('/account/SignupAPI', {
          json: angular.toJson({
            Email: $scope.email,
            FirstName: $scope.firstName,
            LastName: $scope.lastName,
            Password: $scope.password
          })
        }).then(function (response) {
          $scope.showLoadingMessage(false, '');
          var result = response.data.Success;
          if (result) {
            $scope.popRegisterCongrats = true;
          }
          else {
            $scope.popRegister = true;
            $scope.signupError = response.data.ErrorMessage;
          }
        }, function (error) {
          $scope.showLoadingMessage(false, '');
          $scope.popServerError = true;
        });
      }
      else {
        if ($scope[form].firstName.$error.required) { $scope.firstNameRequired = true; }
        if ($scope[form].lastName.$error.required) { $scope.lastNameRequired = true; }
        if ($scope[form].password.$error.required) { $scope.passwordRequired = true; }
      }
    };

    // OTP Password submit
    $scope.otpPasswordNext = function (form) {
      if ($scope[form].$valid) {
        $scope.popForgetPassword = false;
        $scope.showLoadingMessage(true, 'Checking password');
        $http.post('/account/CheckCodePasswordAPI', {
          json: angular.toJson({
            Email: $scope.email,
            Password: $scope.otpPassword
          })
        }).then(function (response) {
          $scope.showLoadingMessage(false, '');
          var result = response.data.Success;
          if (result) {
            $scope.showCreatePasswordForm();
          }
          else {
            $scope.popForgetPassword = true;
            $scope.IncorrectotpPassword = true;
          }
        }, function (error) {
          $scope.showLoadingMessage(false, '');
          $scope.popServerError = true;
        });
      }
      else {
        if ($scope[form].otpPassword.$error.required) { $scope.otpPasswordRequired = true; }
      }
    };

    // Create a new password 
    $scope.newPasswordNext = function (form) {
      if ($scope[form].$valid) {
        if ($scope.newPassword == $scope.repeatPassword) {
          $scope.popCreatePassword = false;
          $scope.showLoadingMessage(true, 'Creating password');
          $http.post('/account/ResetPasswordAPI', {
            json: angular.toJson({
              Email: $scope.email,
              Password: $scope.newPassword,
              ConfirmPassword: $scope.repeatPassword,
              Code: $scope.otpPassword
            })
          }).then(function (response) {
            $scope.showLoadingMessage(false, '');
            var result = response.data.Success;
            if (result) {
              $scope.popCreatePasswordCongrats = true;
            }
            else {
              $scope.showInfoMessage(true, result.ErrorMessage);
            }
          }, function (error) {
            $scope.showLoadingMessage(false, '');
            $scope.popServerError = true;
          });
        }
        else {
          $scope.passwordNotMatch = true;
        }
      }
      else {
        if ($scope[form].newPassword.$error.required) { $scope.newPasswordRequired = true; }
        if ($scope[form].repeatPassword.$error.required) { $scope.repeatPasswordRequired = true; }
      }
    };

    // Escape on the keyboard close all popup
    $scope.closeLightBoxWithEsc = function () {
      $scope.popLogin = false;
      $scope.popRegister = false;
      $scope.popLoginPassword = false;
      $scope.popForgetPassword = false;
      $scope.popCreatePassword = false;
      $scope.popCreatePasswordCongrats = false;
      $scope.popRegisterCongrats = false;
      $scope.popLoading = false;
      $scope.popServerError = false;
      $scope.popInfoMessage = false;
    };

    $scope.externalLogin = function (site) {
      $scope.popLogin = false;
      // Delete the Requested With Header
      delete $http.defaults.headers.common['X-Requested-With'];
      $scope.showLoadingMessage(true, 'Creating password');
      $http({
        method: 'GET',
        url: '/account/ExternalLoginAPI',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Access-Control-Allow-Origin': '*'
        },
        //        data: $.param({
        //          json: angular.toJson({
        //            Provider: site,
        //            ReturnUrl: $window.location.href
        //          })
        params: {
          provider: site,
          returnUrl: $window.location.href
        }
      }).then(function (response) {
        $scope.showLoadingMessage(false, '');
        console.log(response);
      }, function (error) {
        $scope.showLoadingMessage(false, '');
        console.log(error);
      });
    }
  }]);

eventComboApp.directive('ngEsc', function () {
  return function (scope, element, attrs) {
    element.bind("keydown keypress keyup", function (event) {
      if (event.which === 27) {
        scope.$apply(function () {
          scope.$eval(attrs.ngEsc);
        });

        event.preventDefault();
      }
    });
  };
});
