// Package BAM_ERMES_COMMON / Copyright 2025 Archimed SA / JSE //loading package... packages.acknowledge('BAM_ERMES_COMMON'); // file: jquery.jgrowl.js (function ($) { $.jGrowl = function (m, o) { if ($('#jGrowl').size() == 0) $('<div id="jGrowl"></div>').addClass((o && o.position) ? o.position : $.jGrowl.defaults.position).appendTo('body'); $('#jGrowl').jGrowl(m, o); }; $.fn.jGrowl = function (m, o) { if ($.isFunction(this.each)) { var args = arguments; return this.each(function () { var self = this; if ($(this).data('jGrowl.instance') == undefined) { $(this).data('jGrowl.instance', $.extend(new $.fn.jGrowl(), { notifications: [], element: null, interval: null })); $(this).data('jGrowl.instance').startup(this); } if ($.isFunction($(this).data('jGrowl.instance')[m])) { $(this).data('jGrowl.instance')[m].apply($(this).data('jGrowl.instance'), $.makeArray(args).slice(1)); } else { $(this).data('jGrowl.instance').create(m, o); } }); }; }; $.extend($.fn.jGrowl.prototype, { defaults: { pool: 0, header: '', group: '', sticky: false, position: 'top-right', glue: 'after', theme: 'default', themeState: 'highlight', corners: '10px', check: 250, life: 3000, closeDuration: 'normal', openDuration: 'normal', easing: 'swing', closer: true, closeTemplate: '×', closerTemplate: '<div>[ close all ]</div>', log: function (e, m, o) { }, beforeOpen: function (e, m, o) { }, afterOpen: function (e, m, o) { }, open: function (e, m, o) { }, beforeClose: function (e, m, o) { }, close: function (e, m, o) { }, animateOpen: { opacity: 'show' }, animateClose: { opacity: 'hide'} }, notifications: [], element: null, interval: null, create: function (message, o) { var o = $.extend({}, this.defaults, o); if (typeof o.speed !== 'undefined') { o.openDuration = o.speed; o.closeDuration = o.speed; } this.notifications.push({ message: message, options: o }); o.log.apply(this.element, [this.element, message, o]); }, render: function (notification) { var self = this; var message = notification.message; var o = notification.options; var notification = $('<div class="jGrowl-notification ' + o.themeState + ' ui-corner-all' + ((o.group != undefined && o.group != '') ? ' ' + o.group : '') + '">' + '<div class="jGrowl-close">' + o.closeTemplate + '</div>' + '<div class="jGrowl-header">' + o.header + '</div>' + '<div class="jGrowl-message">' + message + '</div></div>').data("jGrowl", o).addClass(o.theme).children('div.jGrowl-close').bind("click.jGrowl", function () { $(this).parent().trigger('jGrowl.close'); }).parent(); $(notification).bind("mouseover.jGrowl", function () { $('div.jGrowl-notification', self.element).data("jGrowl.pause", true); }).bind("mouseout.jGrowl", function () { $('div.jGrowl-notification', self.element).data("jGrowl.pause", false); }).bind('jGrowl.beforeOpen', function () { if (o.beforeOpen.apply(notification, [notification, message, o, self.element]) != false) { $(this).trigger('jGrowl.open'); } }).bind('jGrowl.open', function () { if (o.open.apply(notification, [notification, message, o, self.element]) != false) { if (o.glue == 'after') { $('div.jGrowl-notification:last', self.element).after(notification); } else { $('div.jGrowl-notification:first', self.element).before(notification); } $(this).animate(o.animateOpen, o.openDuration, o.easing, function () { if ($.browser.msie && (parseInt($(this).css('opacity'), 10) === 1 || parseInt($(this).css('opacity'), 10) === 0)) this.style.removeAttribute('filter'); if ($(this).data("jGrowl") != null) $(this).data("jGrowl").created = new Date(); $(this).trigger('jGrowl.afterOpen'); }); } }).bind('jGrowl.afterOpen', function () { o.afterOpen.apply(notification, [notification, message, o, self.element]); }).bind('jGrowl.beforeClose', function () { if (o.beforeClose.apply(notification, [notification, message, o, self.element]) != false) $(this).trigger('jGrowl.close'); }).bind('jGrowl.close', function () { $(this).data('jGrowl.pause', true); $(this).animate(o.animateClose, o.closeDuration, o.easing, function () { if ($.isFunction(o.close)) { if (o.close.apply(notification, [notification, message, o, self.element]) !== false) $(this).remove(); } else { $(this).remove(); } }); }).trigger('jGrowl.beforeOpen'); if (o.corners != '' && $.fn.corner != undefined) $(notification).corner(o.corners); if ($('div.jGrowl-notification:parent', self.element).size() > 1 && $('div.jGrowl-closer', self.element).size() == 0 && this.defaults.closer != false) { $(this.defaults.closerTemplate).addClass('jGrowl-closer ui-state-highlight ui-corner-all').addClass(this.defaults.theme).appendTo(self.element).animate(this.defaults.animateOpen, this.defaults.speed, this.defaults.easing).bind("click.jGrowl", function () { $(this).siblings().trigger("jGrowl.beforeClose"); if ($.isFunction(self.defaults.closer)) { self.defaults.closer.apply($(this).parent()[0], [$(this).parent()[0]]); } }); }; }, update: function () { $(this.element).find('div.jGrowl-notification:parent').each(function () { if ($(this).data("jGrowl") != undefined && $(this).data("jGrowl").created != undefined && ($(this).data("jGrowl").created.getTime() + parseInt($(this).data("jGrowl").life)) < (new Date()).getTime() && $(this).data("jGrowl").sticky != true && ($(this).data("jGrowl.pause") == undefined || $(this).data("jGrowl.pause") != true)) { $(this).trigger('jGrowl.beforeClose'); } }); if (this.notifications.length > 0 && (this.defaults.pool == 0 || $(this.element).find('div.jGrowl-notification:parent').size() < this.defaults.pool)) this.render(this.notifications.shift()); if ($(this.element).find('div.jGrowl-notification:parent').size() < 2) { $(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose, this.defaults.speed, this.defaults.easing, function () { $(this).remove(); }); } }, startup: function (e) { this.element = $(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>'); this.interval = setInterval(function () { $(e).data('jGrowl.instance').update(); }, parseInt(this.defaults.check)); if ($.browser.msie && parseInt($.browser.version) < 7 && !window["XMLHttpRequest"]) { $(this.element).addClass('ie6'); } }, shutdown: function () { $(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove(); clearInterval(this.interval); }, close: function () { $(this.element).find('div.jGrowl-notification').each(function () { $(this).trigger('jGrowl.beforeClose'); }); } }); $.jGrowl.defaults = $.fn.jGrowl.prototype.defaults; })(jQuery); // [EOF] for file jquery.jgrowl.js // file: tag-it.js (function ($) { $.fn.tagit = function (options) { var el = this, BACKSPACE = 8, ENTER = 13, SPACE = 32, COMMA = 44; // add the tagit CSS class. el.addClass("tagit"); // create the input field. var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li><a href=\"#\" class=\"bouton tagit_ok\"><span>ok</span></a>\n"; el.html(html_input_field); var $tagitInput = el.find(".tagit-input"); $tagitInput.focus(); $(el).click(function (e) { // if (e.target.tagName == 'A') { // // Removes a tag when the little 'x' is clicked. // // Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it. //// $(e.target).parent().remove(); // } if ($(e.target).hasClass("tagit_ok")) { var e = jQuery.Event("keypress"); e.which = ENTER; $tagitInput.trigger(e); return true; } else { // Sets the focus() to the input field, if the user clicks anywhere inside the UL. // This is needed because the input field needs to be of a small size. $tagitInput.focus(); return false; } }); $tagitInput.keypress(function (event) { // if (event.which == BACKSPACE) { // if (tag_input.val() == "") { // // When backspace is pressed, the last tag is deleted. // $(el).children(".tagit-choice:last").remove(); // } // } // Comma/Space/Enter are all valid delimiters for new tags. //if (event.which === COMMA || event.which === SPACE || event.which === ENTER) { // Space is annoying while talking about tags... if (event.which === ENTER) { event.preventDefault(); var typed = $(this).val(); typed = typed.replace(/,+$/, ""); typed = typed.trim(); if (typed !== "") { if (is_new(typed, this)) { create_choice_label_value(typed, this); } // Cleaning the input. $(this).val(""); } } }); $tagitInput.autocomplete({ source: options.availableTags // select: function (event, ui) { // //if (is_new(ui.item.value, this)) { // // create_choice_label_value(ui.item, this); // //} // // Cleaning the input. // //$(this).val(""); // $(this).val(ui.item.value); // // Preventing the tag input to be update with the chosen value. // return false; // } }); //V?rifie si le tag ajout? n'est pas d?j? pr?sent function is_new(value, elt) { var is_new = true; $(elt).parents("ul").children(".tagit-choice").each(function (i) { n = $(this).children("input").val(); if (value == n) { is_new = false; } }); return is_new; } function create_choice(value, elt) { var el = ""; el = "<li class=\"tagit-choice\">\n"; el += value + "\n"; el += "<a class=\"close\">x</a>\n"; el += "<input type=\"hidden\" style=\"display:none;\" value=\"" + value + "\" name=\"item[tags][]\">\n"; el += "</li>\n"; var li_search_tags = $(elt).parent(); $(el).insertBefore(li_search_tags); $(elt).val(""); } function create_choice_label_value(item, elt) { var el = ""; el = "<li class=\"tagit-choice\"><a class=\"tag_label\">\n"; el += ((typeof (item.label) != "undefined") ? item.label : item) + "</a>\n"; el += "<a class=\"bouton supp\" href=\"#\" title=\"supprimer\">\n"; el += "<span class=\"x-label\" id=\"res_ResultsLinkedTagsDeleteLabel_label\">supprimer</span></a>"; el += "<input type=\"hidden\" style=\"display:none;\" value=\"" + ((typeof (item.value) != "undefined") ? item.value : item) + "\" name=\"item[tags][]\">\n"; el += "</li>\n"; var li_search_tags = $(elt).parent(); $(el).insertBefore(li_search_tags); $(elt).val(""); } }; String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ""); }; })(jQuery); // [EOF] for file tag-it.js // file: typewatch.js /* * TypeWatch 2.0 - Original by Denny Ferrassoli / Refactored by Charles Christolini * * Examples/Docs: www.dennydotnet.com * * Copyright(c) 2007 Denny Ferrassoli - DennyDotNet.com * Coprright(c) 2008 Charles Christolini - BinaryPie.com * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function (jQuery) { jQuery.fn.typeWatch = function (o) { // Options var options = jQuery.extend({ wait: 750, callback: function () { }, highlight: true, captureLength: 2 }, o); function checkElement(timer, override) { var elTxt = jQuery(timer.el).val(); // Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text) || (override && elTxt.length > options.captureLength)) { timer.text = elTxt.toUpperCase(); timer.cb(elTxt); } }; function watchElement(elem) { // Must be text or textarea if (elem.type.toUpperCase() == "TEXT" || elem.nodeName.toUpperCase() == "TEXTAREA") { // Allocate timer element var timer = { timer: null, text: jQuery(elem).val().toUpperCase(), cb: options.callback, el: elem, wait: options.wait }; // Set focus action (highlight) if (options.highlight) { jQuery(elem).focus( function () { this.select(); }); } // Key watcher / clear and reset the timer var startWatch = function (evt) { var timerWait = timer.wait; var overrideBool = false; if (evt.keyCode == 13 && this.type.toUpperCase() == "TEXT") { timerWait = 1; overrideBool = true; } var timerCallbackFx = function () { checkElement(timer, overrideBool); }; // Clear timer clearTimeout(timer.timer); timer.timer = setTimeout(timerCallbackFx, timerWait); }; jQuery(elem).keydown(startWatch); } }; // Watch Each Element return this.each(function (index) { watchElement(this); }); }; })(jQuery); // [EOF] for file typewatch.js // file: common.js if (typeof console == "undefined") { this.console = { log: function () { } }; } ///////////////////////////////////////////////////////// // jGrowl Defaults $.jGrowl.defaults.closer = false; // indexOf n'est pas implémenté par IE <= 8 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } ///////////////////////////////////////////////////////// // Namespace (w. Module Pattern) var ErmesManager = (function () { var pub = {}; //Enum pub.SearchType = { "Basket": 0, "Selection": 1, "Detail": 2, "DetailStatic": 3, "List": 4, "Tag": 5 }; pub.CaptureType = { "Search": 0, "Area": 1, "Grid": 2 }; pub.SearchTimeout = -1; pub.CurrentSearchType = pub.SearchType.List; pub.StopAutocompletion = false; pub.afterImgLoad = function (selector, callback) { var self = this, args = Array.prototype.slice.call(arguments, 2), imgCount = $(selector).length, imgLoaded = 0; $(selector).one('load', function () { imgLoaded++; if (imgLoaded >= imgCount) { callback.apply(self, args); //Appel du callback avec le contexte courant et ses eventuels arguments (passés à afterImgLoad) } }).each(function () { //Déclencher l'event load meme si l'image provient du cache if (this.complete) { $(this).load(); } }); }; //A executer avant chaque recherche... pub.beforeSearch = function () { /* $("#pdf_loading").remove(); //Dialog Export PDF $("#expo_resa").remove(); //Dialog reservation d'expo */ $("div.dialog-model").remove(); $(".ui-dialog").remove(); $(".container").remove(); //Les dialogs jQuery UI sont coriaces... Même après un dialog('destroy') il en reste des traces sur la page... return true; } //demande une licence et lance l'application si ok pub.launchAppli = function () { var $container = ErmesManager.findClosestContainer("#searchField"); var data = $container.data("form"); var url; try { document.getElementById('ErmesLauncher1').EID = data.Result.Resource.RscId; document.getElementById('ErmesLauncher1').Instance = CFInstance; document.getElementById('ErmesLauncher1').Server = sErmesServer; document.getElementById('ErmesLauncher1').XmlLaunch = sErmesXmlLaunch; document.getElementById('ErmesLauncher1').LaunchXml(); } catch (e) { if (sErmesTS) { url = '/ermes/resource/termserv.aspx?INSTANCE=' + CFInstance + '&EID=' + data.Result.Resource.RscId; popups.get('popupLaunchTs').putPropertyValue('title', 'Lancement de l\'application ...'); popups.get('popupLaunchTs').putPropertyValue('src', url); popups.show('popupLaunchTs', callbackLaunchTs); //JSGo(url); } } }; pub.renderImg = function () { $('img.amazonCover').one('load', function () { var $img = $(this), format; try { if ($("#notice_longue").length) { format = $("#notice_longue").data("result").Resource.Frmt; } else { format = $(this).closest("li").find(".notice").data("result").Resource.Frmt; } } catch (e) { console.log(e); } format = format || "MONO"; if (format.substring(0, 5) == "marc:") { format = format.substring(5); } var t = new Image(); t.src = ($img.attr ? $img.attr("src") : false) || $img.src; if (t.width == 1 || t.height == 1) { $img.attr('src', '/medias/image.ashx?SIZE=MEDIUM&F=' + format); setTimeout(function () { $("div#images_scroll").smoothDivScroll("recalculateScrollableArea"); $("div#images_scroll").smoothDivScroll("showHotSpotBackgrounds"); }, 500); } else { $img.parents('li').find('.copyright_vignettes').show(); } }).each(function () { //Déclencher l'event load meme si l'image provient du cache if (this.complete) { $(this).load(); } }); }; pub.setupAutocomplete = function (input) { var termTemplate = "<span class='ui-autocomplete-term'>%s</span>", //Pour gérer la mise en gras du terme recherché textField = $(input), ajaxSearch; textField.data("last_autocomplete", ""); //Pour ne pas relancer la recherche si elle porte sur le même terme var autoSearch = function (value, delay, force) { if (ErmesManager.StopAutocompletion) { ErmesManager.StopAutocompletion = false; } else { if (ErmesManager.AjaxAutocomplete) { if (textField.data("last_autocomplete") !== value) { clearTimeout(ErmesManager.SearchTimeout); textField.data("last_autocomplete", value); ErmesManager.SearchTimeout = setTimeout(function () { ErmesManager.CurrentSearchType = ErmesManager.SearchType.List; ErmesManager.Cloud.Data = ""; ErmesManager.callback.common.search(textField, { QueryString: value, ResultSize: ErmesManager.getCookieValue(ErmesManager.COOKIES_FORM, "resultSize", 10), Grid: null, ScenarioCode: $("#globalScenario").val(), ForceSearch: true, CloudTerms: [], SearchLabel: "" }); }, delay); return true; } } else if (force) { $("#main_search_form").submit(); } } return false; }; $(input).autocomplete({ "source": function (req, add) { // Passage de la saisie en lowercase req.term = req.term.toLowerCase(); req.scenarioCode = $("#globalScenario").val(); if (typeof (ajaxSearch) !== "undefined") { ajaxSearch.abort(); } ajaxSearch = jQuery.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: "/" + CFInstance + "/ermes/recherche/Search.svc/SolrSuggest", data: JSON.stringify(req), success: function (data) { if (!ErmesManager.checkResponse(data)) { return; } if (data.d != null && typeof (data.d) !== 'undefined' && data.d.Suggestions.length > 0) { add(data.d.Suggestions); } else { //On a pas de suggestion, on lance quand meme une recherche sur le terme entré if (ErmesManager.AjaxAutocomplete) { $(input).autocomplete("close"); $(input).data("last_autocomplete", $(input).val()); clearTimeout(ErmesManager.SearchTimeout); ErmesManager.SearchTimeout = setTimeout(function () { ErmesManager.CurrentSearchType = ErmesManager.SearchType.List; ErmesManager.Cloud.Data = ""; ErmesManager.callback.common.search($(input), { ResultSize: ErmesManager.getCookieValue(ErmesManager.COOKIES_FORM, "resultSize", 10), Grid: null, ScenarioCode: $("#globalScenario").val(), ForceSearch: true, CloudTerms: [], SearchLabel: "" }); }, 400); } } }, error: function (XMLHttpRequest, textStatus, errorThrown) { $("#error").html(XMLHttpRequest.responseText); } }); }, open: function (event, ui) { //Override de l'event open pour gérer la mise en gras + lancer la recherche sur le premier terme remonté var acData = $(this).data('autocomplete'), styledTerm = termTemplate.replace('%s', acData.term); acData.menu.element.find('a').each(function () { var me = $(this); me.html(me.text().replace(acData.term, styledTerm)); }); var textField = $("#textfield"); var value = textField.autocomplete("widget").find("li:first").text(); return autoSearch(value, 400); }, select: function (event, ui) { //Lorsqu'on sélectionne un élément on lance une recherche $("#textfield").val(ui.item.label); return autoSearch(ui.item.label, 0, true); }, "dataType": "json", "delay": 200 }); }; pub.convertTagCloudJson = function (input) { return $.map(input, function (item) { return { label: item.Label, value: item.Label }; }); }; pub.convertSelectionsJson = function (input) { return $.map(input, function (item) { return { label: item.SelName, value: item.SelUid }; }); }; // Renvoie une structure contenant les identifiants d'un item associé au contrôle HTML passé en paramètre pub.getCurrentItemIdentifiers = function (controlElement) { var data = controlElement.closest("div.notice").data("result"); var ids = {}; if (!ErmesManager.isDefined(data.Resource)) { return null; } ids.RscUid = data.Resource.RscUid; if (ids.RscUid === 0 || typeof (ids.RscUid) === "undefined") { ids.RscBase = data.Resource.RscBase; ids.RscDocId = data.Resource.RscId; } return ids; }; pub.checkResponse = function (jsonData) { if (ErmesManager.isNullOrEmpty(jsonData) || typeof (jsonData.d) === "undefined") { pub.notify("Format de réponse inattendu", { "theme": "growlError" }); return false; } if (typeof (jsonData.message) !== "undefined" && jsonData.message !== "") { pub.notify(jsonData.message); } if (typeof (jsonData.success) !== "undefined" && jsonData.success === false) { try { pub.notify(jsonData.errors[0].msg, { "theme": "growlError" }); } catch (e) { } $(".ajax-loader-big").remove(); return false; } return true; }; pub.showMessage = function (errors) { $("<div></div>").text(errors[0].msg).dialog({ title: "Erreur", modal: true, buttons: { Ok: function () { $(this).dialog("close"); } } }); }; pub.notify = function (msg, options) { var params = { position: 'bottom-right' }; $.extend(params, options); $.jGrowl(msg, params); }; pub.isDefined = function (o) { return (typeof (o) !== "undefined" && o !== null); }; pub.isNullOrEmpty = function (o) { return (typeof (o) === "undefined" || o === ""); }; pub.searchString = function (arrayToSearch, stringToSearch) { arrayToSearch.sort(); for (var i = 0; i < arrayToSearch.length; i++) { if (arrayToSearch[i] === stringToSearch) { return true; } } return false; }; pub.serializeObject = function (self) { var o = {}; var a = $(self).serializeArray(); $.each(a, function () { if (typeof (this.value) !== "undefined" && this.value !== "") { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = [this.value || '']; } } }); return o; }; pub.findClosestContainer = function (self) { var $container = $(self).closest("div.searchContainer"); if ($container.length !== 0) { return $container; } else { return $("body").find("div.searchContainer:first"); } }; pub.displayForm = function ($target, scenarioCode) { var params = { "query": { "ScenarioCode": scenarioCode} }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/Search.svc/GetForm", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } $target.html(json.d); } }); }; ///////////////////////////////////////////////////////// // Ecrit une valeur dans un cookie json pub.saveCookieValue = function (cookieName, key, value) { if ((typeof (key) === "undefined") || (typeof (cookieName) === "undefined")) { return; } if ((key.length === 0) || (cookieName.length === 0)) { return; } var jsonCookie = null; jsonCookie = JSON.parse($.cookie(cookieName)); if (jsonCookie === null) { jsonCookie = {}; } jsonCookie[key] = value; $.cookie(cookieName, JSON.stringify(jsonCookie), ErmesManager.cookieOptions); }; ///////////////////////////////////////////////////////// // Lit une valeur dans un cookie json pub.getCookieValue = function (cookieName, key, defaultValue) { if ((typeof (key) === "undefined") || (typeof (cookieName) === "undefined")) { return defaultValue; } if (cookieName.length === 0) { return defaultValue; } var jsonCookie = null; jsonCookie = JSON.parse($.cookie(cookieName)); if (jsonCookie === null) { jsonCookie = {}; } if (key === '') { return jsonCookie; } value = jsonCookie[key]; value = typeof (value) === "undefined" ? defaultValue : value; return value; }; pub.cookieOptions = { path: '/', expires: 0 }; //ErmesLibrary.COOKIES_PREFIX = "erms_form_"; pub.COOKIES_FORM = "ErmesForms"; ///////////////////////////////////////////////////////// // Initialise les tooltips qtip pub.initTooltips = function () { // Désactivation des tooltip pour le moment return; //Réinitialiser les tooltips $("ul.notice > li").each(function () { var $container = ErmesManager.findClosestContainer(this); var $this = $(this); var data = $container.data("form"); var query = {}; var ids = ErmesManager.getCurrentItemIdentifiers($this.find("div.notice_corps")); if (ErmesManager.isDefined(ids)) { query = { query: { RscUid: ids.RscUid, RscBase: ids.RscBase, RscDocId: ids.RscDocId, ScenarioCode: $("#globalScenario").val(), UseScenarioForTemplate: true} }; $(this).qtip({ content: { text: 'Chargement en cours...', ajax: { url: "/" + CFInstance + "/Ermes/Recherche/Openfind.svc/GetOpenfindRecord", type: 'POST', data: JSON.stringify(query), dataType: 'json', success: function (data, status) { var content = data.d.Result.CustomResult; this.set('content.text', content); return false; } } }, position: { my: 'top left', at: 'bottom left', viewport: $(window), adjust: { x: 4, y: 0 } }, style: { classes: 'ui-tooltip-light ui-tooltip-shadow ui-tooltip-ermes' // Inherit from preset style }, show: { solo: true }, hide: { fixed: true } }); } }); }; pub.loadSearchInserts = function () { var searchInserts = $("div.ermes_search_model"); var insertLength = searchInserts.length; for (var i = 0; i < insertLength; i++) { (function () { var $insert = $(searchInserts[i]); var q = { query: { InjectOpenFind: true, XslPath: "Recherche/encart_search.xslt"} }; $.each($insert.find("span"), function () { q.query[$(this).attr("class")] = $(this).text(); }); $insert.data("query", q); $insert.closest("div.content_corps").prepend("<div class='ajax-loader-big'/>"); $.ajax( { url: "/" + CFInstance + "/Ermes/Recherche/Search.svc/Search", data: JSON.stringify(q), success: function (json) { //Lien RSS var rss = "<a target=\"_blank\" href=\"/" + CFInstance + "/Ermes/Recherche/Search.svc/SearchRss?q=" + encodeURIComponent(JSON.stringify(q.query)) + "\" class=\"RSS ENCART_FUNCTIONS cms-icon-rss\"/>"; $insert.closest("div.content").append(rss); $insert.closest("div.content_corps").find(".ajax-loader-big").remove(); $insert.html(json.d.HtmlResult); if (!$insert.is(":visible")) { $insert.show(); } if ($insert.hasClass("chargement_async")) { $insert.toggleClass("chargement_async"); } ErmesManager.renderImg(); $insert.find("a.fancybox").fancybox(); try { JSPortal_resize(null); } catch (e) { //Nothing } } }); })(); } }; pub.buildCaptureForm = function (q, t) { $("#capture_search_dialog").remove(); //Remise à zéro de la modal box (si déjà existante) var dialogHtml = '<div id="capture_search_dialog" class="dialog-model" style="display:none;">' + '<div class="template_container"/>' + '</div>'; $("body").append(dialogHtml); if (t === ErmesManager.CaptureType.Search) { //Dans le cas d'une capture de recherche, on affiche 2 boutons pour choisir le type d'affichage & le nombre de notices var buttonsHtml = '<div class="capture_search_actions">' + '<div>Affichage : <select class="capture_type"><option value="Recherche/encart_search.xslt">Miniatures</option><option value="Recherche/encart_search_short.xslt">Court</option></select></div>' + '<div>Nombre de notices à afficher : <input class="capture_change_size" type="text" value="' + q.query.ResultSize + '"></input></div>' + '<div>Libellé de la recherche : <input class="capture_change_label" type="text" value="' + q.query.SearchLabel + '"></input></div>' + '</div>'; $("#capture_search_dialog").append(buttonsHtml); } ErmesManager.populateCaptureForm(q, t); }; pub.populateCaptureForm = function (q, t) { var title = "", tmpl = ""; $("div.template_container", "#capture_search_dialog").html(""); switch (t) { case ErmesManager.CaptureType.Search: tmpl = "#captureSearchTmpl"; title = "Capturer la recherche"; break; case ErmesManager.CaptureType.Area: tmpl = "#captureSearchAreaTmpl"; title = "Capturer la zone de recherche"; break; case ErmesManager.CaptureType.Grid: tmpl = "#captureSearchGridTmpl"; title = "Capturer le formulaire avancé"; break; } $(tmpl).tmpl(q).appendTo($("div.template_container", "#capture_search_dialog")); $("#capture_search_dialog").data("query", q); $("#capture_search_dialog").dialog({ modal: true, title: title, width: 500, height: 500, buttons: { Ok: function () { $(this).dialog("close"); } } }); }; //Fonction vérifiant la présence du cookie 'fileDownloadToken' signifiant que l'export PDF est prêt (conditionne la fermeture du dialog 'pdf_loading') //... On pourrait être tentés d'utiliser l'évenement onload sur l'iframe, mais le fonctionnement n'est pas cross browser //... D'ou ce workaround pub.checkCookie = function (token) { window.setTimeout(function () { var cookieValue = $.cookie('fileDownloadToken'); if (cookieValue == token) { $("#pdf_loading").dialog("destroy"); } else { ErmesManager.checkCookie(token); } }, 500); } return pub; } ()); ///////////////////////////////////////////////////////// // Classe abstraite 'Form' ErmesManager.BaseForm = { //Champs Query: { query: { Page: 0, ResultSize: ErmesManager.getCookieValue(ErmesManager.COOKIES_FORM, "resultSize", 10)} }, PreviousQuery: { query: { Page: 0, ResultSize: ErmesManager.getCookieValue(ErmesManager.COOKIES_FORM, "resultSize", 10)} }, Result: {}, Info: {}, //Méthodes toJson: function ($form) { var jsonObject = {}, jsonString = {}; $form.each(function () { jsonObject = ErmesManager.serializeObject($(this)); jsonString = JSON.stringify(jsonObject); }); return jsonString.replace(new RegExp("\\[\\]", "g"), ""); }, //à overrider doSearch: function ($container) { return false; }, getHoldingsFull: function ($container, data) { $.ajax({ url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/GetHoldings", data: JSON.stringify(data), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } if (json.d === null) { $('#detail-holdings').html(""); return; } $('#detail-holdings').html(json.d.HtmlView); try { JSPortal_resize(null); } catch (e) { //Nothing } var $holdings = $('.holding-item'), holdingIds = $.map($holdings, function (val, i) { return $(val).attr("data-id"); }); $.each(json.d.Holdings, function (index, value) { var id = value.HoldingId, idx = holdingIds.indexOf(id); $($holdings[idx]).data("result", value); $('#holding-reservation-title').data("result", value); }); //Tooltip d'aide var $multipleSelect = $("#detail-holdings").find(".multiple-reservation-mad"), $multipleResa = $("#detail-holdings").find(".multiple-reservation"); if ($multipleSelect.length) { $multipleSelect.qtip({ content: s_WAI_HOLDINGS_HOLDING_PLACE, position: { my: 'bottom center', at: 'top center' }, style: { classes: 'ui-tooltip-dark ui-tooltip-shadow' // Inherit from preset style }, show: { target: $("#detail-holdings .holding-help") }, hide: { target: $("#detail-holdings .holding-help") } }); } if ($multipleResa.length) { $multipleResa.qtip({ content: ErmesManager.labels.HoldingHelpHoldingMultiple, position: { my: 'bottom left', at: 'top right' }, style: { classes: 'ui-tooltip-dark ui-tooltip-shadow' // Inherit from preset style }, show: { target: $("#detail-holdings .holding-help") }, hide: { target: $("#detail-holdings .holding-help") } }); } } }); }, getHoldings: function ($container) { var Holds = { RecordIdArray: [], searchQuery: this.Query.query }; $.each(this.Result, function () { // L'absence de Resource (i.e: openfind) provoquait une erreur. j'ai donc testé en amont if (typeof (this.Resource) != "undefined") { Holds.RecordIdArray.push({ RscId: this.Resource.RscId, Docbase: this.Resource.RscBase, PazPar2Id: this.Recid }); } }); $.ajax({ url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/CheckAvailability", data: JSON.stringify(Holds), success: function (json) { ErmesManager.checkResponse(json); if (json.d === null) { return; } // Sélection des documents affichés var $records = $('#resultats .notice_courte'); // On parcourt chaque résultat récupéré, et on associe à chaque élément dom correspondant // le html généré $.each(json.d, function () { var itemJson = this; //20110310 : Optimisation du fetch de la bonne notice parmis les résultats (ajout d'un identifiant DOM contenant le RscId) var $targetDiv = $("#rscId_" + itemJson.Id.RscId, "#resultats"); //alert($targetDiv); $('.statut', $targetDiv).html(itemJson.HtmlView); }); } }); }, getEnrichment: function ($container, query) { var self = this; var ajaxMore; if (typeof (ajaxMore) != "undefined") { ajaxMore.abort(); } ajaxMore = $.ajax( { ifModified: true, cache: true, async: true, type: 'GET', url: "/" + CFInstance + "/Ermes/Recherche/Sarasvati.svc/More", data: 'queryStr=' + JSON.stringify(query.query), success: function (json) { ErmesManager.checkResponse(json); if (json.d != null && json.d.HtmlResult != null) { $("#enrichissements").html(json.d.HtmlResult); self.EnrichmentLoaded = true; $('#tab-more-wip').hide(); $("a.fancybox").fancybox(); // Images LastFM et Quatrième if (json.d.HtmlResult != "") { $('#tab-more-dispo').show(); } } else { $('#tab-more-wip').hide(); } } }); } }; ///////////////////////////////////////////////////////// // Sous-module 'Services' ErmesManager.services = (function () { var self = this; var pub = {}; pub.retrieveShortAccount = function (code) { params = { codeConfig: code, xslPath: "Services/MyShortAccount.xslt" }; $.ajax({ url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/RetrieveShortAccount", type: 'POST', async: true, contentType: "application/json; charset=utf-8", dataType: "json", timeout: 60000, //1 min data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } $('#MyShortAccount').html(json.d.HtmlView); // appel au resize CF try { JSPortal_resize(null); } catch (e) { //Nothing } } }); }; pub.retrieveAccount = function (code) { params = { codeConfig: code }; $.ajax({ url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/RetrieveAccount", type: 'POST', async: true, contentType: "application/json; charset=utf-8", dataType: "json", timeout: 60000, //1 min data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } $('#MyAccount').html(json.d.HtmlResult); // appel au resize CF try { JSPortal_resize(null); } catch (e) { //Nothing } var $items = $('.Loan'); $.each(json.d.ClientAccount.Loans, function (index, value) { $($items[index]).data("result", value); }); $items = $('.Reservation'); $.each(json.d.ClientAccount.Reservations, function (index, value) { $($items[index]).data("result", value); }); } }); }; /* * Méthode de réservation par titre */ pub.PlaceTitleReservation = function () { var holdingItem = $('#holding-reservation-title').data("result"); //Choix du lieu de mise à dispo if ($("#detail-holdings .multiple-reservation-mad").length) { holdingItem.HoldingPlace = $("#detail-holdings .multiple-reservation-mad").val(); } $.ajax({ url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/PlaceReservation", type: 'POST', async: true, contentType: "application/json; charset=utf-8", dataType: "json", timeout: 60000, //1 min data: '{"HoldingItem":' + JSON.stringify(holdingItem) + '}', success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } //TODO : si la résa s'est bien passée, on change le bouton réserver en réservation effectuée ? } }); return false; }; pub.PlaceReservation = function (holdingItem, $domItem) { //Choix du lieu de mise à dispo if ($("#detail-holdings .multiple-reservation-mad").length) { holdingItem.HoldingPlace = $("#detail-holdings .multiple-reservation-mad").val(); } $.ajax({ url: "/" + CFInstance + "/Ermes/Services/ILSClient.svc/PlaceReservation", type: 'POST', async: true, contentType: "application/json; charset=utf-8", dataType: "json", timeout: 60000, //1 min data: '{"HoldingItem":' + JSON.stringify(holdingItem) + '}', success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } $domItem.remove(); } }); return false; }; return pub; } ()); ///////////////////////////////////////////////////////// // Sous-module 'Selection' ErmesManager.selection = (function () { var state = 0; var pub = {}; pub.options = { async: true }; pub.List = []; pub.clear = function () { $.ajax({ async: pub.options.async, url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/LightSelectionClear", success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.selection.List = []; ErmesManager.selection.refreshControl(); ErmesManager.selection.checkSelectedItems(); } }); }; pub.addToBasket = function () { $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/LightSelectionAddToBasket", success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } } }); }; pub.deleteItem = function (index) { ErmesManager.selection.toggleItem(ErmesManager.selection.List[index]); }; pub.toArray = function () { return this.List; }; // Charge la sélection courante depuis le serveur pub.load = function () { $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/GetLightSelection", success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.selection.List = json.d; } }); }; pub.toggleItem = function (item) { var params = { resIdentifier: { RscUid: item.RscUid, RscBase: item.RscBase, RscDocId: item.RscId} }; $.ajax({ async: pub.options.async, url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/LightSelectionToggleItem", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.selection.List = json.d; ErmesManager.selection.refreshControl(); ErmesManager.selection.checkSelectedItems(); ErmesManager.callback.selection.showSelection(); } }); }; pub.addItem = function (item) { for (var i = 0; i < pub.List.length; ++i) { if (pub.List[i].RscUid === item.RscUid) { return false; } } pub.toggleItem(item); return true; }; pub.toggleItems = function (items) { var identifiers = []; $.each(items, function () { if (ErmesManager.isDefined(this.Resource)) { identifiers.push({ RscUid: this.Resource.RscUid, RscBase: this.Resource.RscBase, RscDocId: this.Resource.RscId }); } }); var query = { items: identifiers }; $.ajax({ async: pub.options.async, url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/LightSelectionToggleItems", data: JSON.stringify(query), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.selection.List = json.d; ErmesManager.selection.refreshControl(); ErmesManager.selection.checkSelectedItems(); ErmesManager.callback.selection.showSelection(); } }); }; pub.toggleFloating = function (item) { if ($("#multi_selection_simple").length > 0) { $("#multi_selection_simple").toggleClass("no_float"); } else { $("#multi_selection").toggleClass("no_float"); } }; pub.refreshControl = function () { if ($("#multi_selection_simple").length > 0) { $("#multi_selection_simple").html($("#selectionTmpl").tmpl({ "item": ErmesManager.selection.toArray() })); } else { $("#multi_selection").html($("#selectionTmpl").tmpl({ "item": ErmesManager.selection.toArray() })); var $multiSelecChild = $("#multi_selection").children("div.global_content"); $multiSelecChild.removeClass("sel_reduced").addClass("sel_enlarged"); $multiSelecChild.find("div.content_corps").removeAttr("style"); $multiSelecChild.find("div.content_footer").removeAttr("style"); } }; pub.checkSelectedItems = function () { $("input:checkbox", "#resultats ul.notice li[id!='']").attr('checked', false); for (var item in ErmesManager.selection.List) { $("#" + ErmesManager.selection.List[item].RscUid, "#resultats").find("input").attr('checked', true); } }; return pub; } ()); ///////////////////////////////////////////////////////// // Sous-module 'event' ErmesManager.event = (function () { var pub = {}; //Evénement appelé à la fin d'une recherche pub.onSearchComplete = function (event, $container) { // Synchronise le scenario si disponible var $scenarioDropDown = $("#globalScenario"); if ($scenarioDropDown.length !== 0) { var data = $($container).data("form"); $("option[value='" + data.Query.query.ScenarioCode + "']", $scenarioDropDown).attr("selected", true); } // Mise à jour de la selection ErmesManager.selection.refreshControl(); ErmesManager.selection.checkSelectedItems(); $.address.history(true); try { JSPortal_resize(null); } catch (e) { //Nothing } ErmesManager.renderImg(); $($container).trigger("searchHtmlLoaded"); }; return pub; } ()); ///////////////////////////////////////////////////////// // Sous-module 'callback' ErmesManager.callback = (function () { var pub = {}; //!\ Evitez de polluer la racine du namespace. Préférez un découpage en sous-namespaces (e.g. callback.selection, callback.basket...). return pub; } ()); ErmesManager.callback.selection = (function () { var pub = {}; //Ajout d'un objet à la selection courante pub.toggleItemIntoSelection = function () { var index = $(this).closest("li.on").index(); var data = ErmesManager.findClosestContainer(this).data("form"); var item = data.Result[index].Resource; ErmesManager.selection.toggleItem(item); }; //Toggle affichage selection pub.showSelection = function () { var $selection = $("#multi_selection_simple"); if ($selection.length > 0) { $selection.attr("id", "multi_selection"); var $selectionChild = $selection.children("div.global_content"); $selectionChild.removeClass("sel_reduced").addClass("sel_enlarged"); $selectionChild.find("div.content_corps").removeAttr("style"); $selectionChild.find("div.content_footer").removeAttr("style"); //le fadeTo pose problème avec IE et le PNG... //$selection.fadeTo(0, 0.7); } return false; }; // Supprime un item de la sélection flottante pub.removeSelectionItem = function () { var $this = $(this); ErmesManager.selection.deleteItem($this.attr("data-index")); return false; }; // Vide la sélection flottante pub.clearSelection = function () { var $dialog = $("#confirm_dialog_selection"); ErmesManager.callback.common.buildConfirmBox($dialog); //Boite de dialogue pour confirmer l'action ErmesManager.callback.common.openConfirmBox($dialog, ErmesManager.selection.clear); return false; }; //Verse la sélection courante dans le panier pub.addSelectionToBasket = function () { ErmesManager.selection.addToBasket(); return false; }; //Ouvre la popup de gestion des sélections pour le contenu de la sélection flottante pub.bindToSelections = function () { // Construction du formulaire ErmesManager.callback.ofSelection.buildSelectionsForm(); $("#manageSelectionsForm").data("result", ErmesManager.selection.toArray()).dialog("open"); return false; }; //Suppression d'un objet de la selection pub.removeFromSelection = function () { ErmesManager.selection.deleteItem($(this).closest("li").attr("id")); if ($("#multi_selection_simple").length > 0) { $("#multi_selection_simple").html($("#selectionTmpl").tmpl({ "item": ErmesManager.selection.toArray() })); } else { $("#multi_selection").html($("#selectionTmpl").tmpl({ "item": ErmesManager.selection.toArray() })); } // Sauve la sélection flottante ErmesManager.selection.save(); }; //Toggle affichage selection pub.toggleSelection = function () { var $selection = $("#multi_selection_simple"), $selectionChild; if ($selection.length > 0) { $selection.attr("id", "multi_selection"); $selectionChild = $selection.children("div.global_content"); $selectionChild.removeClass("sel_reduced").addClass("sel_enlarged"); $selectionChild.find("div.content_corps").removeAttr("style"); $selectionChild.find("div.content_footer").removeAttr("style"); } else { $selection = $("#multi_selection"); $selection.attr("id", "multi_selection_simple"); $selectionChild = $selection.children("div.global_content"); $selectionChild.removeClass("sel_enlarged").addClass("sel_reduced"); $selectionChild.find("div.content_corps").attr("style", "display:none;"); $selectionChild.find("div.content_footer").attr("style", "display:none;"); } return false; }; pub.checkAll = function (self) { var data = ErmesManager.findClosestContainer(self).data("form"); var notices = []; var uncheckedItems = $("ul.notice > li", "#resultats").find(":checkbox:not(:checked)"); $.each(uncheckedItems, function () { var index = $(this).closest("li").index(); notices.push(data.Result[index]); }); ErmesManager.selection.toggleItems(notices); }; pub.uncheckAll = function (self) { var data = ErmesManager.findClosestContainer(self).data("form"); var notices = []; var uncheckedItems = $("ul.notice > li", "#resultats").find(":checkbox:checked"); $.each(uncheckedItems, function () { var index = $(this).closest("li").index(); notices.push(data.Result[index]); }); ErmesManager.selection.toggleItems(notices); }; return pub; } ()); ErmesManager.callback.pagination = (function () { var pub = {}; //Page précédente pub.previousPage = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); if (data.Query.query.Page > 0) { data.Query.query.Page--; data.doSearch($container); } return false; }; //Page suivante pub.nextPage = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); if (data.Query.query.Page < data.Info.PageMax) { data.Query.query.Page++; data.doSearch($container); } return false; }; //Changement de page pub.changePage = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var newPage = $(this).children("span").text(); data.Query.query.Page = newPage - 1; data.doSearch($container); return false; }; //Changement de ResultSize pub.changeResultSize = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var newResultSize = $(this).val(); data.Query.query.Page = 0; data.Query.query.ResultSize = newResultSize; data.doSearch($container); // Sauvegarde Cookie ErmesManager.saveCookieValue(ErmesManager.COOKIES_FORM, "resultSize", newResultSize); return false; }; return pub; } ()); ErmesManager.callback.tag = (function () { var pub = {}; // Supprime une ressource d'un tag pub.removeTagResource = function () { var $this = $(this); var ids = ErmesManager.getCurrentItemIdentifiers($this); if (!ErmesManager.isDefined(ids)) { return false; } var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var tagUid = $this.attr("data-selectionId"); var params = { "resIdentifier": { "RscUid": ids.RscUid, "RscBase": ids.RscBase, "RscDocId": ids.RscDocId }, "tagUid": tagUid }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/ResourceRemoveTag", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); return false; }; //Affiche le champ tag-it pour l'ajout de tag pub.showTagForm = function () { var $this = $(this); var tags = []; tags = $this.closest("div.notice").data("result").Resource.Tags; var ids = ErmesManager.getCurrentItemIdentifiers($this); if (!ErmesManager.isDefined(ids)) { return false; } var $tagDiv = $this.closest("div.themes"); $this.closest("div.cadre").html("<ul class='tagit_container_tag'></ul>").removeClass("cadre"); var $tagitContainer = $tagDiv.find("ul.tagit_container_tag"); var tagsLabel = []; for (var j = 0; j < tags.length; j++) { tagsLabel.push(tags[j].Label); } $tagitContainer.tagit({ availableTags: function (req, add) { req.resIdentifier = ids; jQuery.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/SuggestTagsForResource", data: JSON.stringify(req), success: function (data) { if (!ErmesManager.checkResponse(data)) { return; } add(ErmesManager.convertTagCloudJson(data.d.list)); }, error: function (XMLHttpRequest, textStatus, errorThrown) { ErmesManager.notify(XMLHttpRequest.responseText); } }); } }); return false; }; //Ajout de tag pub.addTag = function (e) { if (e.keyCode === 13) { var $this = $(this); var request = { query: { Tags: []} }; var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var ids = ErmesManager.getCurrentItemIdentifiers($this); if (!ErmesManager.isDefined(ids)) { return false; } request.query.RscUid = ids.RscUid; request.query.RscBase = ids.RscBase; request.query.RscDocId = ids.RscDocId; $.each($this.children("li.tagit-choice"), function () { request.query.Tags.push($(this).children("input").val()); }); $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/AddTag", data: JSON.stringify(request), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); return false; } }; return pub; } ()); ErmesManager.callback.comment = (function () { var pub = {}; pub.buildCommentForm = function () { // Construction formulaire d'ajout de commentaire $("#addCommentForm").dialog({ autoOpen: false, resizable: true, modal: true, buttons: { "Valider": function () { ErmesManager.callback.comment.addComment(this); }, "Annuler": function () { $(this).dialog("close"); } }, close: function () { $(this).dialog('destroy'); } }); }; //Ajout d'un commentaire pub.addComment = function (form, isDetail) { var $this = $(form); var request = { query: {} }; var $container = ErmesManager.findClosestContainer($this); var data = $container.data("form"); var result = $this.data("result"); request.query.RscUid = result.Resource.RscUid; request.query.RscBase = result.Resource.RscBase; request.query.RscDocId = result.Resource.RscId || result.Resource.RscDocId; //RM-20111213 : RscDocId pour l'ajout de commentaire depuis le compte lecteur request.query.Title = $this.find("input[name='titre']").val(); request.query.Message = $this.find("textarea[name='comment']").val(); request.query.Nickname = $this.find("input[name='pseudo']").val(); request.query.UserPlace = $this.find("input[name='ville']").val(); request.query.Note = $this.find("select[name='note']").val(); if (request.query.Nickname.replace(/^\s+|\s+$/, '') === '') { $this.find("input[name='pseudo']").addClass("required"); return false; }; if (request.query.Title.replace(/^\s+|\s+$/, '') === '') { $this.find("input[name='titre']").addClass("required"); return false; }; if (request.query.Message.replace(/^\s+|\s+$/, '') === '') { $this.find("textarea[name='comment']").addClass("required"); return false; }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/AddComment", data: JSON.stringify(request), success: function (json) { $this.dialog("close"); if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); return false; }; //Affiche le formulaire d'ajout de commentaire pub.showAddCommentForm = function () { // Construction du formulaire jQuery UI d'ajout de commentaire ErmesManager.callback.comment.buildCommentForm(); var result = $(this).closest("div.notice").data("result"); $("#addCommentForm").data("result", result).dialog("open"); return false; }; //Suppression d'un commentaire pub.commonDeleteComment = function (uid, callback) { $.ajax({ url: "/" + CFInstance + "/Ermes/Contributions/CommentAdminService.svc/Delete", data: JSON.stringify({ commentUids: [uid] }), success: callback }); }; //Suppression d'un commentaire pub.deleteComment = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer($this); var data = $container.data("form"); var uid = $this.closest("li").attr("id").substr(3); var callback = function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.notify("Votre commentaire a bien été supprimé"); setTimeout(function () { data.doSearch($container); }, 1000); } ErmesManager.callback.comment.commonDeleteComment(uid, callback); return false; }; pub.invalidateComment = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer($this); var data = $container.data("form"); var commentUid = { uid: $this.closest("li").attr("id").substr(3) }; var callback = function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/DeleteComment", data: JSON.stringify(commentUid), success: callback }); return false; } pub.commonEditComment = function (uid, message, title, callback) { var query = { commentUid: uid, newComment: "" }; $("#edit_comment_message").val(message); $("#edit_comment_title").val(title); // Construction formulaire d'ajout de commentaire $("#edit_comment_form").dialog({ autoOpen: true, resizable: true, modal: true, height: 450, width: 350, buttons: { "Valider": function () { var commentValue = $("#edit_comment_form").find(".comment_text").val(); var commentTitle = $("#edit_comment_form").find(".comment_title").val(); query.newComment = commentValue; query.newTitle = commentTitle; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/EditCommentByUid", data: JSON.stringify(query), success: callback }); }, "Annuler": function () { $(this).dialog("close"); } }, close: function () { $(this).dialog('destroy'); } }); }; //Edition d'un commentaire pub.editComment = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer($this); var data = $container.data("form"); var commentUid = $this.closest("li").attr("id").substr(3); var commentIdx = $this.closest("li").index(); var commentMsg = data.Result.Resource.Cmts[commentIdx].Message; var commentTitle = data.Result.Resource.Cmts[commentIdx].Title; var callback = function (json) { if (!ErmesManager.checkResponse(json)) { return; } $(this).dialog("close"); data.doSearch($container); }; ErmesManager.callback.comment.commonEditComment(commentUid, commentMsg, commentTitle, callback); return false; }; //Validation d'un commentaire pub.validateComment = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer($this); var data = $container.data("form"); var uid = { uid: parseInt($this.closest("li").attr("id").substr(3), 10) }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/ValidateComment", data: JSON.stringify(uid), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); }; return pub; } ()); ErmesManager.callback.basket = (function () { var pub = {}; //Suppression d'un document du panier pub.removeFromBasket = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var ids = ErmesManager.getCurrentItemIdentifiers($this); if (!ErmesManager.isDefined(ids)) { return false; } var params = { uid: ids.RscUid }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/DeleteBasketItem", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); return false; }; //Ajout au panier pub.addToBasket = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var ids = ErmesManager.getCurrentItemIdentifiers($this); if (!ErmesManager.isDefined(ids)) { return false; } var params = { resIdentifier: { RscUid: ids.RscUid, RscBase: ids.RscBase, RscDocId: ids.RscDocId} }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/AddBasketItem", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); return false; }; return pub; } ()); ErmesManager.callback.ofSelection = (function () { var pub = {}; //Affiche le formulaire de gestion des selections pub.showSelectionsForm = function () { // Construction du formulaire ErmesManager.callback.ofSelection.buildSelectionsForm(); var $this = $(this); var result = $this.closest("div.notice").data("result"); $("#manageSelectionsForm").data("result", result.Resource); var $container = ErmesManager.findClosestContainer(this); $("#manageSelectionsForm").data("container", $container).dialog("open"); return false; }; pub.addNewSelectionDialog = function () { var label = $("#manageSelectionsForm").find("#newSelectionName").val(); var description = $("#manageSelectionsForm").find("#newSelectionDescription").val(); ErmesManager.callback.ofSelection.addNewSelection(label, description); return false; }; // Crée une nouvelle sélection pub.addNewSelection = function (label, description) { var params = { "label": label, "description": description }; // lancement de la requête d'ajout $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/CreateSelection", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } // On affecte d'office les ressources à cette nouvelle sélection (confort) ErmesManager.callback.ofSelection.bindToSelection(json.d.SelUid); // Mise à jour de la liste des sélections ErmesManager.callback.ofSelection.refreshSelectionsForm(); } }); return false; }; // Supprime une ressource d'une sélection pub.removeSelectionResource = function () { var $this = $(this); var ids = ErmesManager.getCurrentItemIdentifiers($this); if (!ErmesManager.isDefined(ids)) { return false; } var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var selectionUid = $this.attr("data-selectionId"); var params = { "resIdentifier": [{ "RscUid": ids.RscUid, "RscBase": ids.RscBase, "RscDocId": ids.RscDocId}], "selectionUid": [selectionUid] }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/ResourcesRemoveSelections", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } data.doSearch($container); } }); return false; }; pub.buildSelectionsForm = function () { // Construction formulaire d'ajout de commentaire $("#manageSelectionsForm").dialog({ autoOpen: false, height: 450, width: 400, modal: true, buttons: { "Fermer": function () { $(this).dialog("close"); var $container = $(this).data("container"); if (typeof ($container) != "undefined") { var data = $container.data("form"); data.doSearch($container); } } }, close: function () { $(this).dialog('destroy'); }, open: function () { this.result = $(this).data("result"); // Mise à jour de la liste des sélections ErmesManager.callback.ofSelection.refreshSelectionsForm(); }, create: function () { // Biding filtre de sélections (typewatch) $("#selectionFilterInput", "#manageSelectionsForm").unbind().die(); $("#selectionFilterInput", "#manageSelectionsForm").typeWatch({ captureLength: -1, highlight: true, wait: 200, callback: ErmesManager.callback.ofSelection.refreshSelectionsForm }); $("#selectionFilterInput", "#manageSelectionsForm").hint(); } }); }; // Mise à jour de la liste des sélections pub.refreshSelectionsForm = function () { // RAZ des champs de saisie $("#newSelectionName", "#manageSelectionsForm").val(""); $("#newSelectionDescription", "#manageSelectionsForm").val(""); // Rechargement de la liste des sélections var resIdentifiers = []; var results = $("#manageSelectionsForm").data("result"); $(results).each(function (i, result) { resIdentifiers.push({ RscUid: result.RscUid, RscBase: result.RscBase, RscDocId: result.RscId }); }); // Lecture du filtre var filter = $("#selectionFilterInput", "#manageSelectionsForm").hasClass("blur") ? "" : $("#selectionFilterInput", "#manageSelectionsForm").val(); var params = { "resIdentifiers": resIdentifiers, "filter": filter }; $.ajax({ url: "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/GetAllSelectionsForResources", data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } //TODO : Afficher les sélections avec leur statut et des cases à cocher. $("#selectionsFormList").html($("#manageSelectionsTmpl").tmpl(json)); // TriState $("input.unknown", "#selectionsFormList").fadeTo(0, 0.5); } }); return false; }; pub.clickItem = function () { var $this = $(this); $this.fadeTo(0, 1); var serviceUrl = $this.is(":checked") ? "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/ResourcesAddSelections" : "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/ResourcesRemoveSelections"; var resIdentifiers = []; var results = $("#manageSelectionsForm").data("result"); $(results).each(function (i, result) { resIdentifiers.push({ RscUid: result.RscUid, RscBase: result.RscBase, RscDocId: result.RscId }); }); var params = { "resIdentifiers": resIdentifiers, "selectionsUid": [$this.attr("data-id")] }; $.ajax({ url: serviceUrl, data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.callback.ofSelection.refreshSelectionsForm(); } }); return false; }; // Affecte la sélection de ressources à la sélection openfind identifiée par son uid pub.bindToSelection = function (selUid) { var serviceUrl = "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/ResourcesAddSelections"; var resIdentifiers = []; var results = $("#manageSelectionsForm").data("result"); $(results).each(function (i, result) { resIdentifiers.push({ RscUid: result.RscUid, RscBase: result.RscBase, RscDocId: result.RscId }); }); var params = { "resIdentifiers": resIdentifiers, "selectionsUid": [selUid] }; $.ajax({ url: serviceUrl, data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.callback.ofSelection.refreshSelectionsForm(); } }); return false; }; pub.deleteSelectionByUid = function (selUid) { var serviceUrl = "/" + CFInstance + "/Ermes/Recherche/OpenFind.svc/DeleteSelection"; var params = { "selectionUid": selUid }; $.ajax({ url: serviceUrl, data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } ErmesManager.callback.ofSelection.refreshSelectionsForm(); } }); }; // Supprime une sélection identifiée par son UID pub.deleteSelection = function () { var $this = $(this); var $dialog = $("#confirm_dialog_ofselection"); ErmesManager.callback.common.buildConfirmBox($dialog); ErmesManager.callback.common.openConfirmBox($dialog, function () { ErmesManager.callback.ofSelection.deleteSelectionByUid($this.attr("data-selectionid")); }); }; return pub; } ()); ErmesManager.callback.common = (function () { var pub = {}; //Recherche pub.search = function (e, options) { if (e.keyCode === undefined || e.keyCode === 13) { // Suppression du timeout le cas échéant clearTimeout(ErmesManager.SearchTimeout); var $container = e.el === undefined ? ErmesManager.findClosestContainer(e) : ErmesManager.findClosestContainer(e.el); //typewatch plugin var data = $container.data("form"); $.extend(data.PreviousQuery.query, data.Query.query); //Backup de la requete precedente if (ErmesManager.isDefined(e.el)) { data.Query.query.QueryString = $(e.el).val(); } else if ($(e).val() !== "") { data.Query.query.QueryString = $(e).val(); } else { return false; } data.Query.query.Page = 0; //Remise à zero de la page if (ErmesManager.isDefined(data.Query.query.FacetFilter)) { //Suppression des filtres par facette delete data.Query.query.FacetFilter; } if (ErmesManager.isDefined(data.Query.query.SortField)) { //Suppression du tri delete data.Query.query.SortField; } $.extend(data.Query.query, options); //Override eventuel des paramètres de requête. data.doSearch($container); } }; //Toggle classe 'on' sur hover resultat pub.hoverResult = function () { var $this = $(this); $("ul.notice > li", "#resultats").removeClass("on").find(".actions > ul").attr("style", "display:none;"); $this.addClass("on").find(".actions > ul").removeAttr("style"); return false; }; pub.buildConfirmBox = function ($target) { $target.dialog({ modal: true, autoOpen: false }); }; pub.openConfirmBox = function ($target, on_success) { $target.dialog('option', 'buttons', { "Confirmer": function () { on_success(); $(this).dialog("close"); }, "Annuler": function () { $(this).dialog("close"); } }); $target.dialog("open"); }; pub.replaySearchInsert = function () { var $this = $(this); var q = $this.closest(".ermes_search_model").data("query"); delete q.query.XslPath; delete q.query.Page; q.query.InjectOpenFind = true; q.query.ResultSize = 10; window.location.assign("/medias/search.aspx?INSTANCE=" + CFInstance + "&SC=" + q.query.ScenarioCode + "&QUERY=" + encodeURIComponent(q.query.QueryString) + "#/Search/" + encodeURIComponent(JSON.stringify(q))); return false; }; pub.showCreatePublicSearchForm = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var query = data.Query.query; var $dialog = $("#SdiCreatePublicSearch") .dialog({ autoOpen: true, //title: 'Nouvelle recherche publique', modal: true, buttons: { "Valider": function () { if ($(this).find("#name").val() == '') { return false; } ErmesManager.callback.common.createPublicSearch(query, $(this).find("#description").val()); $(this).dialog('destroy'); }, "Annuler": function () { $(this).dialog("close"); } }, close: function () { $(this).dialog('destroy'); } }); }; pub.showSubscribeForm = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var query = data.Query.query; var $dialog = $("#SdiCreatePrivateSearch") .dialog({ autoOpen: true, //title: 'Nouvel abonnement à une recherche', modal: true, buttons: { "Valider": function () { if ($(this).find("#name").val() == '') { return false; } $(this).dialog('destroy'); ErmesManager.callback.common.subscribeSearch(query, $(this).find("#name").val()); }, "Annuler": function () { $(this).dialog("close"); } }, close: function () { $(this).dialog('destroy'); } }); }; pub.subscribeSearch = function (query, name) { var serviceUrl = "/" + CFInstance + "/Ermes/Recherche/Sdi.svc/Subscribe"; var params = { "query": query, name: name }; $.ajax({ url: serviceUrl, data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } } }); return false; }; pub.createPublicSearch = function (query, description) { var serviceUrl = "/" + CFInstance + "/Ermes/Recherche/Sdi.svc/CreatePublicSearchService"; var params = { "query": query, "description": description }; $.ajax({ url: serviceUrl, data: JSON.stringify(params), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } } }); return false; }; pub.exportToPDF = function (event, searchType) { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var token = new Date().getTime(); var q = data.Query.query; var query = { Target: 0, Source: searchType || ErmesManager.CurrentSearchType, Query: JSON.stringify(q), Token: token }; //On supprime l'iframe précédente au cas ou on aurait déjà lancé un export $('#iframe_download_pdf').remove(); //Création d'une iframe pour le téléchargement du pdf $('<iframe />', { name: 'pdf_iframe', id: 'iframe_download_pdf', style: 'display:none;', src: "/" + CFInstance + "/ermes/Recherche/Convert.svc/Convert?query=" + encodeURIComponent(JSON.stringify(query)) }).appendTo('body'); //Dialog telechargement PDF en cours $("#pdf_loading").dialog({ modal: true }); //Fonction vérifiant la présence du cookie 'fileDownloadToken' signifiant que l'export PDF est prêt (conditionne la fermeture du dialog 'pdf_loading') //... On pourrait être tentés d'utiliser l'évenement onload sur l'iframe, mais le fonctionnement n'est pas cross browser //... D'ou ce workaround ErmesManager.checkCookie(token); return false; }; pub.showExpoReservation = function () { var data = ErmesManager.findClosestContainer(this).data("form"); var recId = $(this).closest(".holding-item").attr("data-id") || data.Result.Resource.RscId; var rec = { "Docbase": data.Result.Resource.RscBase, "RscId": recId }; var q = { "query": { "Record": rec} }; $("#expo_resa").html("<div class='ajax-loader-big'/>"); $("#expo_resa").dialog({ modal: true, width: 'auto', height: 'auto', resizable: false, buttons: {}, close: function (e, ui) { $(this).dialog('destroy'); } }); var expoDates = []; var startDate; var endDate; var dateSwitch = false; var dateLowerBound; var dateUpperBound; //Event sur sélection de date var onSelect = function (date) { var dateParsed = $.datepicker.parseDate("d/m/yy", date); if (!dateSwitch) { startDate = endDate = dateParsed; $("#date_debut").val(date); $("#date_fin").val(date); } else if (dateParsed < startDate) { startDate = dateParsed; $("#date_debut").val(date); } else { endDate = dateParsed; $("#date_fin").val(date); } dateSwitch = !dateSwitch; return true; }; //Fonction appelée avant chaque affichage de date var beforeShowDay = function (date) { var textDate = date.format("d/m/Y"); //Désactivation des dates < à la date du jour if (date < new Date()) { return [false, ""]; } //Désactivation des dates déjà reservées (+ affichage du libellé en tooltip) for (var i = 0, length = expoDates.length; i < length; ++i) { var startExpoDate = $.datepicker.parseDate("d/m/yy", expoDates[i].DateDebut); var endExpoDate = $.datepicker.parseDate("d/m/yy", expoDates[i].DateFin); if (date >= startExpoDate && date <= endExpoDate) { return [false, "", expoDates[i].Libelle]; } } //Highlight des dates de début et de fin selectionnées if ((startDate && (startDate.getTime() === date.getTime())) || (endDate && (endDate.getTime() === date.getTime()))) { return [true, "ui-state-highlight"]; } //Si la date est comprise entre la date de début et de fin (non comprises), highlight else if (date > startDate && date < endDate) { return [true, "ui-state-dateRange"]; } //Cas par défaut else { return [true, ""]; } }; //Fonction cachant les entrée dans la table planning expo qui ne sont pas affichées dans le datepicker var showExpoTable = function () { var trDates = $("tbody > tr", "#planning_expo"); var trDateDebut; var trDateFin; trDates.each(function () { trDateDebut = $.datepicker.parseDate("d/m/yy", $(this).find(".date_debut").html()); trDateFin = $.datepicker.parseDate("d/m/yy", $(this).find(".date_fin").html()); if ((trDateDebut > dateLowerBound && trDateDebut < dateUpperBound) || (trDateFin > dateLowerBound && trDateDebut < dateUpperBound)) { $(this).show(); } else { $(this).hide(); } }); }; //Récupération des infos d'expo $.ajax({ url: "/" + CFInstance + "/Ermes/Services/BDP.svc/InfoExposition", data: JSON.stringify(q), success: function (json) { $("#expo_resa").html(json.d.HtmlResult); $("#expo_resa").dialog({ buttons: { "Réserver": function () { //Desactivation du bouton tant qu'on a pas reçu la réponse du service $(".ui-dialog-buttonpane button:contains('Réserver')").button("disable"); $("#expo_resa").next(".ui-dialog-buttonpane").prepend('<span class="chargement_async" style="float:left; margin-top: 10px; width: 20px; height:20px;"/>'); var resaQuery = $.extend(true, {}, q); resaQuery.query.DateDebut = $("#date_debut").val(); resaQuery.query.DateFin = $("#date_fin").val(); $.ajax({ url: "/" + CFInstance + "/Ermes/Services/BDP.svc/PlaceExpoReservation", data: JSON.stringify(resaQuery), success: function (json) { //Réactivation du bouton $(".ui-dialog-buttonpane button:contains('Réserver')").button("enable"); $("#expo_resa").next(".ui-dialog-buttonpane").find(".chargement_async").remove(); if (!ErmesManager.checkResponse(json)) { return; } else { ErmesManager.notify(json.d); } } }); }, "Fermer": function () { $(this).dialog("close"); } } }); expoDates = json.d.InfoExpos; //Infos d'expos renvoyées par le service web //Construction du datepicker jQuery UI $("#expo_datepicker").datepicker({ numberOfMonths: 3, changeMonth: true, changeYear: true, onSelect: function (dateText, inst) { return onSelect(dateText); }, beforeShowDay: function (date) { return beforeShowDay(date); }, onChangeMonthYear: function (year, month, inst) { //Mise à jour de la plage de dates affichées à l'écran (utilisé par showExpoTable) dateLowerBound.setMonth(month - 1); dateLowerBound.setYear(year); dateUpperBound = new Date(dateLowerBound); dateUpperBound.setMonth(dateLowerBound.getMonth() + $("#expo_datepicker").datepicker("option", "numberOfMonths") - 1); dateUpperBound = dateUpperBound.getLastDateOfMonth(); showExpoTable(); } }); $("#expo_resa").dialog("option", "position", "center"); $("#expo_resa").dialog("open"); dateLowerBound = $("#expo_datepicker").datepicker("getDate").getFirstDateOfMonth(); dateUpperBound = new Date(dateLowerBound); dateUpperBound.setMonth(dateLowerBound.getMonth() + $("#expo_datepicker").datepicker("option", "numberOfMonths") - 1); dateUpperBound = dateUpperBound.getLastDateOfMonth(); showExpoTable(); } }); return false; }; return pub; } ()); ErmesManager.callback.detail = (function () { var pub = {}; // Callback lien tarzan ISBD autorité pub.launchTarzanAuthority = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var q = data.Query.query.SearchQuery; var scenario = ErmesManager.isNullOrEmpty(q) ? "DEFAULT" : q.ScenarioCode; window.location.assign("/medias/search.aspx?INSTANCE=" + CFInstance + "&SC=" + scenario + "&QUERY=Authority_id_idx:%22" + $this.attr("data-id") + "%22&QUERY_LABEL=Recherche %22" + encodeURIComponent($this.text()) + "%22"); return false; }; // Callback lien tarzan ISBD bibliographique pub.launchTarzanBibliographic = function () { var $this = $(this); var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var q = data.Query.query.SearchQuery; var scenario = ErmesManager.isNullOrEmpty(q) ? "DEFAULT" : q.ScenarioCode; window.location.assign("/medias/search.aspx?INSTANCE=" + CFInstance + "&SC=" + scenario + "&QUERY=Identifier_idx:%22" + $this.attr("data-id") + "%22&QUERY_LABEL=Recherche %22" + encodeURIComponent($this.text()) + "%22&DETAIL_MODE=true"); return false; }; pub.showTab = function () { var $this = $(this); $this.addClass("on"); var thisTabId = $this.attr("href").substr(1); $("#" + thisTabId).removeAttr("style"); var $tabOnA = $this.closest("li").siblings("li").find("a[class='on']"); $tabOnA.removeClass("on"); var tabOnId = $tabOnA.attr("href").substr(1); $("#" + tabOnId).attr("style", "display:none;"); try { JSPortal_resize(null); } catch (e) { //Nothing } if (thisTabId === "enrichissements") { var $container = ErmesManager.findClosestContainer($this); var data = $container.data("form"); if (data.EnrichmentLoaded === false) { var title = ErmesManager.isDefined(data.Result.More.Title) ? data.Result.More.Title : null; var author = ErmesManager.isDefined(data.Result.More.Title) ? data.Result.More.Author : null; var isbn = ErmesManager.isDefined(data.Result.More.Isbn) ? data.Result.More.Isbn : null; var isbnList = ErmesManager.isDefined(data.Result.More.IsbnList) ? data.Result.More.IsbnList : null; var ean = ErmesManager.isDefined(data.Result.More.Ean) ? data.Result.More.Ean : null; var format = ErmesManager.isDefined(data.Result.More.Format) ? data.Result.More.Format : null; var query = { query: { Title: title, Author: author, Isbn: isbn, Ean: ean, Format: format, IsbnList: isbnList} }; $("#" + thisTabId).html("<h3> Chargement en cours, veuillez patienter </h3>"); data.getEnrichment($container, query); } } return false; }; return pub; } ()); ErmesManager.callback.capture = (function () { var pub = {}; pub.changeXsl = function () { var $this = $(this); var q = $this.closest("#capture_search_dialog").data("query"); q.query.XslPath = $this.val(); ErmesManager.populateCaptureForm(q, ErmesManager.CaptureType.Search); return false; }; pub.changeSize = function (event) { var $this = $(this); var q = $this.closest("#capture_search_dialog").data("query"); q.query.ResultSize = $this.val(); ErmesManager.populateCaptureForm(q, ErmesManager.CaptureType.Search); return true; }; pub.changeLabel = function (event) { var $this = $(this); var q = $this.closest("#capture_search_dialog").data("query"); q.query.SearchLabel = $this.val(); ErmesManager.populateCaptureForm(q, ErmesManager.CaptureType.Search); return true; }; pub.captureSearch = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); //Construction de la requête à utiliser dans l'encart de recherche var captureQuery = $.extend(true, {}, data.Query); //Deep clone data.Query captureQuery.query.ResultSize = 6; captureQuery.query.XslPath = "Recherche/encart_search.xslt"; delete captureQuery.query.ForceSearch; delete captureQuery.query.Page; delete captureQuery.query.TemplateParams; ErmesManager.buildCaptureForm(captureQuery, ErmesManager.CaptureType.Search); return true; }; pub.captureSearchArea = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); var scenariosArray = []; $.each($("#globalScenario")[0].options, function () { scenariosArray.push({ code: this.value, label: this.text }); }); //Construction de la requête à utiliser dans l'encart de recherche var captureQuery = { query: { url: "http://" + document.domain + "/medias/search.aspx", scenarios: scenariosArray } }; ErmesManager.buildCaptureForm(captureQuery, ErmesManager.CaptureType.Area); return true; }; pub.captureSearchGrid = function () { var $container = ErmesManager.findClosestContainer(this); var data = $container.data("form"); //Construction de la requête à utiliser dans l'encart de recherche var captureQuery = { query: {} }; jQuery.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: "/" + CFInstance + "/ermes/recherche/Search.svc/GetGridByScenarioCode", data: JSON.stringify({ code: $("#globalScenario").val() }), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } captureQuery.query.grid = $("#formTmpl").tmpl({ searchGrid: json.d }).html(); captureQuery.query.scenario = $("#globalScenario").val(); captureQuery.query.url = "http://" + document.domain + "/medias/search.aspx?Instance=" + CFInstance + "&SC=DEFAULT&QUERY=*:*"; ErmesManager.buildCaptureForm(captureQuery, ErmesManager.CaptureType.Grid); } }); return true; }; return pub; } ()); // Formulaire avancés (temporaire) // Sérialisation d'un objet (formulaire dans notre cas) jQuery.fn.serializeObject = function () { var o = {}; var a = jQuery(this).serializeArray(); jQuery.each(a, function () { if (typeof (this.value) !== "undefined" && this.value !== "") { if (o[this.name]) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = [this.value || '']; } } }); return o; }; // Binding d'un champ (association à un comportement spécifique selon les données associées) jQuery.fn.bindField = function (options) { var defaults = { serviceUrl: "/" + CFInstance + "/ermes/recherche/Search.svc/Suggest" }; var actualOptions = jQuery.extend(defaults, options); jQuery(this).each( function () { var jsonData = jQuery(this).data("jsonData"); if (jsonData !== null) { switch (jsonData.SearchFieldType) { case 3: jQuery(this).autocomplete({ "source": function (req, add) { req.fieldUid = jsonData.Id; // Passage de la saisie en lowercase req.term = req.term.toLowerCase(); jQuery.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: actualOptions.serviceUrl, data: JSON.stringify(req), success: function (data) { if (!ErmesManager.checkResponse(data)) { return; } add(data.d); }, error: function (XMLHttpRequest, textStatus, errorThrown) { jQuery("#error").html(XMLHttpRequest.responseText); } }); }, "dataType": "json", "delay": 500 }); break; default: break; } } } ); return this; }; // Binding d'un formulaire complet (invocation du binding de formulaire sur tous les champs) jQuery.fn.bindForm = function (options) { var defaults = { }; jQuery(this).each( function () { jQuery("input.suggest", jQuery(this)).bindField(jQuery.extend(defaults, options)); } ); return this; }; //Copie de champ jQuery.fn.copyField = function () { var newField = null; jQuery(this).each( function () { var currentRow = jQuery(this).parents(".indexWrapper"); newField = currentRow.clone(false).insertAfter(currentRow).find("input[type='text']"); newField.val("").data("jsonData", currentRow.find("input[type='text']").data("jsonData")); // On bind le nouveau champs afin qu'il se comporte comme prévu newField.bindField(); } ); return newField; }; //Génération de la chaine (string) json correspondant à l'objet courant jQuery.fn.toJson = function () { var jsonObject = null; var jsonString = null; jQuery(this).each( function () { jsonObject = jQuery(this).serializeObject(); jsonString = JSON.stringify(jsonObject); } ); return jsonString.replace(new RegExp("\\[\\]", "g"), ""); }; // Affichage d'un formulaire (TODO : expliquer les options) jQuery.fn.displayForm = function (options) { var defaults = { serviceUrl: "/" + CFInstance + "/ermes/recherche/Search.svc/GetGridByScenarioCode", restoreContext: true }; var actualOptions = jQuery.extend(defaults, options); jQuery(this).each(function () { var targetElement = jQuery(this); jQuery.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", url: actualOptions.serviceUrl, data: JSON.stringify({ code: actualOptions.scenarioCode }), success: function (json) { if (!ErmesManager.checkResponse(json)) { return; } // Transformation du json (SearchGrid) en formulaire //targetElement.setTemplateElement("formTpl").processTemplate(json.d); targetElement.html($("#formTmpl").tmpl({ searchGrid: json.d })); // Stockage du bloc json dans chaque index jQuery.each(json.d.Index.list, function (i, item) { jQuery("input." + item.Id, targetElement).data("jsonData", item); }); var actualForm = targetElement.find("form"); actualForm.addClass("ermes_form_container").addClass("ermes_container"); actualForm.data("data", actualOptions); // Binding des évènements (autocomplete, etc...) actualForm.bindForm(); // Restauration du contexte if (actualOptions.restoreContext) { var jsonString = ErmesManager.getCookieValue(ErmesManager.COOKIES_FORM, actualOptions.scenarioCode); if (typeof (jsonString) !== "undefined" && jsonString !== "") { var jsonObject = JSON.parse(jsonString); actualForm.populate(jsonObject); } } } }); }); }; jQuery.fn.launchSearch = function (options) { var defaults = { resultSize: ErmesManager.getCookieValue(ErmesManager.COOKIES_FORM, "resultSize", 10) }; var actualOptions = jQuery.extend(defaults, options); jQuery(this).each(function () { jQuery(this).fadeTo(0, 0.3); var savedData = jQuery(this).data("data"); // Ajout de l'objet de recherche qui sera envoyé au service de recherche actualOptions.searchQuery = { Page: 0, ResultSize: actualOptions.resultSize, ScenarioCode: savedData.scenarioCode, Grid: jQuery(this).toJson(), SortOrder: 0, InjectFields: true }; actualOptions.formOptions = savedData; ErmesManager.saveCookieValue(ErmesManager.COOKIES_FORM, savedData.scenarioCode, actualOptions.searchQuery.Grid); var targetElementById = null; if (typeof (savedData.searchTargetId) != "undefined") { targetElementById = jQuery("#" + savedData.searchTargetId); } var targetElement = targetElementById || actualOptions.searchTarget || savedData.searchTarget || jQuery(this).parent(); var form = new ErmesManager.Form(); // Initialisation de form.Query.query form.Query.query.ForceSearch = true; // On affecte ForceSearch au cas où Pz2 form.Query.query.QueryString = null; // On passe la recherche directe chaine à null form.Query.query.Grid = actualOptions.searchQuery.Grid; form.Query.query.ScenarioCode = actualOptions.searchQuery.ScenarioCode; form.Query.query.Page = 0; targetElement.data("form", form); form.doSearch(targetElement); // On masque le formulaire, on lui rend son opacité normale $(this).fadeTo(0, 1).hide(); }); }; jQuery.fn.resetForm = function () { jQuery(this).each(function () { var $this = jQuery(this); // RAZ Cookie var savedData = $this.data("data"); if (typeof (savedData) != "undefined") { ErmesManager.saveCookieValue(ErmesManager.COOKIES_FORM, savedData.scenarioCode, null); } /// RAZ HTML form $(":input[type!=button][type!=checkbox]", $this). val(""). removeAttr("selected"); $(":input[type=checkbox]", $this). attr("checked", false); }); }; jQuery(function () { /* French initialisation for the jQuery UI date picker plugin. */ /* Written by Keith Wood (kbwood{at}iinet.com.au) and Stéphane Nahmani (sholby@sholby.net). */ jQuery(function ($) { $.datepicker.regional['fr'] = { closeText: 'Fermer', prevText: '<Préc', nextText: 'Suiv>', currentText: 'Courant', monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], monthNamesShort: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'], dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'], weekHeader: 'Sm', dateFormat: 'dd/mm/yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: '' }; $.datepicker.setDefaults($.datepicker.regional['fr']); }); // Binding de la duplication de ligne d'index jQuery("form.ermes_form .addRow").live("click", function () { var currentRow = jQuery(this).parents(".indexWrapper"); currentRow.find("input[type='text']").copyField(); }); // Binding de la duplication de validation de formulaire jQuery("form.ermes_form input.ermes_valid").live("click", function () { jQuery(this).parents("form").launchSearch({}); }); // Binding de la duplication de reset de formulaire jQuery("form.ermes_form input.ermes_clear").live("click", function () { // RAZ Cookie var $form = jQuery(this).parents("form"); $form.resetForm(); }); // Catch validation form jQuery("form.ermes_form").live("submit", function () { jQuery(this).launchSearch(); return false; }); // validation par entrée sur les forms jQuery("form.ermes_form input").live("keyup", function (e) { if (e.keyCode == 13) { jQuery(this).parents("form.ermes_form").launchSearch(); return false; } }); // Binding affichage formulaire après masquage $("span.back_to_form").live("click", function () { $("div.searchForm form").toggle(); try { JSPortal_resize(null); } catch (e) { //Nothing } }); $("span.reserver_expo").live("click", ErmesManager.callback.common.showExpoReservation); $("#holding-reservation-title").live("click", ErmesManager.services.PlaceTitleReservation); $("span.reserver").live("click", function () { var $domItem = $(this).closest("span.holding-item"); var holdingItem = $domItem.data("result"); ErmesManager.services.PlaceReservation(holdingItem, $domItem); return false; }); $("a.hold-more").live("click", function () { $(this).closest("tr").next("tr").show(); $(this).removeClass("hold-more").addClass("hold-more-remove"); try { JSPortal_resize(null); } catch (e) { //Nothing } return false; }); $("a.hold-more-remove").live("click", function () { $(this).parents("tr").next("tr").hide(); $(this).removeClass("hold-more-remove").addClass("hold-more"); try { JSPortal_resize(null); } catch (e) { //Nothing } return false; }); // jQuery Ajax Setup $.ajaxSetup({ async: true, type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", timeout: 60000, //1 min error: function (jqXHR, textStatus, errorThrown) { //ErmesManager.notify("La requête a échoué : " + textStatus, { "theme": "growlError" }); //On remonte l'erreur à l'utilisateur $(".searchContainer").find(".ajax-loader-big").remove(); //On retire le gif de chargement (le cas échéant) return false; } }); // "Google suggest" ErmesManager.setupAutocomplete("#textfield"); // Chargement des eventuels encarts de recherche ErmesManager.loadSearchInserts(); $("div.ermes_search_model .see_all_results").live("click", ErmesManager.callback.common.replaySearchInsert); // Binding checkbox ajout/suppression de ressources / sélections dans formulaire "gestion des sélections" $("input:checkbox", "#selectionsFormList").live("click", ErmesManager.callback.ofSelection.clickItem); // binding bouton "ajout de nouvelle sélection" dans le formualaire $("#selectionsFormAddButton", "#manageSelectionsForm").live("click", ErmesManager.callback.ofSelection.addNewSelectionDialog); // Binding bouton "Supprimer" sur les sélections dans le formulaire $("a.supp", "#manageSelectionsForm").live("click", ErmesManager.callback.ofSelection.deleteSelection); $("select.capture_type", "#capture_search_dialog").live("change", ErmesManager.callback.capture.changeXsl); $("input.capture_change_size", "#capture_search_dialog").live("keyup", ErmesManager.callback.capture.changeSize); $("input.capture_change_label", "#capture_search_dialog").live("keyup", ErmesManager.callback.capture.changeLabel); // Binding lien ISBD autorité $("a.isbd-link-aut", "#notice_longue").live("click", ErmesManager.callback.detail.launchTarzanAuthority); // Binding lien ISBD biliographique $("a.isbd-link-bib", "#notice_longue").live("click", ErmesManager.callback.detail.launchTarzanBibliographic); //Binding export pdf $("a.export_pdf").live("click", ErmesManager.callback.common.exportToPDF); //Binding export pdf $("a.selection_export_pdf").live("click", function (e) { return ErmesManager.callback.common.exportToPDF.apply(this, [e, ErmesManager.SearchType.Selection]); }); // Binding abonnement à la recherche courante $("a.subscribe-search").live("click", ErmesManager.callback.common.showSubscribeForm); // Binding création recherche publique $("a.subscribe-search-public").live("click", ErmesManager.callback.common.showCreatePublicSearchForm); //Binding suppression item depuis la selection flottante $("#multi_selection a.removeItem").live("click", ErmesManager.callback.selection.removeSelectionItem); //Binding suppression tous les items depuis la selection flottante $("#multi_selection a.removeAll").live("click", ErmesManager.callback.selection.clearSelection); //Binding versement délection flottante vers le panier $("#multi_selection a.memoriser").live("click", ErmesManager.callback.selection.addSelectionToBasket); //Binding affectation des items de la sélection flottante à une selection $("#multi_selection a.bindToSelections").live("click", ErmesManager.callback.selection.bindToSelections); // Permet d'afficher les images correctement ErmesManager.renderImg(); $("#avis_lecteurs a.comment-delete").live("click", ErmesManager.callback.comment.deleteComment); $("#avis_lecteurs a.comment-edit").live("click", ErmesManager.callback.comment.editComment); $("#SdiCreatePrivateSearch form").live("submit", function (e) { return false; }); $("#SdiCreatePublicSearch form").live("submit", function (e) { return false; }); }); // [EOF] for file common.js //package loaded! packages.complete('BAM_ERMES_COMMON'); // Served in 399 ms