var $ = jQuery; $(document).ready(function () { $(".close-alert").click(function () { $(this).parent().hide(); }); $('#job-type-modal').modal({ backdrop: 'static', keyboard: false, show: true }); $('.select2-checkbox').each(function(i, elem){ $(elem).select2({ closeOnSelect: false, "language": { "noResults": function(){ return $(elem).data('locale') == 'ar' ? "لم يتم العثور علي نتائج" : "No results found"; } }, }).data('select2').$dropdown.addClass('select2-checkbox-container'); }); $("#chkall").click(function(){ if($("#chkall").is(':checked')){ $("#L-job-major > option").prop("selected", "selected"); $("#L-job-major").trigger("change"); } else { $("#L-job-major > option").removeAttr("selected"); $("#L-job-major").trigger("change"); } }); jQuery('#new-job-type').submit(function(e) { $('.help').hide(); e.preventDefault(); showLoader(); $.ajax({ type: 'POST', url: $(this).prop('action'), data: $(this).serialize(), dataType: 'json', success: submissionSuccess }).fail(function (e) { hideLoader(); if (e.responseJSON && e.responseJSON.errors && 422 === e.status) { let errors = e.responseJSON.errors; for (let key in e.responseJSON.errors) { let $help = $('#' + key + '-help'); $help.text(errors[key]); $help.show(); } } else { $('#job-type-modal').modal('toggle'); } }); }); $('#close-skills-hint').click(function (e) { $.cookie('skills_check',0, { path: '/' }); }); // Resend activation link via email const $activation_link = $('#resend-activation'); if ($activation_link.length > 0) { $activation_link.click(function (e) { e.preventDefault(); showLoader(); const $form = $('#resend-activation-form'); $.ajax({ url: $form.attr('action'), method: 'POST', data: $form.serialize() }).done(res => window.location = res.data.redirect_to) .fail(e => window.location = e.responseJSON.data.redirect_to) .always(_ => hideLoader()); }); } $('#close-job-titles-hint').click(function (e) { $.cookie('job_titles_check',0, { path: '/' }); }); $.fn.select2.defaults.set('language', { noResults: function () { return opts.no_results; } }); if ($('.skills-input').length>0 ) { $('.skills-input').select2(); } bindDatepicker(); if ( $('[data-toggle="tooltip"]').length>0) { $('[data-toggle="tooltip"]').tooltip(); } $(document).on('submit', 'form.ajax-form', function (e) { e.preventDefault(); var success_fn = $(this).data('success'); var success_args = $(this).data('success-args'); if (success_fn != undefined) { success_fn = window[success_fn]; if (success_args != undefined) { success_fn = success_fn(...success_args.split(',')); } } else { success_fn = submissionFormSuccess; } var data = new FormData(this) $.ajax({ url: ajax_object.ajax_url, method: 'post', data: data, dataType: 'json', processData: false, contentType: false, beforeSend: function() { showLoader(); }, success: success_fn, error: submissionFormError('form.ajax-form'), complete: function() { hideLoader(); } }); }); $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { trigger_truncate_action(); }); $( '.arial' ).each( function() { $element = $(this); $element.html( $element.html().toIndiaDigits ); } ); if ($('.select2-multiple').length>0) { $('.select2-multiple').select2({ tags: true, tokenSeparators: [','], minimumInputLength: 2 }); } // Teleworker Skills if ($('.L-select-teleworker-skill').length > 0) { let $select2 = $('#teleworkers-skills'); $select2.select2({ language: $select2.data('locale'), tokenSeparators: [','], minimumInputLength: 2, ajax: { url: $select2.data('url'), dataType: 'json', delay: 250, data: function (params) { return { search_term: params.term // search term }; }, processResults: function (response) { return { results: response.data['skills'] }; }, cache: true } }); } if( $('.L-teleworker-job-skills').length > 0 ){ url = decodeURIComponent( window.location.search); const result = url.split('&') const jobSkillsList = result.filter((item) => item.includes('q[job_skills][]=')) const jobSkillsNumbers = [] jobSkillsList.forEach(item => { jobSkillsNumbers.push(item.split('=')[1]) }) let $job_skills_select2 = $('#L-teleworker-job-skills'); if (jobSkillsNumbers.length > 0) { $job_skills_select2.select2({ language: { inputTooShort: function(args) { // args.minimum is the minimum required length // args.input is the user-typed text return $job_skills_select2.data('locale') ? "الرجاء اضافه 2 عنصر" : "please enter 2 or more character"; }, inputTooLong: function(args) { // args.maximum is the maximum allowed length // args.input is the user-typed text return "You typed too much"; }, noResults: function() { return $job_skills_select2.data('locale') ? "لم يتم العثور علي نتائج" : "No results found"; }, searching: function() { return $job_skills_select2.data('locale') ? "جاري البحث..." : "Searching..."; }, }, tokenSeparators: [','], minimumInputLength: 2, ajax: { url: $job_skills_select2.data('url'), dataType: 'json', delay: 250, data: function (params) { return { search_term: params.term // search term }; }, processResults: function (response) { return { results: response.data.skills, more: false }; }, cache: true }, initSelection: function (element, callback) { var id = $(element).val(); if(id !== "") { $.ajax("/ar/skills/search/", { data: {skills: jobSkillsNumbers}, dataType: "json" }).done(function(data) { $skills = data.data.skills; $skills.forEach(function(item) { element.append(''); callback({id: item.id,text: item.text}); }) }); } } }); } else { $job_skills_select2.select2({ language: { inputTooShort: function(args) { // args.minimum is the minimum required length // args.input is the user-typed text return $job_skills_select2.data('locale') ? "الرجاء اضافه 2 عنصر" : "please enter 2 or more character"; }, inputTooLong: function(args) { // args.maximum is the maximum allowed length // args.input is the user-typed text return "You typed too much"; }, noResults: function() { return $job_skills_select2.data('locale') ? "لم يتم العثور علي نتائج" : "No results found"; }, searching: function() { return $job_skills_select2.data('locale') ? "جاري البحث..." : "Searching..."; }, }, tokenSeparators: [','], minimumInputLength: 2, ajax: { url: $job_skills_select2.data('url'), dataType: 'json', delay: 250, data: function (params) { return { search_term: params.term // search term }; }, processResults: function (response) { return { results: response.data.skills, more: false }; }, cache: true } }); } } $('#job_type_id').change(function() { let $txtFieldWrap = $(this).parents('.L-job_type_select_gp').find('.L-others_select_text'); let $txtCheck = $(this).parents('.L-job_type_select_gp').find('.job-type-notification'); let $type = $(this).val(); if( $type == 'Others') { $txtFieldWrap.show(); $txtCheck.hide(); } else { $txtFieldWrap.hide(); $txtCheck.show(); } }); $('#job-type').change(function() { let $txtFieldWrap = $(this).parents('.L-job_type_select_gp').find('.L-others_select_text'); let $type = $(this).val().split('-'); if( $type[1] == 'Others') { $txtFieldWrap.show(); } else { $txtFieldWrap.hide(); } }); $('#job-type').change(function() { let $txtFieldWrap = $(this).parents('.L-job_type_select_gp').find('.L-others_select_text'); let $type = $(this).val().split('-'); if( $type[1] == 'Others') { $txtFieldWrap.show(); } else { $txtFieldWrap.hide(); } }); $('#job_title_id').change(function() { let $txtFieldWrap = $(this).parents('.L-job_title_select_gp').find('.L-others_select_text'); let $title = $(this).val(); if( $title == 'Others') { $txtFieldWrap.show(); } else { $txtFieldWrap.hide(); } }); // Disable teleworker save skills button while selecting from the drop-down results $('#teleworkers_skills').on('select2:opening', function () { $('#save-skills-button').prop( 'disabled', true ); }); // Enable Teleworker save skills button while selecting from the drop-down results $('#teleworkers_skills').on('select2:select select2:close', function () { $('#save-skills-button').prop( 'disabled', false ); }); // Job Skills if( $('.L-select-job-skills').length > 0 ){ let $job_skills_select2 = $('#job_skills'); $job_skills_select2.select2({ language: $job_skills_select2.data('locale'), tokenSeparators: [','], minimumInputLength: 2, ajax: { url: $job_skills_select2.data('url'), dataType: 'json', delay: 250, data: function (params) { console.log(123); return { search_term: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); } // Disable Company/SP new job button while selecting from skills drop-down results $('#job_skills').on('select2:opening', function () { $('#save-job-button').prop( 'disabled', true ); }); // Enable Teleworker new job button while selecting from skills drop-down results $('#job_skills').on('select2:select select2:close', function () { $('#save-job-button').prop( 'disabled', false ); }); // Employee Page search skills if( $('.L-system-skills').length > 0 ){ let $system_skill_select2 = $('#search-system-skills'); $system_skill_select2.select2({ tags: true, language: $system_skill_select2.data('locale'), tokenSeparators: [','], minimumInputLength: 2, ajax: { url: $system_skill_select2.data('url'), dataType: 'json', delay: 250, data: function (params) { return { search_term: params.term // search term }; }, processResults: function (response) { return { results: response }; }, cache: true } }); } // Disable search employees button while selecting from skills drop-down results $('#search-system-skills').on('select2:opening', function () { $('#search-employees-button').prop( 'disabled', true ); }); // Enable search employees button while selecting from skills drop-down results $('#search-system-skills').on('select2:select select2:close', function () { $('#search-employees-button').prop( 'disabled', false ); }); $('.secured-attachment').click(function(e) { e.preventDefault(); $(this).siblings(".secured-attachment-form").submit(); }); // Clear filter forms and resubmit $('#clear_filters_form').on('click', function () { $(this).closest('form').find('input[type=text], textarea').val(''); $('.submit_filters_form').click(); }); $('#new-project-form').on('hidden.bs.modal', function () { $('.collapse').collapse('hide'); }); function showHideText(sSelector, options) { // Def. options var defaults = { charQty: 100, ellipseText: "...", moreText: "Show more", lessText: "Show less" }; var settings = $.extend({}, defaults, options); var s = this; s.container = $(sSelector); s.containerH = s.container.height(); s.container.each(function () { var content = $(this).html(); if (content.length > settings.charQty) { var visibleText = content.substr(0, settings.charQty); var hiddenText = content.substr(settings.charQty, content.length - settings.charQty); var html = visibleText + '' + settings.ellipseText + '' + hiddenText + '' + settings.moreText + ''; $(this).html(html); } }); s.showHide = function (event) { event.preventDefault(); if ($(this).hasClass("less")) { $(this).removeClass("less"); $(this).html(settings.moreText); $(this).prev().fadeToggle('fast', function () { $(this).parent().prev().fadeIn(); }); } else { $(this).addClass("less"); $(this).html(settings.lessText); $(this).parent().prev().hide(); $(this).prev().fadeToggle('fast'); } } $(".morelink").bind('click', s.showHide); } var th = new showHideText('.collapsible-text', { charQty: 250, ellipseText: "...", moreText: "", lessText: "" }); handleFormError(); $(document).ajaxComplete(function() { handleFormError(); }); }); function trigger_truncate_action() { let elementsToEllipsis = $('[data-toggle="ellipsis"]'); elementsToEllipsis.each((i, element) => { let $element = $(element); let options = {}; if( $element.data('type') !== undefined ) options.type = $element.data('type'); if( $element.data('count') !== undefined ) options.count = $element.data('count'); $ellipsis_element = $.data($element[0], 'plugin_ellipsis'); if($ellipsis_element){ $ellipsis_element.reset( options ); } $element.ellipsis(options); }); } function submissionFormSuccess(res) { location.reload(); } function submissionFormError(form_selector) { return function(err) { hideLoader() // Remove all error fields before populating errors $(form_selector + ' div.error').remove(); $(form_selector).find(":submit").removeAttr( "disabled" ); var errors = err.responseJSON.data for (var errorField in errors) { var selector = form_selector + " [name=" + errorField + "]"; var $inputFormGroup = $(selector).parent(); $inputFormGroup.append("
" + errors[errorField] + "
"); } } } function load_more_func(action, count, records_per_page, container_selector, loadmore_selector) { var page = 1; var current_count = records_per_page; return function(event) { event.preventDefault(); $(loadmore_selector).attr('disabled', 'disabled'); page++; var data = { action: action, page: page}; showLoader() $.ajax({ type: "POST", url: ajax_object.ajax_url, data: data, success: function(response) { hideLoader(); var obj = response.data; if(obj.html != 0){ current_count += records_per_page; if (count <= current_count) { $(loadmore_selector).hide(); } else { $(loadmore_selector).removeAttr('disabled'); } $(container_selector).append(obj.html); } } }); } } function showLoader() { $('#tele-loader').show(); } function hideLoader() { $('#tele-loader').hide(); } var truncateString = function(str, length) { if( !str ) return str; var dots = str.length > length ? '...' : ''; return str.substring(0, length)+dots; }; var trauncateElement = function( element, length ) { $( element ).html( truncateString( $( element ).html() , length) ); } $(document).ready( function() { if( $('#navbarDropdown span').length ) { trauncateElement( '#navbarDropdown span', 15 ); } } ); String.prototype.toIndiaDigits = function() { var id = ['٠','١','٢','٣','٤','٥','٦','٧','٨','٩']; return this.innerHTML.replace(/[0-9]/g, function(w) { return id[+w]; }); }; /** * AJAX call for posts and custom post types, considering pagination * and depends on Paginator class for pagination response * * @param payload Plain Js object containing the request payload * @param updatePosts Callback function to be called with the returned HTML * @param onFailure Callback function to be called on request failure * @param additionalParams Object with added query parameters */ function paginatePosts( payload, updatePosts, onFailure = null, additionalParams = {} ) { showLoader(); $.extend(payload, additionalParams); let url; if(isUrl(payload['action'])){ // JQuery does not send query parameters unless the URL is appended by "/" // http://example.com/path/to/action/?current_page=1 works // http://example.com/path/to/action?current_page=1 does not work! url = slashIt(payload['action']); delete payload['action']; } else { url = ajaxurl; } $.get({url, data: payload, cache: false}).done(function (res) { if(res['data'] && res['data'].data){ res = res['data'].data } updatePosts(res.items_html, res.total_pages); }).fail(function (error) { if (null !== onFailure) { onFailure(error); } else { console.log(error); } }).always(function () { hideLoader(); }); } /** * AJAX call to backend server for paginated posts * with rendering response into HTML elements * * @param action String * @param $itemsContainer JQuery * @param $showMore JQuery * @param currentPage String * @param perPage String * @param additionalParams Object * @param onUpdate Function is called on rendering posts elements */ function renderPaginatedPosts( action, $itemsContainer, $showMore, currentPage, perPage, additionalParams = {}, onUpdate = null ) { paginatePosts({ action: action, current_page: currentPage, per_page: perPage }, function (html, totalPages) { $itemsContainer.html(html); if (totalPages > 1) { $showMore.find('.pagination').html(renderPaginationNavItems( totalPages, currentPage, $showMore.find('.next-locale').text(), $showMore.find('.prev-locale').text() )); } else { // Remove pagination for onchange events $showMore.find('.pagination').children().remove(); } if (onUpdate) { onUpdate(); } }, function (e) { console.log(e); }, additionalParams ); } /** * Render pagination navigation buttons * * @param totalPages * @param currentPage * @param nextLocale * @param prevLocale * @returns {string} */ function renderPaginationNavItems(totalPages, currentPage, nextLocale, prevLocale) { currentPage = parseInt(currentPage, 10); totalPages = parseInt(totalPages, 10); // Previous btn let disabled = (currentPage === 1) ? 'disabled' : ''; let tabindex = (currentPage === 1) ? 'tabindex="-1"' : ''; let prevPage = (currentPage === 1) ? 1 : currentPage - 1; let prev = '
  • ' + '' + prevLocale + '' + '
  • '; if (currentPage > 1 && totalPages > 5) { // Display .. and 1st page when pagination is too long => 1..12,13,14,15,16 prev += '
  • ' + '1' + '
  • ' + '
  • ...
  • '; } let items = ''; let index = currentPage; if (currentPage > (totalPages - 4) && totalPages > 5) { // Fix last 5 btns => 1..15,16,17,18,19 index = totalPages - 4; } else if (totalPages <= 5) { index = 1; } for (; index <= (currentPage + 4) && index <= totalPages; index++) { let page = (index === currentPage) ? index + ' (current)' : index; let active = (index === currentPage) ? 'active' : ''; items += '
  • ' + '' + page + '' + '
  • '; } let next = ''; if (currentPage < (totalPages - 4)) { // Display .. and last page when pagination is too long => 1,2,3,4,5..20 next += '
  • ...
  • ' + '
  • ' + '' + totalPages + '' + '
  • '; } // Next btn disabled = (currentPage === totalPages) ? 'disabled' : ''; tabindex = (currentPage === totalPages) ? 'tabindex="-1"' : ''; next += '
  • ' + '' + nextLocale + '' + '
  • '; return prev + items + next; } /** * Checks whether a string is a url or not * * @param chkStr */ function isUrl(chkStr){ return chkStr && ( chkStr.startsWith('http://') || chkStr.startsWith('https://')) } /** * Append forward slash to URI to allow sending query parameters via JQuery.get * * @param uri String * @return String */ function slashIt(uri) { if (! uri.endsWith('/')) { uri += '/'; } return uri; } /** * Bind datepicker to elements with class 'datepicker-field' */ function bindDatepicker(){ if ( $('.datepicker-field').length>0 ) { $('.datepicker-field').datepicker(); } } /** * Move to the next step using the Jquery steps wizard plugin * * @param {object} $container * @param {Integer} prev_step * @param {Integer} next_step */ function wizard_next_step( $container, prev_step, next_step ) { for (let i = prev_step; i < next_step; i++) { $container.find('.L-step-' + i).hide(); $container.find('.step-' + i).addClass('done').removeClass('doing'); } $container.find('.L-step-' + next_step).show(); $container.find('.step-' + next_step).addClass('doing'); $container.find('.modal-content').scrollTop(0); } /** * Save user notification token * * @param token String * @param csrf String */ function saveNotificationToken(token, csrf) { $.post('/notifications/token', {token: token, _tr_nonce_form: csrf}); } /** * Displays errors for form fields * * @param $errors object Where the key is the field name and the value is the error * @return void */ function show_fields_errors(errors){ for (let key in errors) { $('.L-' + key + '_err').text(errors[key]) .show(); } } /** * Handles the design classes for the form fields * @return void */ function handleFormError(){ $('input, select, textarea').removeClass('input-error'); $('div.error:visible, div.text-danger:visible, small.error:visible, small.text-danger:visible').not(':empty').closest('.form-group').find('input, select, textarea') .addClass('input-error'); $('.input-error').on('change input', '', function(){ $(this).removeClass('input-error'); $(this).closest('.form-group').find('div.error, div.text-danger, small.error, small.text-danger').hide(); }); }