Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amixpal/e52c3f75c15c7f3a42fc09bf08162022 to your computer and use it in GitHub Desktop.
Save amixpal/e52c3f75c15c7f3a42fc09bf08162022 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
HandleLoginFunction();
});
var GenericErrorMessage = "Something went wrong! Please try again later.";
var NoDataErrorMessage = "No Data to show";
var IdErrorMessage = "ID does not exists";
var AppRegistrationFailureMessage = "Failed to register app with the server. Please try again later.";
var AppRegistrationGuid = "";
var AJAX_CALL_API_BASE = "http://35.226.205.65:9000/v1";
var googleapiloaded = false;
var autocomplete;
var representativDivId = 0;
/* ------ START -- admin login --------*/
function HandleLoginFunction() {
var formElement = $("#loginadminform")[0];
var validator = new FormValidator({"events" : ['blur', 'input', 'change']}, formElement);
$("#loginAdminSubmitBtn").click(function(e) {
if (e.isDefaultPrevented()) {
return;
} else {
e.preventDefault();
}
// First Make a call to register Guid
if (AppRegistrationGuid.length <= 0){
AppRegistrationGuid = GenerateGuid();
}
var GuidData = {"guid": AppRegistrationGuid};
$.ajax({
type: "POST",
dataType: "json",
url: AJAX_CALL_API_BASE + "/app",
data: JSON.stringify(GuidData),
headers: { 'Content-type': 'application/json' },
success: function(response) {
if (response.success == true) {
if (response.error) {
$("#loginadminformerrdiv p").html(AppRegistrationFailureMessage + ": " + response.message);
$("#loginadminformerrdiv").show();
} else {
VerifyLoginCredentials();
}
} else {
$("#loginadminformerrdiv p").html(AppRegistrationFailureMessage + ": " + response.message);
$("#loginadminformerrdiv").show();
}
},
error: function(response) {
if (response && response.responseJSON && response.responseJSON.error) {
$("#loginadminformerrdiv p").html(AppRegistrationFailureMessage + ": " + response.responseJSON.error);
$("#loginadminformerrdiv").show();
} else {
$("#loginadminformerrdiv p").html(AppRegistrationFailureMessage);
$("#loginadminformerrdiv").show();
}
}
});
});
}
function VerifyLoginCredentials(){
var _email = $("#emailidAdmin").val();
var _pass = $("#passwordAdmin").val();
var loginData = {
email: _email,
password: _pass,
guid: AppRegistrationGuid
};
$.ajax({
type: "POST",
dataType: "json",
url: AJAX_CALL_API_BASE + "/admin/login",
data: JSON.stringify(loginData),
headers: {
'Content-type': 'application/json',
},
success: function(response) {
if (response.success == true) {
$("#loginadminformerrdiv p").html("");
$("#loginadminformerrdiv").hide();
if (response.data && response.data.clientToken && response.data.guid){
SendSessionCreationRequest(_email, response.data.clientToken, response.data.guid, "#loginadminformerrdiv");
} else if (response.error) {
$("#loginadminformerrdiv p").html(response.error);
$("#loginadminformerrdiv").show();
} else {
$("#loginadminformerrdiv p").html("Authorization token not found in response");
$("#loginadminformerrdiv").show();
}
} else {
$("#loginadminformerrdiv p").html(response.message);
$("#loginadminformerrdiv").show();
}
},
error: function(response) {
if (response && response.responseJSON && response.responseJSON.error) {
$("#loginadminformerrdiv p").html(response.responseJSON.error);
$("#loginadminformerrdiv").show();
} else {
$("#loginadminformerrdiv p").html(GenericErrorMessage);
$("#loginadminformerrdiv").show();
}
}
});
}
function SendSessionCreationRequest(_email, _token, _guid, errorDiv) {
$.ajax({
type: "POST", dataType: "json", url: '/home/login',
data: {
'emailId': _email,
'token': _token,
'guid': _guid,
},
success: function(response) {
if (response.status == "success") {
$(errorDiv + " p").html("");
$(errorDiv).hide();
var targeturl = GetLoggedinUrl();
window.location.href = targeturl;
} else {
$(errorDiv + " p").html(response.message);
$(errorDiv).show();
}
},
});
}
/* ------ END -- admin login --------*/
/* ------ START -- Helper methods --------*/
function SendDataToFirebase(file,folderName) {
var returnurl = '';
//file.previewElement.classList.remove("dz-complete");
// Create a root reference
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
var filename = encodeURI(file.name);
var uploadTask = storageRef.child(folderName+ "/" + filename).put(file);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
function(snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
// var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
// console.log('Upload is ' + progress + '% done');
// $(".data-dz-uploadprogress").show().css('width', progress + "%");
//
// if (file.previewElement) {
// var _ref = file.previewElement.querySelectorAll("[data-dz-uploadprogress]");
// _results = [];
// for (_i = 0, _len = _ref.length; _i < _len; _i++) {
// node = _ref[_i];
// if (node.nodeName === 'PROGRESS') {
// _results.push(node.value = progress);
// } else {
// _results.push(node.style.width = "" + progress + "%");
// }
// }
// }
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
//console.log(error.code);
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
file.previewElement.classList.add("dz-error");
file.previewElement.querySelector(".dz-error-message").style.display = "none";
}, function() {
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
returnurl = downloadURL;
file.previewElement.classList.add("dz-success");
file.previewElement.setAttribute("dz-success-urlDonwloaded", downloadURL);
});
});
}
function GetLoggedinUrl() {
return "/admin";
}
function GenerateGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
function statusInToValue(status) {
if (status === 0) {
return "On Location";
} else if (status === 1) {
return "Gym Only";
} else if (status === 2) {
return "Gym and on Location";
}
return "undefined";
}
function paymentMethodMapping(mapping) {
if (mapping === 0) {
return "ApplePay";
} else if (mapping === 1) {
return "GooglePay";
} else if (mapping === 2) {
return "Card";
}
return "undefined";
}
function availabilityValue_old(availability) {
if (availability === 0) {
return "On Demand";
} else if (availability === 1) {
return "Gym";
}
return "undefined";
}
function availabilityValue(availability) {
var returnValue = "";
if (availability && $.isArray(availability)) {
$.each(availability, function(i, item) {
switch(item) {
case 1:
returnValue += "<span class='label label-default nameSpanleft'> MORNING (6AM - 11AM) </span> ";
break;
case 2:
returnValue += "<span class='label label-default nameSpanleft'> AFTERNOONS (12PM - 4PM) </span>";
break;
case 3:
returnValue += "<span class='label label-default nameSpanleft'> EVENINGS (5PM - 9PM) </span> ";
break;
case 4:
returnValue += "<span class='label label-default nameSpanleft'> LATE NIGHT (10PM - 4AM) </span> "
break;
}
});
}
return returnValue;
}
function IfElementWithIdExists(id) {
if ($("#" + id).length > 0) {
return true;
}
return false;
}
function IfElementWithClassExists(_class) {
if ($("." + _class).length > 0) {
return true;
}
return false;
}
function CommonAjaxHeaders() {
return {
"token": loggedInUser.token,
"user": loggedInUser.guid,
'Content-type': 'application/json'
}
}
function CommonErrorHandler(errorDiv) {
if ((typeof(loggedInUser) != 'undefined') && loggedInUser) {
return true;
}
return false;
}
function longToDateFormat(longDate){
var d = new Date(longDate);
var month_names = ["Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"];
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
return month_names[month] + ' ' + date + ' ,' + year;
}
function datetimestamp(longDate){
var d = new Date(longDate);
var month_names = ["Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"];
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var hours = ((d.getHours() % 12 || 12) < 10 ? '0' : '') + (d.getHours() % 12 || 12);
var minutes = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
var meridiem = (d.getHours() >= 12) ? 'PM' : 'AM';
return month_names[month] + ' ' + date + ' ' + year +' ,' +hours + ':' + minutes + ' ' + meridiem;
}
function chatDateFormat(longDate){
var d = new Date(longDate);
var month_names = ["Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"];
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var hours = ((d.getHours() % 12 || 12) < 10 ? '0' : '') + (d.getHours() % 12 || 12);
var minutes = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
var meridiem = (d.getHours() >= 12) ? 'PM' : 'AM';
return month_names[month] + ' ' + date + ', '+hours + ':' + minutes + ' ' + meridiem;
}
function longToTimeHHMMFormat(timestamp){
var d = new Date(timestamp);
var hours = ((d.getHours() % 12 || 12) < 10 ? '0' : '') + (d.getHours() % 12 || 12);
var minutes = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
var meridiem = (d.getHours() >= 12) ? 'PM' : 'AM';
return hours + ':' + minutes + ' ' + meridiem;
}
function minuteFormat(timestamp){
var d = new Date(timestamp);
var minutes = (d.getMinutes() < 10 ? '0' : '') + d.getMinutes();
return minutes + " minutes" ;
}
/* -------- Sorting functions ------- */
function sortByKeyStringDesc(array, key) {
return array.sort(function (a, b) {
var x = a[key].toLowerCase();
var y = b[key].toLowerCase();
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
}
function sortByKeyStringAsc(array, key) {
return array.sort(function (a, b) {
var x = a[key].toLowerCase();
var y = b[key].toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function sortByKeyDesc(array, key) {
return array.sort(function (a, b) {
var x = a[key];
var y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
}
function sortByKeyAsc(array, key) {
return array.sort(function (a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function getStarRating(rating, numStars) {
var fullStar = new Array(Math.floor(rating + 1)).join('<i class="fa fa-star"></i>');
var halfStar = ((rating%1) !== 0) ? '<i class="fa fa-star-half-o"></i>': '';
var noStar = new Array(Math.floor(numStars + 1 - rating)).join('<i class="fa fa-star-o"></i>');
return fullStar + halfStar + noStar;
}
function handleImageOnError(imgId) {
$(imgId).error(function() {
$(this).unbind("error").attr("src", "/assets/images/user.png");
});
}
/* ------ END -- Helper methods --------*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment