<commit_before>import isEmpty from 'lodash/isEmpty';
import debounce from 'lodash/debounce';
import FirebasePersistor from '../persistors/FirebasePersistor';
import appFirebase from '../services/appFirebase';
import validations from '../validations';

function getCurrentPersistor(state) {
  const currentUser = state.user.toJS();
  if (currentUser.authenticated) {
    return new FirebasePersistor(currentUser);
  }
  return null;
}

function generateProjectKey() {
  const date = new Date();
  return (date.getTime() * 1000 + date.getMilliseconds()).toString();
}

function getCurrentProject(state) {
  const projectKey = state.currentProject.get('projectKey');
  if (projectKey) {
    return state.projects.get(projectKey);
  }

  return null;
}

function saveCurrentProject(state) {
  const currentProject = getCurrentProject(state);
  const persistor = getCurrentPersistor(state);

  if (persistor && currentProject && currentProject.get('updatedAt')) {
    persistor.saveCurrentProject(currentProject.toJS());
    return true;
  }

  return false;
}

function showErrorsAfterDebounce() {
  return debounce((dispatch) => {
    dispatch({type: 'ERROR_DEBOUNCE_FINISHED'});
  }, 1000);
}

function validateSource(language, source, enabledLibraries) {
  return (dispatch) => {
    dispatch({
      type: 'VALIDATING_SOURCE',
      payload: {
        language,
      },
    });

    const validate = validations[language];
    validate(source, enabledLibraries.toJS()).then((errors) => {
      dispatch({
        type: 'VALIDATED_SOURCE',
        payload: {
          language,
          errors,
        },
      });

      if (!isEmpty(errors)) {
        dispatch(showErrorsAfterDebounce());
      }
    });
  };
}

function validateAllSources(project) {
  return (dispatch) => {
    const enabledLibraries = project.get('enabledLibraries');
    project.get('sources').forEach((source, language) => {
      dispatch(validateSource(language, source, enabledLibraries));
    });
  };
}

function createProject() {
  return (dispatch) => {
    dispatch({
      type: 'PROJECT_CREATED',
      payload: {
        projectKey: generateProjectKey(),
      },
    });
  };
}

function loadCurrentProjectFromStorage() {
  return (dispatch, getState) => {
    const persistor = getCurrentPersistor(getState());
    if (persistor === null) {
      dispatch(createProject());
      return;
    }

    persistor.getCurrentProjectKey().then((projectKey) => {
      if (projectKey) {
        persistor.load(projectKey).then((project) => {
          dispatch({
            type: 'CURRENT_PROJECT_LOADED_FROM_STORAGE',
            payload: {project},
          });

          dispatch(validateAllSources(getCurrentProject(getState())));
        });
      } else {
        dispatch(createProject());
      }
    });
  };
}

function updateProjectSource(projectKey, language, newValue) {
  return (dispatch, getState) => {
    dispatch({
      type: 'PROJECT_SOURCE_EDITED',
      meta: {timestamp: Date.now()},
      payload: {
        projectKey,
        language,
        newValue,
      },
    });

    const state = getState();
    saveCurrentProject(state);

    const currentProject = getCurrentProject(state);
    dispatch(validateSource(
      language,
      newValue,
      currentProject.get('enabledLibraries')
    ));
  };
}

function changeCurrentProject(projectKey) {
  return (dispatch, getState) => {
    dispatch({
      type: 'CURRENT_PROJECT_CHANGED',
      payload: {projectKey},
    });

    const state = getState();
    saveCurrentProject(state);
    dispatch(validateAllSources(getCurrentProject(state)));
  };
}

function toggleLibrary(projectKey, libraryKey) {
  return (dispatch, getState) => {
    dispatch({
      type: 'PROJECT_LIBRARY_TOGGLED',
      meta: {timestamp: Date.now()},
      payload: {
        projectKey,
        libraryKey,
      },
    });

    const state = getState();
    dispatch(validateAllSources(getCurrentProject(state)));
    saveCurrentProject(state);
  };
}

function loadAllProjects() {
  return (dispatch, getState) => {
    const persistor = getCurrentPersistor(getState());
    if (persistor === null) {
      return;
    }

    persistor.all().then((projects) => {
      projects.forEach((project) => {
        dispatch({
          type: 'PROJECT_LOADED_FROM_STORAGE',
          payload: {project},
        });
      });
    });
  };
}

function addRuntimeError(error) {
  return {
    type: 'RUNTIME_ERROR_ADDED',
    payload: {error},
  };
}

function clearRuntimeErrors() {
  return {
    type: 'RUNTIME_ERRORS_CLEARED',
  };
}

function resetWorkspace() {
  return (dispatch) => {
    dispatch({
      type: 'RESET_WORKSPACE',
      payload: {projectKey: generateProjectKey()},
    });
  };
}

function logIn(authData) {
  return (dispatch, getState) => {
    dispatch({type: 'USER_AUTHENTICATED', payload: authData});

    if (!saveCurrentProject(getState())) {
      dispatch(loadCurrentProjectFromStorage());
    }

    dispatch(loadAllProjects());
  };
}

function logOut() {
  return (dispatch) => {
    dispatch({type: 'USER_LOGGED_OUT'});
    dispatch(resetWorkspace());
  };
}

function listenForAuth() {
  return (dispatch) => {
    appFirebase.onAuth((authData) => {
      if (authData === null) {
        dispatch(logOut());
      } else {
        dispatch(logIn(authData));
      }
    });
  };
}

export {
  createProject,
  changeCurrentProject,
  loadCurrentProjectFromStorage,
  loadAllProjects,
  updateProjectSource,
  toggleLibrary,
  addRuntimeError,
  clearRuntimeErrors,
  listenForAuth,
};
<commit_msg>If there is no current project in storage, only create one if needed<commit_after>import isEmpty from 'lodash/isEmpty';
import debounce from 'lodash/debounce';
import FirebasePersistor from '../persistors/FirebasePersistor';
import appFirebase from '../services/appFirebase';
import validations from '../validations';

function getCurrentPersistor(state) {
  const currentUser = state.user.toJS();
  if (currentUser.authenticated) {
    return new FirebasePersistor(currentUser);
  }
  return null;
}

function generateProjectKey() {
  const date = new Date();
  return (date.getTime() * 1000 + date.getMilliseconds()).toString();
}

function getCurrentProject(state) {
  const projectKey = state.currentProject.get('projectKey');
  if (projectKey) {
    return state.projects.get(projectKey);
  }

  return null;
}

function saveCurrentProject(state) {
  const currentProject = getCurrentProject(state);
  const persistor = getCurrentPersistor(state);

  if (persistor && currentProject && currentProject.get('updatedAt')) {
    persistor.saveCurrentProject(currentProject.toJS());
    return true;
  }

  return false;
}

function showErrorsAfterDebounce() {
  return debounce((dispatch) => {
    dispatch({type: 'ERROR_DEBOUNCE_FINISHED'});
  }, 1000);
}

function validateSource(language, source, enabledLibraries) {
  return (dispatch) => {
    dispatch({
      type: 'VALIDATING_SOURCE',
      payload: {
        language,
      },
    });

    const validate = validations[language];
    validate(source, enabledLibraries.toJS()).then((errors) => {
      dispatch({
        type: 'VALIDATED_SOURCE',
        payload: {
          language,
          errors,
        },
      });

      if (!isEmpty(errors)) {
        dispatch(showErrorsAfterDebounce());
      }
    });
  };
}

function validateAllSources(project) {
  return (dispatch) => {
    const enabledLibraries = project.get('enabledLibraries');
    project.get('sources').forEach((source, language) => {
      dispatch(validateSource(language, source, enabledLibraries));
    });
  };
}

function createProject() {
  return (dispatch) => {
    dispatch({
      type: 'PROJECT_CREATED',
      payload: {
        projectKey: generateProjectKey(),
      },
    });
  };
}

function ensureProject() {
  return (dispatch, getState) => {
    if (getCurrentProject(getState()) === null) {
      dispatch(createProject());
    }
  }
}

function loadCurrentProjectFromStorage() {
  return (dispatch, getState) => {
    const persistor = getCurrentPersistor(getState());
    if (persistor === null) {
      dispatch(createProject());
      return;
    }

    persistor.getCurrentProjectKey().then((projectKey) => {
      if (projectKey) {
        persistor.load(projectKey).then((project) => {
          dispatch({
            type: 'CURRENT_PROJECT_LOADED_FROM_STORAGE',
            payload: {project},
          });

          dispatch(validateAllSources(getCurrentProject(getState())));
        });
      } else {
        dispatch(ensureProject());
      }
    });
  };
}

function updateProjectSource(projectKey, language, newValue) {
  return (dispatch, getState) => {
    dispatch({
      type: 'PROJECT_SOURCE_EDITED',
      meta: {timestamp: Date.now()},
      payload: {
        projectKey,
        language,
        newValue,
      },
    });

    const state = getState();
    saveCurrentProject(state);

    const currentProject = getCurrentProject(state);
    dispatch(validateSource(
      language,
      newValue,
      currentProject.get('enabledLibraries')
    ));
  };
}

function changeCurrentProject(projectKey) {
  return (dispatch, getState) => {
    dispatch({
      type: 'CURRENT_PROJECT_CHANGED',
      payload: {projectKey},
    });

    const state = getState();
    saveCurrentProject(state);
    dispatch(validateAllSources(getCurrentProject(state)));
  };
}

function toggleLibrary(projectKey, libraryKey) {
  return (dispatch, getState) => {
    dispatch({
      type: 'PROJECT_LIBRARY_TOGGLED',
      meta: {timestamp: Date.now()},
      payload: {
        projectKey,
        libraryKey,
      },
    });

    const state = getState();
    dispatch(validateAllSources(getCurrentProject(state)));
    saveCurrentProject(state);
  };
}

function loadAllProjects() {
  return (dispatch, getState) => {
    const persistor = getCurrentPersistor(getState());
    if (persistor === null) {
      return;
    }

    persistor.all().then((projects) => {
      projects.forEach((project) => {
        dispatch({
          type: 'PROJECT_LOADED_FROM_STORAGE',
          payload: {project},
        });
      });
    });
  };
}

function addRuntimeError(error) {
  return {
    type: 'RUNTIME_ERROR_ADDED',
    payload: {error},
  };
}

function clearRuntimeErrors() {
  return {
    type: 'RUNTIME_ERRORS_CLEARED',
  };
}

function resetWorkspace() {
  return (dispatch) => {
    dispatch({
      type: 'RESET_WORKSPACE',
      payload: {projectKey: generateProjectKey()},
    });
  };
}

function logIn(authData) {
  return (dispatch, getState) => {
    dispatch({type: 'USER_AUTHENTICATED', payload: authData});

    if (!saveCurrentProject(getState())) {
      dispatch(loadCurrentProjectFromStorage());
    }

    dispatch(loadAllProjects());
  };
}

function logOut() {
  return (dispatch) => {
    dispatch({type: 'USER_LOGGED_OUT'});
    dispatch(resetWorkspace());
  };
}

function listenForAuth() {
  return (dispatch) => {
    appFirebase.onAuth((authData) => {
      if (authData === null) {
        dispatch(logOut());
      } else {
        dispatch(logIn(authData));
      }
    });
  };
}

export {
  createProject,
  changeCurrentProject,
  loadCurrentProjectFromStorage,
  loadAllProjects,
  updateProjectSource,
  toggleLibrary,
  addRuntimeError,
  clearRuntimeErrors,
  listenForAuth,
};
<|endoftext|>


<commit_before>import axios from 'axios'

export const REGISTER_USER = 'REGISTER_USER'
export const LOGIN = 'LOGIN'
export const SEARCH_BOOKS = 'SEARCH_BOOKS'
export const ADD_TO_WISHLIST = 'ADD_TO_WISHLIST'
export const ROOT_URL = 'http://localhost:3000'

export function registerUser(user) {
	const url = `${ROOT_URL}/register`
	const request = axios.post(url, user)

	return{
		type: REGISTER_USER,
		payload: request
	}
}

export function login(user) {
	const url = `${ROOT_URL}/login`
	const request = axios.post(url, user)

	return{
		type: LOGIN,
		payload: request
	}
}

export function searchBooks(searchTerm) {
	const url = `https://www.googleapis.com/books/v1/volumes?q=${searchTerm}&maxResults=20`
	const request = axios.get(url)

	return {
		type: SEARCH_BOOKS,
		payload: request
	}
}

export function addToWishlist(bookId) {
	const url = `${ROOT_URL}/api/addToWishlist`
	const request = axios.post(url, {bookId})

	return {
		type: ADD_TO_WISHLIST,
		payload: request
	}
}<commit_msg>added get wishlist action creator to actions index<commit_after>import axios from 'axios'

export const REGISTER_USER = 'REGISTER_USER'
export const LOGIN = 'LOGIN'
export const SEARCH_BOOKS = 'SEARCH_BOOKS'
export const ADD_TO_WISHLIST = 'ADD_TO_WISHLIST'
export const GET_WISHLIST = 'GET_WISHLIST'

export const ROOT_URL = 'http://localhost:3000'

export function registerUser(user) {
	const url = `${ROOT_URL}/register`
	const request = axios.post(url, user)

	return{
		type: REGISTER_USER,
		payload: request
	}
}

export function login(user) {
	const url = `${ROOT_URL}/login`
	const request = axios.post(url, user)

	return{
		type: LOGIN,
		payload: request
	}
}

export function searchBooks(searchTerm) {
	const url = `https://www.googleapis.com/books/v1/volumes?q=${searchTerm}&maxResults=20`
	const request = axios.get(url)

	return {
		type: SEARCH_BOOKS,
		payload: request
	}
}

export function addToWishlist(bookId) {
	const url = `${ROOT_URL}/api/addToWishlist`
	const request = axios.post(url, {bookId})

	return {
		type: ADD_TO_WISHLIST,
		payload: request
	}
}

export function getWishlist() {
	const url = `${ROOT_URL}/api/getWishlist`
	const request = axios.get(url)

	return {
		type: GET_WISHLIST,
		payload: request
	}
}<|endoftext|>


<commit_before>var OjsArticleSubmission = {
    submissionId: null,
    step: null,
    languages: [],
    activatedSteps: {"step0": true, "step1": false, "step2": false, "step3": false, "step4": false},
    showResumeNote: function () {

        var html = '' + this.submissionId + '';
        $("#resumeNote").html(html);
    },
    loadStepTemplate: function (step) {
        if (!this.activatedSteps["step" + step]) {
            $("#step" + step).append(Mustache.render($("#step" + step + "_tpl").html()));
            this.activatedSteps["step" + step] = true;
        }
    },
    backTo: function (step) {
        this.configureProgressBar(step);
        this.hideAllSteps();
        this.configureProgressBar(step);
        this.showStep(step);
    },
    configureProgressBar: function (step) {
        $("ul.submission-progress li").removeClass("active");
        $("ul.submission-progress li#submission-progress-step" + step).addClass("active");
    },
    hideAllSteps: function () {
        $(".step").addClass("hide", 200, "easeInBack");
    },
    showStep: function (step) {
        $("#step" + step + "-container").removeClass("hide", 200, "easeInBack");
        history.pushState({}, "Article Submission", "/author/article/submit/resume/" + $("input[name=submissionId]").val());
        window.location.hash = step;
        this.step = step;
        this.showResumeNote();
    },
    hideStep: function (step) {
        $("#step" + step + "-container").slideUp("fast", 200, "easeInBack");
    },
    addAuthorForm: function (params) {
        $("#step2").append(Mustache.render($("#step2_tpl").html(), params));
        OjsArticleSubmission.setupUi();
        function formatResult(item) {
            return item.name;
        }
        function formatSelection(item) {
            return '' + item.name + '';
        }
        $(".select2-institution-search-element").select2({
            multiple: false,
            //Allow manually entered text in drop down.
            createSearchChoice: function (term, data) {
                if ($(data).filter(function () {
                    return this.text.localeCompare(term) === 0;
                }).length === 0) {
                    return {id: term, text: term};
                }
            },
            ajax: {
                url: '/api/public/search/institution',
                dataType: 'json',
                type: "GET",
                delay: 300,
                data: function (params) {
                    return {
                        q: '(.*)'+params+'(.*)'
                    };
                },
                results: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {
                                text: item.name,
                                slug: item.name,
                                id: item.id
                            };
                        })
                    };
                },
                cache: true
            },
//            escapeMarkup: function (markup) {
//                return markup;
//            }, // let our custom formatter work
            minimumInputLength: 1
//            templateResult: formatResult,
//            templateSelection: formatSelection

        });
    },
    addFileForm: function (params) {
        $("#step4").append(Mustache.render($("#step4_tpl").html(), params));
        this.setupUi();
    },
    removeAuthor: function ($el) {
        $el.parents(".author-item").first().remove();
    },
    step0: function (actionUrl) {
        var form = $("#step0-container form").serialize();
        var status = OjsArticleSubmission.licenceCheck();
        if (status === false) {
            return;
        }
        OjsCommon.waitModal();
        $.post(actionUrl, form, function (resp) {
            if (resp.submissionId) {
                OjsArticleSubmission.submissionId = resp.submissionId;
                $("input[name=submissionId]").attr('value', resp.submissionId);
                OjsArticleSubmission.hideAllSteps();
                OjsArticleSubmission.prepareStep.step1();
                OjsCommon.hideallModals();
            } else {
                OjsCommon.errorModal("Error occured. Check your data and please try again.");
            }
        });
    },
    licenceCheck: function () {
        var checkboxes = $("#step0-container input[type=checkbox]");
        var status = true;
        checkboxes.each(function () {
            if ($(this).is(':checked') === false) {
                status = false;
                OjsCommon.errorModal("Please check all licence field!");
            }
        });
        return status;
    },
    step1: function (actionUrl) {
        forms = $("#step1 form");
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();
        // prepare post params
        articleParams = false;
        translationParams = [];
        forms.each(function () {
            data = $(this).serializeObject();
            locale = $(this).attr('id');
            data.locale = locale;
            postUrl = actionUrl.replace('locale', locale);
            tmpParam = {"data": data, "postUrl": postUrl};
            if ($primaryLang === locale) {
                // article main data
                tmpParam.data.journalId = $("input[name=journalId]").val();
                tmpParam.data.primaryLanguage = $("select[name=primaryLanguage] option:selected").val();
                articleParams = tmpParam;
            } else {
                translationParams.push(tmpParam);
            }
        });

        if (!articleParams) {
            OjsCommon.errorModal("Please select and fill metadata for article's language.");
            return;
        }

        OjsCommon.waitModal();
        if (translationParams) {
            articleParams.data.translations = JSON.stringify(translationParams);
        }
        articleParams.data.submissionId = $("input[name=submissionId]").val();
        articleParams.data.section = $("select[name=section]").val();

        if(!$("#section").val()){
            OjsCommon.errorModal("Please select a section for article.");
            return;
        }
        articleParams.data.section = $("#section").val();
        $.post(articleParams.postUrl, articleParams.data, function (response) {
            OjsCommon.hideallModals();
            if (response.submissionId) {
                OjsArticleSubmission.submissionId = response.submissionId;
                $("input[name=submissionId]").attr('value', response.submissionId);
                OjsArticleSubmission.hideAllSteps();
                OjsArticleSubmission.prepareStep.step2();
            } else {
                OjsCommon.errorModal("Error occured. Check your data and please try again.");
            }
        }).fail(function(){
            OjsCommon.errorModal("Something went wrong while sumitting. Please try again.");
        });
    },
    step2: function (actionUrl) {
        forms = $(".author-item");
        if (forms.length === 0) {
            OjsCommon.errorModal("Add at least one author.");
            return false;
        }
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();
        // prepare post params
        authorParams = false;
        var dataArray = [];
        forms.each(function () {
            dataArray.push($("form", this).serializeObject());
        });
        OjsCommon.waitModal();
        $.post(actionUrl, {"authorsData": JSON.stringify(dataArray), "submissionId": OjsArticleSubmission.submissionId}, function (response) {
            OjsCommon.hideallModals();
            OjsArticleSubmission.hideAllSteps();
            OjsArticleSubmission.prepareStep.step3();
        }).error(function () {
            OjsCommon.errorModal("Something is wrong. Check your data and try again.");
        });
    },
    step3: function (actionUrl) {
        forms = $("form", $(".cite-item"));
        if (forms.length > 0) {
            $primaryLang = $("select[name=primaryLanguage] option:selected").val();
            // prepare post params
            var dataArray = [];
            forms.each(function () {
                dataArray.push($(this).serializeObject());
            });
            OjsCommon.waitModal();
            $.post(actionUrl, {"citeData": JSON.stringify(dataArray), "submissionId": OjsArticleSubmission.submissionId}, function (response) {
                OjsCommon.hideallModals();
                OjsArticleSubmission.hideAllSteps();
                OjsArticleSubmission.prepareStep.step4();
            }).error(function () {
                OjsCommon.errorModal("Something is wrong. Check your data and try again.");
            });
        } else {
            OjsCommon.hideallModals();
            OjsArticleSubmission.hideAllSteps();
            OjsArticleSubmission.prepareStep.step4();
        }
    },
    step4: function (actionUrl) {
        forms = $("form.file-item");
        if (forms.length > 0) {
            $primaryLang = $("select[name=primaryLanguage] option:selected").val();
            // prepare post params
            var dataArray = [];
            forms.each(function () {
                dataArray.push($(this).serializeObject());
            });
            OjsCommon.waitModal();
            $.post(actionUrl, {"filesData": JSON.stringify(dataArray), "submissionId": OjsArticleSubmission.submissionId}, function (response) {
                OjsArticleSubmission.hideAllSteps();
                if (response.redirect) {
                    window.onbeforeunload = null;
                    window.location.href = response.redirect;
                } else {
                    OjsCommon.errorModal("Something is wrong. Check your data and try again.");
                }
            }).error(function () {
                OjsCommon.errorModal("Something is wrong. Check your data and try again.");
            });
        }
    },
    submit: function () {
        var licenceCheck = OjsArticleSubmission.licenceCheck();
        var check = confirm("Are you sure to submit your article?");
        if (check === true && licenceCheck === true) {
            OjsCommon.waitModal();
            window.location.href = "/";
        } else {
            return false;
        }
    },
    /**
     * prepare and show steps
     */
    prepareStep: {
        step0: function () {
            OjsArticleSubmission.configureProgressBar(0);
            OjsArticleSubmission.showStep(0, true);
        },
        step1: function () {
            OjsCommon.scrollTop();
            if ($("#step1").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(1);
                OjsArticleSubmission.loadStepTemplate(1);
            }
            OjsArticleSubmission.showStep(1);

        },
        step2: function () {
            OjsCommon.scrollTop();
            if ($("#step2").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(2);
            }
            OjsArticleSubmission.addAuthorForm();
            OjsArticleSubmission.showStep(2);
            OjsArticleSubmission.setupUi();
        },
        step3: function () {
            OjsCommon.scrollTop();
            if ($("#step3").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(3);
                OjsArticleSubmission.loadStepTemplate(3);
            }
            OjsArticleSubmission.showStep(3);
        },
        step4: function () {
            OjsCommon.scrollTop();
            if ($("#step4").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(4);
                OjsArticleSubmission.loadStepTemplate(4);
            }
            OjsArticleSubmission.showStep(4);
            OjsArticleSubmission.setupUi();
        }
    },
    bindFileUploader: function () {
        $('.article_file_upload').fileupload({});
        $('.article_file_upload').bind('fileuploadsend', function (e, data) {
            $uploadIndicator = $('.upload_progress', $(this).parent().parent());
            $uploadIndicator.show();
            $uploadIndicator.html("Uploading...");
        }).bind('fileuploaddone', function (e, data) {
            $('.upload_progress', $(this).parent().parent()).html("Done.");
            $obj = JSON.parse(data.result);
            $('.previewLink', $(this).parent().parent()).attr('href', '/uploads/journalfiles/' + $obj.files.path + $obj.files.name).removeClass('hide');
            $('.filename', $(this).parent()).attr('value', $obj.files.name);
            $('input[name="article_file_mime_type"]', $(this).parent()).attr('value', $obj.files.size);
            $('input[name="article_file_size"]', $(this).parent()).attr('value', $obj.files.mimeType);
        });
    },
    setupUi: function () {
        this.bindFileUploader();
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();
        $('input[name=keywords], input[name=subjects]').tagsinput({
            tagClass: 'label label-info'
        });
        $('#changeSelectedJournal').on("select2-selecting", function (e) {
            window.location.href = "" + e.val;
        });
        $('.select2-element').select2({placeholder: '', allowClear: true, closeOnSelect: false});
        $("div.editor").wysihtml5({
            toolbar: {
                "font-styles": false,
                "emphasis": true,
                "lists": false,
                "html": false,
                "link": true,
                "image": false,
                "color": false,
                "blockquote": true}
        });
    },
    step1ScrollToLangPanel: function (lang) {
        $('html, body').animate({
            scrollTop: $("#lang_" + lang).offset().top
        }, 500);
    }
};

$(document).ready(function () {
    OjsArticleSubmission.setupUi();

});
<commit_msg>inst. public search api action modified<commit_after>var OjsArticleSubmission = {
    submissionId: null,
    step: null,
    languages: [],
    activatedSteps: {"step0": true, "step1": false, "step2": false, "step3": false, "step4": false},
    showResumeNote: function () {

        var html = '' + this.submissionId + '';
        $("#resumeNote").html(html);
    },
    loadStepTemplate: function (step) {
        if (!this.activatedSteps["step" + step]) {
            $("#step" + step).append(Mustache.render($("#step" + step + "_tpl").html()));
            this.activatedSteps["step" + step] = true;
        }
    },
    backTo: function (step) {
        this.configureProgressBar(step);
        this.hideAllSteps();
        this.configureProgressBar(step);
        this.showStep(step);
    },
    configureProgressBar: function (step) {
        $("ul.submission-progress li").removeClass("active");
        $("ul.submission-progress li#submission-progress-step" + step).addClass("active");
    },
    hideAllSteps: function () {
        $(".step").addClass("hide", 200, "easeInBack");
    },
    showStep: function (step) {
        $("#step" + step + "-container").removeClass("hide", 200, "easeInBack");
        history.pushState({}, "Article Submission", "/author/article/submit/resume/" + $("input[name=submissionId]").val());
        window.location.hash = step;
        this.step = step;
        this.showResumeNote();
    },
    hideStep: function (step) {
        $("#step" + step + "-container").slideUp("fast", 200, "easeInBack");
    },
    addAuthorForm: function (params) {
        $("#step2").append(Mustache.render($("#step2_tpl").html(), params));
        OjsArticleSubmission.setupUi();
        function formatResult(item) {
            return item.name;
        }
        function formatSelection(item) {
            return '' + item.name + '';
        }
        $(".select2-institution-search-element").select2({
            multiple: false,
            //Allow manually entered text in drop down.
            createSearchChoice: function (term, data) {
                if ($(data).filter(function () {
                    return this.text.localeCompare(term) === 0;
                }).length === 0) {
                    return {id: term, text: term};
                }
            },
            ajax: {
                url: '/api/public/search/institution',
                dataType: 'json',
                type: "GET",
                delay: 300,
                data: function (params) {
                    return {
                        q: '(.*)'+params+'(.*)',
                        verified: true
                    };
                },
                results: function (data) {
                    return {
                        results: $.map(data, function (item) {
                            return {
                                text: item.name,
                                slug: item.name,
                                id: item.id
                            };
                        })
                    };
                },
                cache: true
            },
//            escapeMarkup: function (markup) {
//                return markup;
//            }, // let our custom formatter work
            minimumInputLength: 1
//            templateResult: formatResult,
//            templateSelection: formatSelection

        });
    },
    addFileForm: function (params) {
        $("#step4").append(Mustache.render($("#step4_tpl").html(), params));
        this.setupUi();
    },
    removeAuthor: function ($el) {
        $el.parents(".author-item").first().remove();
    },
    step0: function (actionUrl) {
        var form = $("#step0-container form").serialize();
        var status = OjsArticleSubmission.licenceCheck();
        if (status === false) {
            return;
        }
        OjsCommon.waitModal();
        $.post(actionUrl, form, function (resp) {
            if (resp.submissionId) {
                OjsArticleSubmission.submissionId = resp.submissionId;
                $("input[name=submissionId]").attr('value', resp.submissionId);
                OjsArticleSubmission.hideAllSteps();
                OjsArticleSubmission.prepareStep.step1();
                OjsCommon.hideallModals();
            } else {
                OjsCommon.errorModal("Error occured. Check your data and please try again.");
            }
        });
    },
    licenceCheck: function () {
        var checkboxes = $("#step0-container input[type=checkbox]");
        var status = true;
        checkboxes.each(function () {
            if ($(this).is(':checked') === false) {
                status = false;
                OjsCommon.errorModal("Please check all licence field!");
            }
        });
        return status;
    },
    step1: function (actionUrl) {
        forms = $("#step1 form");
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();
        // prepare post params
        articleParams = false;
        translationParams = [];
        forms.each(function () {
            data = $(this).serializeObject();
            locale = $(this).attr('id');
            data.locale = locale;
            postUrl = actionUrl.replace('locale', locale);
            tmpParam = {"data": data, "postUrl": postUrl};
            if ($primaryLang === locale) {
                // article main data
                tmpParam.data.journalId = $("input[name=journalId]").val();
                tmpParam.data.primaryLanguage = $("select[name=primaryLanguage] option:selected").val();
                articleParams = tmpParam;
            } else {
                translationParams.push(tmpParam);
            }
        });

        if (!articleParams) {
            OjsCommon.errorModal("Please select and fill metadata for article's language.");
            return;
        }

        OjsCommon.waitModal();
        if (translationParams) {
            articleParams.data.translations = JSON.stringify(translationParams);
        }
        articleParams.data.submissionId = $("input[name=submissionId]").val();
        articleParams.data.section = $("select[name=section]").val();

        if(!$("#section").val()){
            OjsCommon.errorModal("Please select a section for article.");
            return;
        }
        articleParams.data.section = $("#section").val();
        $.post(articleParams.postUrl, articleParams.data, function (response) {
            OjsCommon.hideallModals();
            if (response.submissionId) {
                OjsArticleSubmission.submissionId = response.submissionId;
                $("input[name=submissionId]").attr('value', response.submissionId);
                OjsArticleSubmission.hideAllSteps();
                OjsArticleSubmission.prepareStep.step2();
            } else {
                OjsCommon.errorModal("Error occured. Check your data and please try again.");
            }
        }).fail(function(){
            OjsCommon.errorModal("Something went wrong while sumitting. Please try again.");
        });
    },
    step2: function (actionUrl) {
        forms = $(".author-item");
        if (forms.length === 0) {
            OjsCommon.errorModal("Add at least one author.");
            return false;
        }
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();
        // prepare post params
        authorParams = false;
        var dataArray = [];
        forms.each(function () {
            dataArray.push($("form", this).serializeObject());
        });
        OjsCommon.waitModal();
        $.post(actionUrl, {"authorsData": JSON.stringify(dataArray), "submissionId": OjsArticleSubmission.submissionId}, function (response) {
            OjsCommon.hideallModals();
            OjsArticleSubmission.hideAllSteps();
            OjsArticleSubmission.prepareStep.step3();
        }).error(function () {
            OjsCommon.errorModal("Something is wrong. Check your data and try again.");
        });
    },
    step3: function (actionUrl) {
        forms = $("form", $(".cite-item"));
        if (forms.length > 0) {
            $primaryLang = $("select[name=primaryLanguage] option:selected").val();
            // prepare post params
            var dataArray = [];
            forms.each(function () {
                dataArray.push($(this).serializeObject());
            });
            OjsCommon.waitModal();
            $.post(actionUrl, {"citeData": JSON.stringify(dataArray), "submissionId": OjsArticleSubmission.submissionId}, function (response) {
                OjsCommon.hideallModals();
                OjsArticleSubmission.hideAllSteps();
                OjsArticleSubmission.prepareStep.step4();
            }).error(function () {
                OjsCommon.errorModal("Something is wrong. Check your data and try again.");
            });
        } else {
            OjsCommon.hideallModals();
            OjsArticleSubmission.hideAllSteps();
            OjsArticleSubmission.prepareStep.step4();
        }
    },
    step4: function (actionUrl) {
        forms = $("form.file-item");
        if (forms.length > 0) {
            $primaryLang = $("select[name=primaryLanguage] option:selected").val();
            // prepare post params
            var dataArray = [];
            forms.each(function () {
                dataArray.push($(this).serializeObject());
            });
            OjsCommon.waitModal();
            $.post(actionUrl, {"filesData": JSON.stringify(dataArray), "submissionId": OjsArticleSubmission.submissionId}, function (response) {
                OjsArticleSubmission.hideAllSteps();
                if (response.redirect) {
                    window.onbeforeunload = null;
                    window.location.href = response.redirect;
                } else {
                    OjsCommon.errorModal("Something is wrong. Check your data and try again.");
                }
            }).error(function () {
                OjsCommon.errorModal("Something is wrong. Check your data and try again.");
            });
        }
    },
    submit: function () {
        var licenceCheck = OjsArticleSubmission.licenceCheck();
        var check = confirm("Are you sure to submit your article?");
        if (check === true && licenceCheck === true) {
            OjsCommon.waitModal();
            window.location.href = "/";
        } else {
            return false;
        }
    },
    /**
     * prepare and show steps
     */
    prepareStep: {
        step0: function () {
            OjsArticleSubmission.configureProgressBar(0);
            OjsArticleSubmission.showStep(0, true);
        },
        step1: function () {
            OjsCommon.scrollTop();
            if ($("#step1").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(1);
                OjsArticleSubmission.loadStepTemplate(1);
            }
            OjsArticleSubmission.showStep(1);

        },
        step2: function () {
            OjsCommon.scrollTop();
            if ($("#step2").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(2);
            }
            OjsArticleSubmission.addAuthorForm();
            OjsArticleSubmission.showStep(2);
            OjsArticleSubmission.setupUi();
        },
        step3: function () {
            OjsCommon.scrollTop();
            if ($("#step3").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(3);
                OjsArticleSubmission.loadStepTemplate(3);
            }
            OjsArticleSubmission.showStep(3);
        },
        step4: function () {
            OjsCommon.scrollTop();
            if ($("#step4").html().length > 0) {
                OjsArticleSubmission.configureProgressBar(4);
                OjsArticleSubmission.loadStepTemplate(4);
            }
            OjsArticleSubmission.showStep(4);
            OjsArticleSubmission.setupUi();
        }
    },
    bindFileUploader: function () {
        $('.article_file_upload').fileupload({});
        $('.article_file_upload').bind('fileuploadsend', function (e, data) {
            $uploadIndicator = $('.upload_progress', $(this).parent().parent());
            $uploadIndicator.show();
            $uploadIndicator.html("Uploading...");
        }).bind('fileuploaddone', function (e, data) {
            $('.upload_progress', $(this).parent().parent()).html("Done.");
            $obj = JSON.parse(data.result);
            $('.previewLink', $(this).parent().parent()).attr('href', '/uploads/journalfiles/' + $obj.files.path + $obj.files.name).removeClass('hide');
            $('.filename', $(this).parent()).attr('value', $obj.files.name);
            $('input[name="article_file_mime_type"]', $(this).parent()).attr('value', $obj.files.size);
            $('input[name="article_file_size"]', $(this).parent()).attr('value', $obj.files.mimeType);
        });
    },
    setupUi: function () {
        this.bindFileUploader();
        $primaryLang = $("select[name=primaryLanguage] option:selected").val();
        $('input[name=keywords], input[name=subjects]').tagsinput({
            tagClass: 'label label-info'
        });
        $('#changeSelectedJournal').on("select2-selecting", function (e) {
            window.location.href = "" + e.val;
        });
        $('.select2-element').select2({placeholder: '', allowClear: true, closeOnSelect: false});
        $("div.editor").wysihtml5({
            toolbar: {
                "font-styles": false,
                "emphasis": true,
                "lists": false,
                "html": false,
                "link": true,
                "image": false,
                "color": false,
                "blockquote": true}
        });
    },
    step1ScrollToLangPanel: function (lang) {
        $('html, body').animate({
            scrollTop: $("#lang_" + lang).offset().top
        }, 500);
    }
};

