/**
* RegistrationController module used to communicate with the backend, register a worker, give feedback,
* and control 'register.html' as an interface to the end-users.
* Jai.
* CloudTech 2016.
* Omar Kanawati.
*/
/**
* Base url used in all API calls.
* @type {string}
*/
const baseUrl = 'https://production-api.Jai.site/';
/**
* Flag Variable used to indicate whether the user has been verified as non-robot by reCaptcha.
* @type {boolean}
*/
var verified = false;
var errors = [];
/**
* Handles event when the document is loaded.
*/
window.onload = function(){
var queryString = getParameterByName("id");
$("#formReferredBy").val(queryString);
//Handle the event if the submit button is clicked.
// if(!verified) $('#registrationError').text('الرجاء التحقق من كونك لست روبوت.')
// else
//$('#submitButton').click(function(){
//return false;
//});//End handles submitButton.
//Prevent the form from submitting by itself.
$('#registrationForm').submit(function(e){
e.preventDefault();
errors = [];
uploadImages();
return false;
});//End of registrationForm submission.
//Phone number validation.
};//End of document ready event handler.
/* upload worker images before submit */
function uploadImages() {
hideMessages();
//form validation
//inputs
var phone = $('#formUserName').val();
var name = $('#formWorkerName').val();
var g_id = $('#formGovId').val();
var sponser = $('#formSponsorName').val();
var job = $('#formFields').val();
var city = $('#formCity').val();
var terms = $('#formCheckbox').prop('checked');
var regNameAr = /^[\u0621-\u064A ]+$/;
var regNameEn = /^[a-zA-Z]+$/;
//Check if the checkbox is checked
if(isNaN(phone) || phone.slice(0,2) != 05 || phone.length != 10 || phone =='') {
errors.push('أدخل رقم جوال بصيغة صحيحة (05xxxxxxxx).
');
}
if((!(regNameEn.test(name) || regNameAr.test(name))) || name ==''){
errors.push('ادخل اسم الفني بطريقة صحيحة.
');
}
if(isNaN(g_id) || g_id.length != 10 || g_id =='') {
errors.push('رقم الهوية يجب ان يكون 10 ارقام.
');
}
if(sponser !='') {
if(!(regNameEn.test(sponser) || regNameAr.test(sponser))){
errors.push('ادخل اسم الكفيل بطريقة صحيحة.
');
}
}
if(job =='' || job == null) {
errors.push('يجب اختيار المهنة.
');
}
if(city =='' || city == null) {
errors.push('يجب اختيار المدينة.
');
}
if(!terms){
errors.push('يجب الموافقة على الشروط.
');
}
if(!$('#workerId').prop('files')[0] || !$('#workerPP').prop('files')[0]) {
errors.push('يجب ارفاق صورة الهوية والصورة الشخصية.
');
}
if (errors.length == 0) {
var worker_id = $('#workerId').prop('files')[0];
var worker_pp = $('#workerPP').prop('files')[0]
var form_data = new FormData();
if(worker_id && worker_pp) {
form_data.append('workerId', worker_id);
form_data.append('workerPP', worker_pp);
}
$.ajax({
url: '/gc/index.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
var res = JSON.parse(data);
if(res.status == 1) {
submitForm(res.data.id,res.data.pp);
} else {
if(res.status == 10) {
errors.push('الصور المدعومة فقط من نوع jpg,png,gif.
');
} else {
errors.push('يجب ارفاق صورة الهوية والصورة الشخصية.
');
}
}
}
});
} else {
errors.forEach(function (err) {
$('#registrationError').append(err);
});
}
}; /* End of Upload */
/**
* Handles the event of submitting a form.
*/
function submitForm(id,pp) {
var send_id = id;
var send_pp = pp;
console.log(send_id,send_pp);
//Hide alerts.
if (errors.length > 0) {
errors.forEach(function (err) {
$('#registrationError').append(err);
});
} else {
//Get entered form data.
var data = getFormData(send_id,send_pp);
//Register the user in the server.
sendToServer('post',baseUrl+'users/NotActiveWorkerSignUp', data, registrationSuccess, registrationFailure);
}
};//End of RegistrationForm submit event handler.
/**
* Callback function called by reCaptcha By Google, to verify the user.
* @param response Object
*/
function captchaResponse(responseString){
//Create the request data.
var data = {
response: responseString
};
//Send to Google's server the response string.
sendToServer('post', baseUrl+"misc/verifyCaptcha", data,
//In case of successful post
function(data, textStatus, jqXHR){
//Check if the user is valid.
if(jqXHR.responseJSON.verified){
console.log("Verified!");
verified = true;
}
else{
$('#registrationError').text('لم يتم التأكد من كونك لست روبوت');
}
},
//In case of failed post.
function(error){
$('#registrationError').text('حصل خطأ أثناء عملية التأكد من صلاحية الطلب');
});//End of send to server.
}//End of captchaResponse function.
/**
* Returns the entered information in the form.
*/
function getFormData(id,pp){
var data = {};
var username = $('#formUserName').val();
data.username = '966' + username.substring(username.indexOf('5'));
//data.username = $('#formUserName').val();
data.city = $('#formCity').val();
data.fields = [$('#formFields').val()];
data.sponsor = $('#formSponsorName').val();
data.governmentId = $('#formGovId').val();
data.name = $('#formWorkerName').val();
data.referredBy = $('#formReferredBy').val();
data.identityImageUrl = id;
data.picURL = pp;
return data;
};//End of GetFormData.
/**
* Sends a HTTP POST request to the server.
* @param type String parameter.
* @param url Destination url. (without hostname).
* @param data Data to send [Optional].
* @param successFunc Callback function in case of success.
* @param failFunc Callback function in case of failure.
*/
function sendToServer(type, url, data, successFunc, failFunc){
$.ajax({
url : url,
data: data,
type: type
}).done(successFunc).fail(failFunc);
}//End of post to server.
/**
* Callback function handles the case of successful registration.
*/
function registrationSuccess(){
$('#registrationFeedback').text("تم استلام طلبك وبنتواصل معك في اقرب وقت لتنشيط حسابك.");
setTimeout(function(){
$('#registrationForm').trigger("reset");
$('#formSponsorName').attr('required',true).show();
}, 300);
}//End of registration success.
/**
* Callback function handles the case of failure registration.
*/
function registrationFailure(request, error){
$('#registrationError').text(request.responseJSON.message);
//$('#registrationError').text('حصل خطأ ما في التسجيل...');
}//End of registration failure.
/**
* Helper function that hides the feedback messages.
*/
function hideMessages(){
$('.feedback').text('');
}//End of hide messages.
/**
* Helper function that gets the referredBy from the url.
* @param name
* @param url
*/
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}//End of getParameterByName.
//validation
$('#formGovId').on('keyup',function(){
if($(this).val().slice(0,1) == 1 || !$(this).val()) {
$('#formSponsorName').removeAttr('required').hide().val('');
} else {
$('#formSponsorName').attr('required',true).show();
}
});
$(document).on('click','.form-group.upload button',function(){
$(this).parents('.form-group').find('input[type=file]').click();
});
$(document).on("change",'.form-group.upload input[type=file]', function(e){
$(this).parents('.form-group').find('input[type=text]').val(e.target.files[0].name);
})