$(document).ready(function () {
    OjsArticleSubmission.setupUi();

});
<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CONTACTS.namespace('CONTACTS.app.getContacts');
CONTACTS.namespace('CONTACTS.app.buildContactList');
CONTACTS.namespace('CONTACTS.app.getContactById');
CONTACTS.namespace('CONTACTS.app.buildContactDetail');
CONTACTS.namespace('CONTACTS.app.restEndpoint');

CONTACTS.app.restEndpoint = 'rest/contacts';

/**
 * It is recommended to bind to this event instead of DOM ready() because this will work regardless of whether
 * the page is loaded directly or if the content is pulled into another page as part of the Ajax navigation system.
 *
 * The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything
 * will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of
 * each page into the DOM as you navigate, and the DOM ready handler only executes for the first page.
 * To execute code whenever a new page is loaded and created, you can bind to the pagecreate event.
 *
 *
 * These functions perform the GET. They display the list, detailed list, and fill in the update form.
 *
 * @author Joshua Wilson
 */
$( document ).on( "pagecreate", function(mainEvent) {
    //Initialize the vars in the beginning so that you will always have access to them.
    var getCurrentTime = CONTACTS.util.getCurrentTime,
        restEndpoint = CONTACTS.app.restEndpoint;

    console.log(getCurrentTime() + " [js/app.js] (document -> pagecreate) - start");

    /*
     * Make sure the Contacts list gets populated but only once.
     *
     * The "pagebeforeshow" event will delay this function until everything is set up.
     *
     * Because of the interesting jQM loading architecture, multiple event triggering is a constant problem.
     * The "e.handled" if statement used here and elsewhere is meant to keep jQM from running this code multiple
     * times for one display.
     */
    $('#contacts-list-page').on( "pagebeforeshow", function(e) {
        if(e.handled !== true) {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-list-page -> pagebeforeshow) - start");

            // Fetches the initial Contact data.
            CONTACTS.app.getContacts();

            e.handled = true;
            console.log(getCurrentTime() + " [js/app.js] (#contacts-list-page -> pagebeforeshow) - end");
        }
    });

    // This is called on 'pagebeforeshow' above and by the CONTACTS.submissions
    // Uses JAX-RS GET to retrieve current contact list.
    CONTACTS.app.getContacts = function () {
        console.log(getCurrentTime() + " [js/app.js] (getContacts) - start");
        var jqxhr = $.ajax({
            url: restEndpoint,
            cache: false,
            type: "GET"
        }).done(function(data, textStatus, jqXHR) {
            console.log(getCurrentTime() + " [js/app.js] (getContacts) - succes on ajax call");
            CONTACTS.app.buildContactList(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.log(getCurrentTime() + " [js/app.js] (getContacts) - error in ajax - " +
                        " - jqXHR = " + jqXHR.status +
                        " - textStatus = " + textStatus +
                        " - errorThrown = " + errorThrown);
        });
        console.log(getCurrentTime() + " [js/app.js] (getContacts) - end");
    };

    // This is called by CONTACTS.app.getContacts.
    // Display contact list on page one.
    CONTACTS.app.buildContactList = function (contacts) {
        console.log(getCurrentTime() + " [js/app.js] (buildContactList) - start");
        var contactList = "",
            contactDetailList = "";

        // The data from the AJAX call is not sorted alphabetically, this will fix that.
        contacts.sort(function(a,b){
              var aName = a.firstName.toLowerCase() + a.lastName.toLowerCase();
              var bName = b.firstName.toLowerCase() + b.lastName.toLowerCase();
              return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

        // Pull the info out of the Data returned from the AJAX request and create the HTML to be placed on the page.
        $.each(contacts, function(index, contact) {
            // Create the HTML for the List only view.
            contactList = contactList.concat(
                "
" +
                    "" + contact.firstName.toString() + " " + contact.lastName.toString() + "" +
                "
");
            // Create the HTML for the Detailed List view.
            contactDetailList = contactDetailList.concat(
                "
" +
                    "" + contact.firstName.toString() + " " + contact.lastName.toString() + "" +
                    "
" +
                        "
" + contact.email.toString() + "
" +
                        "
" + contact.phoneNumber.toString() + "
" +
                        "
" + contact.birthDate.toString() + "
" +
                    "
" +
                 "
");
        });

        // Start with a clean list element otherwise we would have repeats.
        $('#contacts-display-listview').empty();

        // Check if it is already initialized or not, refresh the list in case it is initialized otherwise trigger create.
        if ( $('#contacts-display-listview').hasClass('ui-listview')) {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - hasClass ui-listview) - append.listview - start");
            $('#contacts-display-listview').append(contactList).listview("refresh", true);
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - hasClass ui-listview) - append.listview - end");
        }
        else {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - !hasClass ui-listview) - append.trigger - start");
            $('#contacts-display-listview').append(contactList).trigger('create');
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - !hasClass ui-listview) - append.trigger - end");
        }

        // Start with a clean list element otherwise we would have repeats.
        $('#contacts-display-detail-listview').empty();

        // check if it is already initialized or not, refresh the list in case it is initialized otherwise trigger create
        if ( $('#contacts-display-detail-listview').hasClass('ui-listview')) {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - hasClass ui-listview) - append.listview - start");
            $('#contacts-display-detail-listview').append(contactDetailList).listview("refresh", true);
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - hasClass ui-listview) - append.listview - end");
        }
        else {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - !hasClass ui-listview) - append.trigger - start");
            $('#contacts-display-detail-listview').append(contactDetailList).trigger('create');
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - !hasClass ui-listview) - append.trigger - end");
        }

        // Attach onclick event to each row of the contact list that will open up the contact info to be edited.
        $('.contacts-list-item').on("click", function(event){
            if(event.handled !== true) {
                console.log(getCurrentTime() + " [js/app.js] (.contacts-display-listview -> on click) - start");

                CONTACTS.app.getContactById($(this).attr("id").split("list-contact-ID-").pop());

                event.handled = true;
                console.log(getCurrentTime() + " [js/app.js] (.contacts-display-listview -> on click) - end");
            }
        });

        // Attach onclick event to each row of the contact list detailed page that will open up the contact info to be edited.
        $('li.contacts-detail-list-item').on("click", function(event){
            if(event.handled !== true) {
                console.log(getCurrentTime() + " [js/app.js] (li.contacts-display-listview -> on click) - start");

                CONTACTS.app.getContactById($(this).attr("id").split("detail-contact-ID-").pop());

                // Turn the whole
 into a link.
                $("body").pagecontainer("change", "#contacts-edit-page");

                event.handled = true;
                console.log(getCurrentTime() + " [js/app.js] (li.contacts-display-listview -> on click) - end");
            }
        });

        console.log(getCurrentTime() + " [js/app.js] (buildContactList) - end");
        // Add in a line to visually see when we are done.
        console.log("-----------------------------List Page---------------------------------------");
    };

    // This is called by the on click event list above.
    // Retrieve employee detail based on employee id.
    CONTACTS.app.getContactById = function (contactID) {
        console.log(getCurrentTime() + " [js/app.js] (getContactById) - start");
        console.log(getCurrentTime() + " [js/app.js] (getContactById) - contactID = " + contactID);

        var jqxhr = $.ajax({
            url: restEndpoint + "/" + contactID.toString(),
            cache: false,
            type: "GET"
        }).done(function(data, textStatus, jqXHR) {
            console.log(getCurrentTime() + " [js/app.js] (getContactById) - success on ajax call");
            CONTACTS.app.buildContactDetail(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.log(getCurrentTime() + " [js/app.js] (getContactById) - error in ajax" +
                        " - jqXHR = " + jqXHR.status +
                        " - textStatus = " + textStatus +
                        " - errorThrown = " + errorThrown);
        });
        console.log(getCurrentTime() + " [js/app.js] (getContactById) - end");
    };

    // This is called by CONTACTS.app.getContactById.
    // Display contact detail for editing on the Edit page.
    CONTACTS.app.buildContactDetail = function(contact) {
        console.log(getCurrentTime() + " [js/app.js] (buildContactDetail) - start");

        // Put each field value in the text input on the page.
        $('#contacts-edit-input-firstName').val(contact.firstName);
        $('#contacts-edit-input-lastName').val(contact.lastName);
        $('#contacts-edit-input-tel').val(contact.phoneNumber);
        $('#contacts-edit-input-email').val(contact.email);
        $('#contacts-edit-input-date').val(contact.birthDate);
        $('#contacts-edit-input-id').val(contact.id);

        console.log(getCurrentTime() + " [js/app.js] (buildContactDetail) - end");
        // Add in a line to visually see when we are done.
        console.log("-----------------------------Update Page---------------------------------------");
    };

    console.log(getCurrentTime() + " [js/app.js] (document -> pagecreate) - end");
});

<commit_msg>Removed uses of deprecated jQueryMobile APIs.<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CONTACTS.namespace('CONTACTS.app.getContacts');
CONTACTS.namespace('CONTACTS.app.buildContactList');
CONTACTS.namespace('CONTACTS.app.getContactById');
CONTACTS.namespace('CONTACTS.app.buildContactDetail');
CONTACTS.namespace('CONTACTS.app.restEndpoint');

CONTACTS.app.restEndpoint = 'rest/contacts';

/**
 * It is recommended to bind to this event instead of DOM ready() because this will work regardless of whether
 * the page is loaded directly or if the content is pulled into another page as part of the Ajax navigation system.
 *
 * The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything
 * will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of
 * each page into the DOM as you navigate, and the DOM ready handler only executes for the first page.
 * To execute code whenever a new page is loaded and created, you can bind to the pagecreate event.
 *
 *
 * These functions perform the GET. They display the list, detailed list, and fill in the update form.
 *
 * @author Joshua Wilson
 */
$( document ).on( "pagecreate", function(mainEvent) {
    //Initialize the vars in the beginning so that you will always have access to them.
    var getCurrentTime = CONTACTS.util.getCurrentTime,
        restEndpoint = CONTACTS.app.restEndpoint;

    console.log(getCurrentTime() + " [js/app.js] (document -> pagecreate) - start");

    /*
     * Make sure the Contacts list gets populated but only once.
     *
     * The "pagebeforeshow" event will delay this function until everything is set up.
     *
     * Because of the interesting jQM loading architecture, multiple event triggering is a constant problem.
     * The "e.handled" if statement used here and elsewhere is meant to keep jQM from running this code multiple
     * times for one display.
     */
    $('#contacts-list-page').on( "pagebeforeshow", function(e) {
        if(e.handled !== true) {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-list-page -> pagebeforeshow) - start");

            // Fetches the initial Contact data.
            CONTACTS.app.getContacts();

            e.handled = true;
            console.log(getCurrentTime() + " [js/app.js] (#contacts-list-page -> pagebeforeshow) - end");
        }
    });

    // This is called on 'pagebeforeshow' above and by the CONTACTS.submissions
    // Uses JAX-RS GET to retrieve current contact list.
    CONTACTS.app.getContacts = function () {
        console.log(getCurrentTime() + " [js/app.js] (getContacts) - start");
        var jqxhr = $.ajax({
            url: restEndpoint,
            cache: false,
            type: "GET"
        }).done(function(data, textStatus, jqXHR) {
            console.log(getCurrentTime() + " [js/app.js] (getContacts) - succes on ajax call");
            CONTACTS.app.buildContactList(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.log(getCurrentTime() + " [js/app.js] (getContacts) - error in ajax - " +
                        " - jqXHR = " + jqXHR.status +
                        " - textStatus = " + textStatus +
                        " - errorThrown = " + errorThrown);
        });
        console.log(getCurrentTime() + " [js/app.js] (getContacts) - end");
    };

    // This is called by CONTACTS.app.getContacts.
    // Display contact list on page one.
    CONTACTS.app.buildContactList = function (contacts) {
        console.log(getCurrentTime() + " [js/app.js] (buildContactList) - start");
        var contactList = "",
            contactDetailList = "";

        // The data from the AJAX call is not sorted alphabetically, this will fix that.
        contacts.sort(function(a,b){
              var aName = a.firstName.toLowerCase() + a.lastName.toLowerCase();
              var bName = b.firstName.toLowerCase() + b.lastName.toLowerCase();
              return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

        // Pull the info out of the Data returned from the AJAX request and create the HTML to be placed on the page.
        $.each(contacts, function(index, contact) {
            // Create the HTML for the List only view.
            contactList = contactList.concat(
                "
" +
                    "" + contact.firstName.toString() + " " + contact.lastName.toString() + "" +
                "
");
            // Create the HTML for the Detailed List view.
            contactDetailList = contactDetailList.concat(
                "
" +
                    "" + contact.firstName.toString() + " " + contact.lastName.toString() + "" +
                    "
" +
                        "
" + contact.email.toString() + "
" +
                        "
" + contact.phoneNumber.toString() + "
" +
                        "
" + contact.birthDate.toString() + "
" +
                    "
" +
                 "
");
        });

        // Start with a clean list element otherwise we would have repeats.
        $('#contacts-display-listview').empty();

        // Check if it is already initialized or not, refresh the list in case it is initialized otherwise trigger create.
        if ( $('#contacts-display-listview').hasClass('ui-listview')) {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - hasClass ui-listview) - append.listview - start");
            $('#contacts-display-listview').append(contactList).listview("refresh", true);
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - hasClass ui-listview) - append.listview - end");
        }
        else {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - !hasClass ui-listview) - append.trigger - start");
            $('#contacts-display-listview').append(contactList).enhanceWithin();
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-listview - !hasClass ui-listview) - append.trigger - end");
        }

        // Start with a clean list element otherwise we would have repeats.
        $('#contacts-display-detail-listview').empty();

        // check if it is already initialized or not, refresh the list in case it is initialized otherwise trigger create
        if ( $('#contacts-display-detail-listview').hasClass('ui-listview')) {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - hasClass ui-listview) - append.listview - start");
            $('#contacts-display-detail-listview').append(contactDetailList).listview("refresh", true);
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - hasClass ui-listview) - append.listview - end");
        }
        else {
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - !hasClass ui-listview) - append.trigger - start");
            $('#contacts-display-detail-listview').append(contactDetailList).enhanceWithin();
            console.log(getCurrentTime() + " [js/app.js] (#contacts-display-detail-listview - !hasClass ui-listview) - append.trigger - end");
        }

        // Attach onclick event to each row of the contact list that will open up the contact info to be edited.
        $('.contacts-list-item').on("click", function(event){
            if(event.handled !== true) {
                console.log(getCurrentTime() + " [js/app.js] (.contacts-display-listview -> on click) - start");

                CONTACTS.app.getContactById($(this).attr("id").split("list-contact-ID-").pop());

                event.handled = true;
                console.log(getCurrentTime() + " [js/app.js] (.contacts-display-listview -> on click) - end");
            }
        });

        // Attach onclick event to each row of the contact list detailed page that will open up the contact info to be edited.
        $('li.contacts-detail-list-item').on("click", function(event){
            if(event.handled !== true) {
                console.log(getCurrentTime() + " [js/app.js] (li.contacts-display-listview -> on click) - start");

                CONTACTS.app.getContactById($(this).attr("id").split("detail-contact-ID-").pop());

                // Turn the whole
 into a link.
                $("body").pagecontainer("change", "#contacts-edit-page");

                event.handled = true;
                console.log(getCurrentTime() + " [js/app.js] (li.contacts-display-listview -> on click) - end");
            }
        });

        console.log(getCurrentTime() + " [js/app.js] (buildContactList) - end");
        // Add in a line to visually see when we are done.
        console.log("-----------------------------List Page---------------------------------------");
    };

    // This is called by the on click event list above.
    // Retrieve employee detail based on employee id.
    CONTACTS.app.getContactById = function (contactID) {
        console.log(getCurrentTime() + " [js/app.js] (getContactById) - start");
        console.log(getCurrentTime() + " [js/app.js] (getContactById) - contactID = " + contactID);

        var jqxhr = $.ajax({
            url: restEndpoint + "/" + contactID.toString(),
            cache: false,
            type: "GET"
        }).done(function(data, textStatus, jqXHR) {
            console.log(getCurrentTime() + " [js/app.js] (getContactById) - success on ajax call");
            CONTACTS.app.buildContactDetail(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.log(getCurrentTime() + " [js/app.js] (getContactById) - error in ajax" +
                        " - jqXHR = " + jqXHR.status +
                        " - textStatus = " + textStatus +
                        " - errorThrown = " + errorThrown);
        });
        console.log(getCurrentTime() + " [js/app.js] (getContactById) - end");
    };

    // This is called by CONTACTS.app.getContactById.
    // Display contact detail for editing on the Edit page.
    CONTACTS.app.buildContactDetail = function(contact) {
        console.log(getCurrentTime() + " [js/app.js] (buildContactDetail) - start");

        // Put each field value in the text input on the page.
        $('#contacts-edit-input-firstName').val(contact.firstName);
        $('#contacts-edit-input-lastName').val(contact.lastName);
        $('#contacts-edit-input-tel').val(contact.phoneNumber);
        $('#contacts-edit-input-email').val(contact.email);
        $('#contacts-edit-input-date').val(contact.birthDate);
        $('#contacts-edit-input-id').val(contact.id);

        console.log(getCurrentTime() + " [js/app.js] (buildContactDetail) - end");
        // Add in a line to visually see when we are done.
        console.log("-----------------------------Update Page---------------------------------------");
    };

    console.log(getCurrentTime() + " [js/app.js] (document -> pagecreate) - end");
});

<|endoftext|>


<commit_before>import { v4 } from 'uuid'

export const ADD_TAB = 'ADD_TAB'
export const CLOSE_TAB = 'CLOSE_TAB'
export const SELECT_TAB = 'SELECT_TAB'
export const UPDATE_URL = 'UPDATE_TITLE'
export const CHANGE_INPUT = 'CHANGE_INPUT'
export const FOCUS_INPUT = 'FOCUS_INPUT'
export const BLUR_INPUT = 'BLUR_INPUT'

export const LOAD_START = 'LOAD_START'
export const LOAD_SUCCESS = 'LOAD_SUCCESS'
export const LOAD_FAIL = 'LOAD_FAIL'

export const addTab = () => {
  // This is an ugly hack.
  // When new tab is opened, location input should focus.
  // It is too complex to do this in React way. 🌧
  document.querySelector('#location').focus()
  return {
    type: ADD_TAB,
    id: v4(),
  }
}

export const closeTab = id => (dispatch, getState) => {
  const state = getState()
  const { tabs } = state
  const allIds = Object.keys(tabs)

  // Do not close last tab
  if (allIds.length <= 1) {
    alert('This is the last tab :)') // eslint-disable-line
    return
  }

  // When active tab is closed, make right tab active
  // If no right, make left active
  let activeId = state.activeTab
  if (id === state.activeTab) {
    const position = allIds.indexOf(id)
    if (position < allIds.length - 1) {
      activeId = allIds[position + 1]
    } else {
      activeId = allIds[position - 1]
    }
  }

  dispatch({
    type: CLOSE_TAB,
    id,
    activeId,
    url: tabs[activeId].url,
  })
}

export const selectTab = id => (dispatch, getState) => dispatch({
  type: SELECT_TAB,
  id,
  url: getState().tabs[id].url,
})

export const updateUrl = ({ id, url }) => ({
  type: UPDATE_URL,
  id,
  url,
})

export const changeInput = value => ({
  type: CHANGE_INPUT,
  value,
})

export const focusInput = value => ({
  type: FOCUS_INPUT,
  value,
})

export const blurInput = () => ({
  type: BLUR_INPUT,
})

const loadStart = ({ id, url }) => ({
  type: LOAD_START,
  id,
  url,
})

export const loadSuccess = id => ({
  type: LOAD_SUCCESS,
  id,
})

const loadFail = id => ({
  type: LOAD_FAIL,
  id,
})

export const load = () => (dispatch, getState) => {
  // Ugly hack either
  // Make loaction input blur after submit
  document.querySelector('#location').blur()

  const state = getState()
  const id = state.activeTab
  const url = state.input
  dispatch(loadStart({ id, url }))

  // HACK
  // We don't know if iframe loaded successfully.
  // If no response after 3s, marked as fail.
  const TIMEOUT = 5000
  setTimeout(() => {
    if (!getState().tabs[id].isLoaded) {
      dispatch(loadFail(id))
    }
  }, TIMEOUT)
}
<commit_msg>Remove loadFail action<commit_after>import { v4 } from 'uuid'

export const ADD_TAB = 'ADD_TAB'
export const CLOSE_TAB = 'CLOSE_TAB'
export const SELECT_TAB = 'SELECT_TAB'
export const UPDATE_URL = 'UPDATE_TITLE'
export const CHANGE_INPUT = 'CHANGE_INPUT'
export const FOCUS_INPUT = 'FOCUS_INPUT'
export const BLUR_INPUT = 'BLUR_INPUT'

export const LOAD_START = 'LOAD_START'
export const LOAD_SUCCESS = 'LOAD_SUCCESS'
export const LOAD_FAIL = 'LOAD_FAIL'

export const addTab = () => {
  // This is an ugly hack.
  // When new tab is opened, location input should focus.
  // It is too complex to do this in React way. 🌧
  document.querySelector('#location').focus()
  return {
    type: ADD_TAB,
    id: v4(),
  }
}

export const closeTab = id => (dispatch, getState) => {
  const state = getState()
  const { tabs } = state
  const allIds = Object.keys(tabs)

  // Do not close last tab
  if (allIds.length <= 1) {
    alert('This is the last tab :)') // eslint-disable-line
    return
  }

  // When active tab is closed, make right tab active
  // If no right, make left active
  let activeId = state.activeTab
  if (id === state.activeTab) {
    const position = allIds.indexOf(id)
    if (position < allIds.length - 1) {
      activeId = allIds[position + 1]
    } else {
      activeId = allIds[position - 1]
    }
  }

  dispatch({
    type: CLOSE_TAB,
    id,
    activeId,
    url: tabs[activeId].url,
  })
}

export const selectTab = id => (dispatch, getState) => dispatch({
  type: SELECT_TAB,
  id,
  url: getState().tabs[id].url,
})

export const updateUrl = ({ id, url }) => ({
  type: UPDATE_URL,
  id,
  url,
})

export const changeInput = value => ({
  type: CHANGE_INPUT,
  value,
})

export const focusInput = value => ({
  type: FOCUS_INPUT,
  value,
})

export const blurInput = () => ({
  type: BLUR_INPUT,
})

const loadStart = ({ id, url }) => ({
  type: LOAD_START,
  id,
  url,
})

export const loadSuccess = id => ({
  type: LOAD_SUCCESS,
  id,
})

export const load = () => (dispatch, getState) => {
  // Ugly hack either
  // Make loaction input blur after submit
  document.querySelector('#location').blur()

  const state = getState()
  const id = state.activeTab
  const url = state.input
  dispatch(loadStart({ id, url }))
}
<|endoftext|>