Fix JS codestyle

This commit is contained in:
Romain Neutron
2013-11-12 12:49:23 +01:00
parent 51fb364d13
commit 9fa95db23c
78 changed files with 5184 additions and 6309 deletions

View File

@@ -1,48 +1,53 @@
var p4 = p4 || {}; var p4 = p4 || {};
$(document).ready(function(){ $(document).ready(function () {
$('input.input-button').hover( $('input.input-button').hover(
function(){$(this).addClass('hover');}, function () {
function(){$(this).removeClass('hover');} $(this).addClass('hover');
},
function () {
$(this).removeClass('hover');
}
); );
var locale = $.cookie('locale'); var locale = $.cookie('locale');
var jq_date = p4.lng = typeof locale !== "undefined" ? locale.split('_').reverse().pop() : 'en'; var jq_date = p4.lng = typeof locale !== "undefined" ? locale.split('_').reverse().pop() : 'en';
if(jq_date == 'en') if (jq_date == 'en') {
{
jq_date = 'en-GB'; jq_date = 'en-GB';
} }
$.datepicker.setDefaults({showMonthAfterYear: false}); $.datepicker.setDefaults({showMonthAfterYear: false});
$.datepicker.setDefaults($.datepicker.regional[jq_date]); $.datepicker.setDefaults($.datepicker.regional[jq_date]);
$('a.infoDialog,div.infoDialog').live('click',function(event){ $('a.infoDialog,div.infoDialog').live('click', function (event) {
console.log("click"); console.log("click");
infoDialog($(this)); infoDialog($(this));
}); });
var cache = $('#mainMenu .helpcontextmenu'); var cache = $('#mainMenu .helpcontextmenu');
$('.context-menu-item',cache).hover(function(){$(this).addClass('context-menu-item-hover');},function(){$(this).removeClass('context-menu-item-hover');}); $('.context-menu-item', cache).hover(function () {
$(this).addClass('context-menu-item-hover');
$('#help-trigger').contextMenu('#mainMenu .helpcontextmenu',{openEvt:'click',dropDown:true,theme:'vista', dropDown:true, }, function () {
showTransition:'slideDown', $(this).removeClass('context-menu-item-hover');
hideTransition:'hide',
shadow:false
}); });
$('#notification_trigger').bind('mousedown',function(event){ $('#help-trigger').contextMenu('#mainMenu .helpcontextmenu', {openEvt: 'click', dropDown: true, theme: 'vista', dropDown: true,
showTransition: 'slideDown',
hideTransition: 'hide',
shadow: false
});
$('#notification_trigger').bind('mousedown', function (event) {
event.stopPropagation(); event.stopPropagation();
var box = $('#notification_box'); var box = $('#notification_box');
if($(this).hasClass('open')) if ($(this).hasClass('open')) {
{
box.hide(); box.hide();
$(this).removeClass('open'); $(this).removeClass('open');
clear_notifications(); clear_notifications();
} }
else else {
{
box.show(); box.show();
fix_notification_height(); fix_notification_height();
@@ -52,24 +57,26 @@ $(document).ready(function(){
} }
}); });
$(this).bind('mousedown',function(){ $(this).bind('mousedown', function () {
var not_trigger = $('#notification_trigger'); var not_trigger = $('#notification_trigger');
if(not_trigger.hasClass('open')) if (not_trigger.hasClass('open'))
not_trigger.trigger('click'); not_trigger.trigger('click');
}); });
$('#notification_box').bind('mousedown',function(event){ $('#notification_box').bind('mousedown', function (event) {
event.stopPropagation(); event.stopPropagation();
}); });
$('#notification_box div.notification').live('mouseover',function(){$(this).addClass('hover');}); $('#notification_box div.notification').live('mouseover', function () {
$('#notification_box div.notification').live('mouseout',function(){$(this).removeClass('hover');}); $(this).addClass('hover');
});
$('#notification_box div.notification').live('mouseout', function () {
$(this).removeClass('hover');
});
$(this).bind('mousedown', function () {
$(this).bind('mousedown',function(){
var box = $('#notification_box'); var box = $('#notification_box');
if($('#notification_trigger').hasClass('open')) if ($('#notification_trigger').hasClass('open')) {
{
box.hide(); box.hide();
$('#notification_trigger').removeClass('open'); $('#notification_trigger').removeClass('open');
clear_notifications(); clear_notifications();
@@ -82,12 +89,10 @@ $(document).ready(function(){
}); });
function login(what) function login(what) {
{
if (confirm(language.confirmRedirectAuth)) { if (confirm(language.confirmRedirectAuth)) {
if(what != undefined) if (what != undefined) {
{ EcrireCookie('last_act', what, null, '/');
EcrireCookie('last_act',what,null,'/');
} }
self.location.replace('/login/?postlog=1'); self.location.replace('/login/?postlog=1');
} }
@@ -95,127 +100,119 @@ function login(what)
} }
function EcrireCookie(nom, valeur) function EcrireCookie(nom, valeur) {
{ var argv = EcrireCookie.arguments;
var argv=EcrireCookie.arguments; var argc = EcrireCookie.arguments.length;
var argc=EcrireCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null;
var expires=(argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : null;
var path=(argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null;
var domain=(argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false;
var secure=(argc > 5) ? argv[5] : false; var cook = nom + "=" + escape(valeur) +
var cook = nom+"="+escape(valeur)+ ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) +
((expires===null) ? "" : ("; expires="+expires.toGMTString()))+ ((path === null) ? "" : ("; path=" + path)) +
((path===null) ? "" : ("; path="+path))+ ((domain === null) ? "" : ("; domain=" + domain)) +
((domain===null) ? "" : ("; domain="+domain))+ ((secure === true) ? "; secure" : "");
((secure===true) ? "; secure" : "");
document.cookie = cook; document.cookie = cook;
} }
function fix_notification_height() function fix_notification_height() {
{
var box = $('#notification_box'); var box = $('#notification_box');
var not = $('.notification',box); var not = $('.notification', box);
var n = not.length; var n = not.length;
var not_t = $('.notification_title',box); var not_t = $('.notification_title', box);
var n_t = not_t.length; var n_t = not_t.length;
h = not.outerHeight() * n + not_t.outerHeight() * n_t; h = not.outerHeight() * n + not_t.outerHeight() * n_t;
h = h > 350 ? 350 : h; h = h > 350 ? 350 : h;
box.stop().animate({height:h}); box.stop().animate({height: h});
} }
function set_notif_position() function set_notif_position() {
{
var trigger = $('#notification_trigger'); var trigger = $('#notification_trigger');
if(trigger.length === 0) if (trigger.length === 0)
return; return;
$('#notification_box').css({ $('#notification_box').css({
'left':Math.round(trigger.offset().left - 1) 'left': Math.round(trigger.offset().left - 1)
}); });
} }
$(window).bind('resize', function(){ $(window).bind('resize', function () {
set_notif_position(); set_notif_position();
}); });
function print_notifications(page) function print_notifications(page) {
{
page = parseInt(page); page = parseInt(page);
var buttons = {}; var buttons = {};
buttons[language.fermer] = function(){ buttons[language.fermer] = function () {
$('#notifications-dialog').dialog('close'); $('#notifications-dialog').dialog('close');
}; };
if($('#notifications-dialog').length === 0) if ($('#notifications-dialog').length === 0)
$('body').append('<div id="notifications-dialog" class="loading"></div>'); $('body').append('<div id="notifications-dialog" class="loading"></div>');
$('#notifications-dialog') $('#notifications-dialog')
.dialog({ .dialog({
title:language.notifications, title: language.notifications,
autoOpen:false, autoOpen: false,
closeOnEscape:true, closeOnEscape: true,
resizable:false, resizable: false,
draggable:false, draggable: false,
modal:true, modal: true,
width:500, width: 500,
height:400, height: 400,
overlay: { overlay: {
backgroundColor: '#000', backgroundColor: '#000',
opacity: 0.7 opacity: 0.7
}, },
close:function(event,ui) close: function (event, ui) {
{
$('#notifications-dialog').dialog('destroy').remove(); $('#notifications-dialog').dialog('destroy').remove();
} }
}).dialog('option','buttons',buttons) }).dialog('option', 'buttons', buttons)
.dialog('open'); .dialog('open');
$.ajax({ $.ajax({
type: "GET", type: "GET",
url: "/user/notifications/", url: "/user/notifications/",
dataType : 'json', dataType: 'json',
data: { data: {
page:page page: page
}, },
error: function(data){ error: function (data) {
$('#notifications-dialog').removeClass('loading'); $('#notifications-dialog').removeClass('loading');
}, },
timeout: function(data){ timeout: function (data) {
$('#notifications-dialog').removeClass('loading'); $('#notifications-dialog').removeClass('loading');
}, },
success: function(data){ success: function (data) {
$('#notifications-dialog').removeClass('loading'); $('#notifications-dialog').removeClass('loading');
var cont = $('#notifications-dialog'); var cont = $('#notifications-dialog');
if(page === 0) if (page === 0)
cont.empty(); cont.empty();
else else
$('.notification_next',cont).remove(); $('.notification_next', cont).remove();
for (i in data.notifications) for (i in data.notifications) {
{ var id = 'notif_date_' + i;
var id = 'notif_date_'+i; var date_cont = $('#' + id);
var date_cont = $('#'+id); if (date_cont.length === 0) {
if(date_cont.length === 0) cont.append('<div id="' + id + '"><div class="notification_title">' + data.notifications[i].display + '</div></div>');
{ date_cont = $('#' + id);
cont.append('<div id="'+id+'"><div class="notification_title">'+data.notifications[i].display+'</div></div>');
date_cont = $('#'+id);
} }
for (j in data.notifications[i].notifications) for (j in data.notifications[i].notifications) {
{
var loc_dat = data.notifications[i].notifications[j]; var loc_dat = data.notifications[i].notifications[j];
var html = '<div style="position:relative;" id="notification_'+loc_dat.id+'" class="notification">'+ var html = '<div style="position:relative;" id="notification_' + loc_dat.id + '" class="notification">' +
'<table style="width:100%;" cellspacing="0" cellpadding="0" border="0"><tr><td style="width:25px;">'+ '<table style="width:100%;" cellspacing="0" cellpadding="0" border="0"><tr><td style="width:25px;">' +
loc_dat.icon+ loc_dat.icon +
'</td><td>'+ '</td><td>' +
'<div style="position:relative;" class="'+loc_dat.classname+'">'+ '<div style="position:relative;" class="' + loc_dat.classname + '">' +
loc_dat.text+' <span class="time">'+loc_dat.time+'</span></div>'+ loc_dat.text + ' <span class="time">' + loc_dat.time + '</span></div>' +
'</td></tr></table>'+ '</td></tr></table>' +
'</div>'; '</div>';
date_cont.append(html); date_cont.append(html);
} }
@@ -223,9 +220,8 @@ function print_notifications(page)
var next_ln = $.trim(data.next); var next_ln = $.trim(data.next);
if(next_ln !== '') if (next_ln !== '') {
{ cont.append('<div class="notification_next">' + next_ln + '</div>');
cont.append('<div class="notification_next">'+next_ln+'</div>');
} }
// '<div style="position:relative;" id="notification_'.$row['id'].'" class="notification '.($row['unread'] == '1' ? 'unread':'').'">'. // '<div style="position:relative;" id="notification_'.$row['id'].'" class="notification '.($row['unread'] == '1' ? 'unread':'').'">'.
@@ -243,11 +239,10 @@ function print_notifications(page)
} }
function read_notifications() function read_notifications() {
{
var notifications = []; var notifications = [];
$('#notification_box .unread').each(function(){ $('#notification_box .unread').each(function () {
notifications.push($(this).attr('id').split('_').pop()); notifications.push($(this).attr('id').split('_').pop());
}); });
@@ -255,180 +250,158 @@ function read_notifications()
type: "POST", type: "POST",
url: "/user/notifications/read/", url: "/user/notifications/read/",
data: { data: {
notifications:notifications.join('_') notifications: notifications.join('_')
}, },
success: function(data){ success: function (data) {
$('#notification_trigger .counter').css('visibility','hidden').empty(); $('#notification_trigger .counter').css('visibility', 'hidden').empty();
} }
}); });
} }
function clear_notifications() function clear_notifications() {
{
var unread = $('#notification_box .unread'); var unread = $('#notification_box .unread');
if(unread.length === 0) if (unread.length === 0)
return; return;
unread.removeClass('unread'); unread.removeClass('unread');
$('#notification_trigger .counter').css('visibility','hidden').empty(); $('#notification_trigger .counter').css('visibility', 'hidden').empty();
} }
function getMyRss(renew) {
function getMyRss(renew)
{
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/prod/prodFeedBack.php", url: "/prod/prodFeedBack.php",
dataType: 'json', dataType: 'json',
data: datas, data: datas,
success: function(data){ success: function (data) {
} }
}); });
} }
function setPref(name,value) function setPref(name, value) {
{ if (jQuery.data['pref_' + name] && jQuery.data['pref_' + name].abort) {
if(jQuery.data['pref_'+name] && jQuery.data['pref_'+name].abort) jQuery.data['pref_' + name].abort();
{ jQuery.data['pref_' + name] = false;
jQuery.data['pref_'+name].abort();
jQuery.data['pref_'+name] = false;
} }
jQuery.data['pref_'+name] = $.ajax({ jQuery.data['pref_' + name] = $.ajax({
type: "POST", type: "POST",
url: "/user/preferences/", url: "/user/preferences/",
data: { data: {
prop:name, prop: name,
value:value value: value
}, },
dataType:'json', dataType: 'json',
timeout: function(){ timeout: function () {
jQuery.data['pref_'+name] = false; jQuery.data['pref_' + name] = false;
}, },
error: function(){ error: function () {
jQuery.data['pref_'+name] = false; jQuery.data['pref_' + name] = false;
}, },
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
jQuery.data['pref_'+name] = false; jQuery.data['pref_' + name] = false;
return; return;
} }
}); });
} }
function infoDialog(el) function infoDialog(el) {
{
$("#DIALOG").attr('title','') $("#DIALOG").attr('title', '')
.empty() .empty()
.append(el.attr('infos')) .append(el.attr('infos'))
.dialog({ .dialog({
autoOpen:false, autoOpen: false,
closeOnEscape:true, closeOnEscape: true,
resizable:false, resizable: false,
draggable:false, draggable: false,
width:600, width: 600,
height:400, height: 400,
modal:true, modal: true,
overlay: { overlay: {
backgroundColor: '#000', backgroundColor: '#000',
opacity: 0.7 opacity: 0.7
} }
}).dialog('open').css({'overflow-x':'auto','overflow-y':'auto'}); }).dialog('open').css({'overflow-x': 'auto', 'overflow-y': 'auto'});
} }
function manageSession(data, showMessages) function manageSession(data, showMessages) {
{ if (typeof(showMessages) == "undefined")
if(typeof(showMessages) == "undefined")
showMessages = false; showMessages = false;
if(data.status == 'disconnected' || data.status == 'session') if (data.status == 'disconnected' || data.status == 'session') {
{
disconnected(); disconnected();
return false; return false;
} }
if(showMessages) if (showMessages) {
{
var box = $('#notification_box'); var box = $('#notification_box');
box.empty().append(data.notifications); box.empty().append(data.notifications);
if(box.is(':visible')) if (box.is(':visible'))
fix_notification_height(); fix_notification_height();
if($('.notification.unread',box).length > 0) if ($('.notification.unread', box).length > 0) {
{ var trigger = $('#notification_trigger');
var trigger = $('#notification_trigger') ; $('.counter', trigger)
$('.counter',trigger)
.empty() .empty()
.append($('.notification.unread',box).length); .append($('.notification.unread', box).length);
$('.counter',trigger).css('visibility','visible'); $('.counter', trigger).css('visibility', 'visible');
} }
else else
$('#notification_trigger .counter').css('visibility','hidden').empty(); $('#notification_trigger .counter').css('visibility', 'hidden').empty();
if(data.changed.length > 0) if (data.changed.length > 0) {
{
var current_open = $('.SSTT.ui-state-active'); var current_open = $('.SSTT.ui-state-active');
var current_sstt = current_open.length > 0 ? current_open.attr('id').split('_').pop() : false; var current_sstt = current_open.length > 0 ? current_open.attr('id').split('_').pop() : false;
var main_open = false; var main_open = false;
for(var i=0; i!=data.changed.length; i++) for (var i = 0; i != data.changed.length; i++) {
{ var sstt = $('#SSTT_' + data.changed[i]);
var sstt = $('#SSTT_'+data.changed[i]); if (sstt.size() === 0) {
if(sstt.size() === 0) if (main_open === false) {
{ $('#baskets .bloc').animate({'top': 30}, function () {
if(main_open === false) $('#baskets .alert_datas_changed:first').show()
{ });
$('#baskets .bloc').animate({'top':30}, function(){$('#baskets .alert_datas_changed:first').show()});
main_open = true; main_open = true;
} }
} }
else else {
{ if (!sstt.hasClass('active'))
if(!sstt.hasClass('active'))
sstt.addClass('unread'); sstt.addClass('unread');
else else {
{ $('.alert_datas_changed', $('#SSTT_content_' + data.changed[i])).show();
$('.alert_datas_changed', $('#SSTT_content_'+data.changed[i])).show();
} }
} }
} }
} }
if('' !== $.trim(data.message)) if ('' !== $.trim(data.message)) {
{ if ($('#MESSAGE').length === 0)
if($('#MESSAGE').length === 0)
$('body').append('<div id="#MESSAGE"></div>'); $('body').append('<div id="#MESSAGE"></div>');
$('#MESSAGE') $('#MESSAGE')
.empty() .empty()
.append(data.message+'<div style="margin:20px;"><input type="checkbox" class="dialog_remove" />'+language.hideMessage+'</div>') .append(data.message + '<div style="margin:20px;"><input type="checkbox" class="dialog_remove" />' + language.hideMessage + '</div>')
.attr('title','Global Message') .attr('title', 'Global Message')
.dialog({ .dialog({
autoOpen:false, autoOpen: false,
closeOnEscape:true, closeOnEscape: true,
resizable:false, resizable: false,
draggable:false, draggable: false,
modal:true, modal: true,
close:function() close: function () {
{ if ($('.dialog_remove:checked', $(this)).length > 0)
if($('.dialog_remove:checked',$(this)).length > 0) setTemporaryPref('message', 0);
setTemporaryPref('message',0);
} }
}) })
.dialog('open'); .dialog('open');
@@ -438,25 +411,23 @@ function manageSession(data, showMessages)
} }
function disconnected() {
function disconnected() showModal('disconnected', {title: 'Disconnection'});
{
showModal('disconnected',{title:'Disconnection'});
} }
function showModal(cas, options){ function showModal(cas, options) {
var content = ''; var content = '';
var callback = null; var callback = null;
var button = { var button = {
"OK": function(e) "OK": function (e) {
{
hideOverlay(3); hideOverlay(3);
$(this).dialog("close"); $(this).dialog("close");
return; return;
}}; }};
var escape = true; var escape = true;
var onClose = function(){}; var onClose = function () {
};
switch (cas) { switch (cas) {
case 'timeout': case 'timeout':
@@ -467,8 +438,10 @@ function showModal(cas, options){
break; break;
case 'disconnected': case 'disconnected':
content = language.serverDisconnected; content = language.serverDisconnected;
escape=false; escape = false;
callback = function(e){ self.location.replace(self.location.href)}; callback = function (e) {
self.location.replace(self.location.href)
};
break; break;
default: default:
break; break;
@@ -479,35 +452,37 @@ function showModal(cas, options){
return; return;
} }
function showOverlay(n,appendto,callback, zIndex){ function showOverlay(n, appendto, callback, zIndex) {
var div ="OVERLAY"; var div = "OVERLAY";
if(typeof(n)!="undefined") if (typeof(n) != "undefined")
div+=n; div += n;
if($('#'+div).length === 0) if ($('#' + div).length === 0) {
{ if (typeof(appendto) == 'undefined')
if(typeof(appendto)=='undefined')
appendto = 'body'; appendto = 'body';
$(appendto).append('<div id="'+div+'" style="display:none;">&nbsp;</div>'); $(appendto).append('<div id="' + div + '" style="display:none;">&nbsp;</div>');
} }
var css = { var css = {
display: 'block', display: 'block',
opacity: 0, opacity: 0,
right:0, right: 0,
bottom:0, bottom: 0,
position:'absolute', position: 'absolute',
top:0, top: 0,
zIndex:zIndex, zIndex: zIndex,
left:0 left: 0
}; };
if(parseInt(zIndex) > 0) if (parseInt(zIndex) > 0)
css['zIndex'] = parseInt(zIndex); css['zIndex'] = parseInt(zIndex);
if(typeof(callback) != 'function') if (typeof(callback) != 'function')
callback = function(){}; callback = function () {
$('#'+div).css(css).addClass('overlay').fadeTo(500, 0.7).bind('click',function(){(callback)();}); };
$('#' + div).css(css).addClass('overlay').fadeTo(500, 0.7).bind('click', function () {
(callback)();
});
if ($.browser.msie && $.browser.version == '6.0') { if ($.browser.msie && $.browser.version == '6.0') {
$('select').css({ $('select').css({
visibility: 'hidden' visibility: 'hidden'
@@ -515,22 +490,22 @@ function showOverlay(n,appendto,callback, zIndex){
} }
} }
function hideDwnl(){ function hideDwnl() {
hideOverlay(2); hideOverlay(2);
$('#MODALDL').css({ $('#MODALDL').css({
'display': 'none' 'display': 'none'
}); });
} }
function hideOverlay(n){ function hideOverlay(n) {
if ($.browser.msie && $.browser.version == '6.0') { if ($.browser.msie && $.browser.version == '6.0') {
$('select').css({ $('select').css({
visibility: 'visible' visibility: 'visible'
}); });
} }
var div = "OVERLAY"; var div = "OVERLAY";
if(typeof(n)!="undefined") if (typeof(n) != "undefined")
div+=n; div += n;
$('#'+div).hide().remove(); $('#' + div).hide().remove();
} }

View File

@@ -1,145 +1,136 @@
(function( $ ){ (function ($) {
var methods = { var methods = {
init : function( options ) { init: function (options) {
var settings = { var settings = {
'zoomable' : false, 'zoomable': false,
'display_full_screen' : false 'display_full_screen': false
}; };
return this.each(function() { return this.each(function () {
var $this = $(this), data = $(this).data('image_enhance'); var $this = $(this), data = $(this).data('image_enhance');
if ( ! data ) if (!data) {
{ if (options) {
if ( options ) { $.extend(settings, options);
$.extend( settings, options );
} }
var wrapper = $('.thumb_wrapper', $(this)); var wrapper = $('.thumb_wrapper', $(this));
var $image =$('img', $this); var $image = $('img', $this);
wrapper.css('position','relative'); wrapper.css('position', 'relative');
reset_position($this); reset_position($this);
if(settings.display_full_screen) if (settings.display_full_screen) {
{
$image.parent() $image.parent()
.append('<div class="image_enhance_titlebar" style="display:none;">\n\ .append('<div class="image_enhance_titlebar" style="display:none;">\n\
<div class="image_enhance_title_options"><span class="full"><img src="/skins/icons/fullscreen.gif" /></span></div>\n\ <div class="image_enhance_title_options"><span class="full"><img src="/skins/icons/fullscreen.gif" /></span></div>\n\
<div class="image_enhance_title_bg"></div></div>'); <div class="image_enhance_title_bg"></div></div>');
var $titlebar = $('.image_enhance_titlebar',$this); var $titlebar = $('.image_enhance_titlebar', $this);
$('.image_enhance_title_bg',$titlebar).css('opacity',0.5); $('.image_enhance_title_bg', $titlebar).css('opacity', 0.5);
$image.parent() $image.parent()
.bind('mouseover.image_enhance', function(){ .bind('mouseover.image_enhance', function () {
$titlebar.stop().show().animate({ $titlebar.stop().show().animate({
'height':28 'height': 28
}, 150); }, 150);
}) })
.bind('mouseout.image_enhance', function(){ .bind('mouseout.image_enhance', function () {
$titlebar.stop().animate({ $titlebar.stop().animate({
'height':0 'height': 0
}, 150, function(){ }, 150, function () {
$titlebar.hide() $titlebar.hide()
}); });
}); });
$('.image_enhance_titlebar .full', wrapper).bind('click.image_enhance', function(){ $('.image_enhance_titlebar .full', wrapper).bind('click.image_enhance', function () {
$('body').append('<div class="image_enhance_theatre">\n\ $('body').append('<div class="image_enhance_theatre">\n\
\n\ \n\
<div class="image_enhance_theatre_closer_wrapper"><span class="closer">close</span></div>\n\ <div class="image_enhance_theatre_closer_wrapper"><span class="closer">close</span></div>\n\
<img style="width:'+image_width+'px;height:'+image_height+'" src="'+$image.attr('src')+'"/>\n\ <img style="width:' + image_width + 'px;height:' + image_height + '" src="' + $image.attr('src') + '"/>\n\
</div>'); </div>');
var $theatre = $('.image_enhance_theatre'); var $theatre = $('.image_enhance_theatre');
var $theatre_img = $('img', $theatre); var $theatre_img = $('img', $theatre);
$(window).bind('resize.image_enhance dblclick.image_enhance',function(event){ $(window).bind('resize.image_enhance dblclick.image_enhance', function (event) {
if(event.type == 'dblclick') if (event.type == 'dblclick') {
{
$theatre_img.removeClass('zoomed'); $theatre_img.removeClass('zoomed');
} }
else else {
{ if ($theatre_img.hasClass('zoomed'))
if($theatre_img.hasClass('zoomed'))
return; return;
} }
var datas = calculate_sizes($(this).width(), $(this).height(), image_width, image_height, 80); var datas = calculate_sizes($(this).width(), $(this).height(), image_width, image_height, 80);
$theatre_img.width(datas.width).height(datas.height).css('top',datas.top).css('left',datas.left); $theatre_img.width(datas.width).height(datas.height).css('top', datas.top).css('left', datas.left);
}) })
$(window).trigger('resize.image_enhance'); $(window).trigger('resize.image_enhance');
$('.closer', $theatre).bind('click.image_enhance', function(){ $('.closer', $theatre).bind('click.image_enhance', function () {
$theatre.remove(); $theatre.remove();
}); });
if(typeof $theatre.disableSelection !== 'function' && window.console) if (typeof $theatre.disableSelection !== 'function' && window.console)
console.error('enhanced image require jquery UI\'s disableSelection'); console.error('enhanced image require jquery UI\'s disableSelection');
$('img', $theatre).disableSelection(); $('img', $theatre).disableSelection();
}); });
} }
if(settings.zoomable) if (settings.zoomable) {
{ if (typeof $image.draggable !== 'function' && window.console)
if(typeof $image.draggable !== 'function' && window.console)
console.error('zoomable require jquery UI\'s draggable'); console.error('zoomable require jquery UI\'s draggable');
if($image.attr('ondragstart')) if ($image.attr('ondragstart')) {
{
$image.removeAttr('ondragstart'); $image.removeAttr('ondragstart');
} }
$image.draggable(); $image.draggable();
$image.css({ $image.css({
'max-width':'none', 'max-width': 'none',
'max-height':'none' 'max-height': 'none'
}); });
var image_width = parseInt($('input[name="width"]', $this).val()); var image_width = parseInt($('input[name="width"]', $this).val());
var image_height = parseInt($('input[name="height"]', $this).val()); var image_height = parseInt($('input[name="height"]', $this).val());
var ratio = image_width / image_height; var ratio = image_width / image_height;
$this.bind('mousewheel',function(event, delta){ $this.bind('mousewheel',function (event, delta) {
$image.addClass('zoomed'); $image.addClass('zoomed');
if(delta > 0) if (delta > 0) {
{
event.stopPropagation(); event.stopPropagation();
zoomPreview(true, ratio, $image, $(this)); zoomPreview(true, ratio, $image, $(this));
} }
else else {
{
event.stopPropagation(); event.stopPropagation();
zoomPreview(false, ratio, $image, $(this)); zoomPreview(false, ratio, $image, $(this));
} }
return false; return false;
}).bind('dblclick', function(event){ }).bind('dblclick', function (event) {
reset_position($this); reset_position($this);
}); });
} }
$(this).data('image_enhance', { $(this).data('image_enhance', {
width:image_width, width: image_width,
height:image_height height: image_height
}); });
} }
}); });
}, },
destroy : function( ) { destroy: function () {
return this.each(function() { return this.each(function () {
$(this).data('image_enhance', null); $(this).data('image_enhance', null);
$('.image_enhance_titlebar, .image_enhance_theatre',this).remove(); $('.image_enhance_titlebar, .image_enhance_theatre', this).remove();
}); });
} }
}; };
function zoomPreview(bool, ratio, $img, $container) function zoomPreview(bool, ratio, $img, $container) {
{ if ($img.length === 0)
if($img.length === 0)
return; return;
var t1 = parseInt($img.css('top')); var t1 = parseInt($img.css('top'));
@@ -147,19 +138,17 @@
var w1 = $img.width(); var w1 = $img.width();
var h1 = $img.height(); var h1 = $img.height();
var w2,t2; var w2, t2;
if(bool) if (bool) {
{ if ((w1 * 1.08) < 32767) {
if((w1 * 1.08) < 32767) {
w2 = w1 * 1.08; w2 = w1 * 1.08;
} else { } else {
w2 = w1; w2 = w1;
} }
} }
else else {
{ if ((w1 / 1.08) > 20) {
if((w1 / 1.08) > 20) {
w2 = w1 / 1.08; w2 = w1 / 1.08;
} else { } else {
w2 = w1; w2 = w1;
@@ -171,11 +160,11 @@
h2 = Math.round(w2 / ratio); h2 = Math.round(w2 / ratio);
w2 = Math.round(w2); w2 = Math.round(w2);
t2 = Math.round(t1 - (h2 - h1) / 2)+'px'; t2 = Math.round(t1 - (h2 - h1) / 2) + 'px';
var l2 = Math.round(l1 - (w2 - w1) / 2)+'px'; var l2 = Math.round(l1 - (w2 - w1) / 2) + 'px';
var wPreview = $container.width()/2; var wPreview = $container.width() / 2;
var hPreview = $container.height()/2; var hPreview = $container.height() / 2;
var nt = Math.round((h2 / h1) * (t1 - hPreview) + hPreview); var nt = Math.round((h2 / h1) * (t1 - hPreview) + hPreview);
var nl = Math.round(((w2 / w1) * (l1 - wPreview)) + wPreview); var nl = Math.round(((w2 / w1) * (l1 - wPreview)) + wPreview);
@@ -186,64 +175,60 @@
}).width(w2).height(h2); }).width(w2).height(h2);
} }
function calculate_sizes(window_width, window_height,image_width, image_height, border) function calculate_sizes(window_width, window_height, image_width, image_height, border) {
{ if (typeof border !== 'number')
if(typeof border !== 'number')
border = 0; border = 0;
var width, height; var width, height;
var ratio_display = window_width / window_height; var ratio_display = window_width / window_height;
var ratio_image = image_width / image_height; var ratio_image = image_width / image_height;
if(ratio_image > ratio_display) if (ratio_image > ratio_display) {
{
width = window_width - border; width = window_width - border;
height = Math.round(width / ratio_image); height = Math.round(width / ratio_image);
} }
else else {
{
height = window_height - border; height = window_height - border;
width = Math.round(height * ratio_image); width = Math.round(height * ratio_image);
} }
var top = Math.round((window_height - height) / 2); var top = Math.round((window_height - height) / 2);
var left = Math.round((window_width - width )/2); var left = Math.round((window_width - width ) / 2);
return { return {
top:top, top: top,
left:left, left: left,
width:width, width: width,
height:height height: height
}; };
} }
function reset_position($this) function reset_position($this) {
{
var display_width = $this.width(); var display_width = $this.width();
var display_height = $this.height(); var display_height = $this.height();
var image_width = parseInt($('input[name="width"]', $this).val()); var image_width = parseInt($('input[name="width"]', $this).val());
var image_height = parseInt($('input[name="height"]', $this).val()); var image_height = parseInt($('input[name="height"]', $this).val());
var datas = calculate_sizes(display_width, display_height, image_width, image_height); var datas = calculate_sizes(display_width, display_height, image_width, image_height);
var $image =$('img', $this); var $image = $('img', $this);
var top = Math.round((display_height - datas.height) / 2)+'px'; var top = Math.round((display_height - datas.height) / 2) + 'px';
var left = Math.round((display_width - datas.width) / 2)+'px'; var left = Math.round((display_width - datas.width) / 2) + 'px';
$image.width(datas.width).height(datas.height).css({top:top, left:left}); $image.width(datas.width).height(datas.height).css({top: top, left: left});
return; return;
} }
$.fn.image_enhance = function(method) { $.fn.image_enhance = function (method) {
if ( methods[method] ) { if (methods[method]) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if ( typeof method === 'object' || ! method ) { } else if (typeof method === 'object' || !method) {
return methods.init.apply( this, arguments ); return methods.init.apply(this, arguments);
} else { } else {
$.error( 'Method ' + method + ' does not exist on jQuery.image_enhance' ); $.error('Method ' + method + ' does not exist on jQuery.image_enhance');
} }
}; };
})( jQuery ); })(jQuery);

View File

@@ -1,26 +1,22 @@
function is_ctrl_key(event) {
if (event.altKey)
function is_ctrl_key(event)
{
if(event.altKey)
return true; return true;
if(event.ctrlKey) if (event.ctrlKey)
return true; return true;
if(event.metaKey) // apple key opera if (event.metaKey) // apple key opera
return true; return true;
if(event.keyCode == '17') // apple key opera if (event.keyCode == '17') // apple key opera
return true; return true;
if(event.keyCode == '224') // apple key mozilla if (event.keyCode == '224') // apple key mozilla
return true; return true;
if(event.keyCode == '91') // apple key safari if (event.keyCode == '91') // apple key safari
return true; return true;
return false; return false;
} }
function is_shift_key(event) function is_shift_key(event) {
{ if (event.shiftKey)
if(event.shiftKey)
return true; return true;
return false; return false;
} }

View File

@@ -1,29 +1,27 @@
(function($){ (function ($) {
$.fn.nicoslider = function(options) $.fn.nicoslider = function (options) {
{
var defaults = { var defaults = {
start : 0, start: 0,
color : '#F6F2F1', color: '#F6F2F1',
sliderHeight : false sliderHeight: false
}; };
var opts = $.extend({}, $.fn.nicoslider.defaults,defaults, options); var opts = $.extend({}, $.fn.nicoslider.defaults, defaults, options);
return this.each(function(){ return this.each(function () {
new nicoslide(this, opts); new nicoslide(this, opts);
}); });
}; };
var nicoslide = function(slider, o) var nicoslide = function (slider, o) {
{
var $slider = $(slider); var $slider = $(slider);
$sliderWidth = $slider.parent().innerWidth(); $sliderWidth = $slider.parent().innerWidth();
$sliderCss = { $sliderCss = {
'width':$sliderWidth, 'width': $sliderWidth,
'background-color':o.color 'background-color': o.color
}; };
$slider.css($sliderCss); $slider.css($sliderCss);
@@ -32,36 +30,34 @@
var ulWidth = 0; var ulWidth = 0;
var liHeight = 0; var liHeight = 0;
$slider.find("li").each(function(){ $slider.find("li").each(function () {
ulWidth += $(this).width() + 5; ulWidth += $(this).width() + 5;
ulWidth += parseInt($(this).css("padding-left")); ulWidth += parseInt($(this).css("padding-left"));
ulWidth += parseInt($(this).css("padding-right")); ulWidth += parseInt($(this).css("padding-right"));
ulWidth += parseInt($(this).css("margin-left")); ulWidth += parseInt($(this).css("margin-left"));
ulWidth += parseInt($(this).css("margin-right")); ulWidth += parseInt($(this).css("margin-right"));
liHeight = Math.max(liHeight,$(this).outerHeight()); liHeight = Math.max(liHeight, $(this).outerHeight());
}); });
//5 % of slider width //5 % of slider width
$scrollWidth = Math.round(parseInt($sliderWidth) * parseFloat("0.05")); $scrollWidth = Math.round(parseInt($sliderWidth) * parseFloat("0.05"));
//min 30 px; //min 30 px;
if($scrollWidth < 30) if ($scrollWidth < 30) {
{
$scrollWidth = 30; $scrollWidth = 30;
} }
var $wrapperWidth = Math.round(parseInt($sliderWidth) - ( 2 * $scrollWidth )); var $wrapperWidth = Math.round(parseInt($sliderWidth) - ( 2 * $scrollWidth ));
if(ulWidth > $wrapperWidth) if (ulWidth > $wrapperWidth) {
{
ul.wrapAll("<div class='wrapper'></div>"); ul.wrapAll("<div class='wrapper'></div>");
$wrapper = $slider.find(".wrapper"); $wrapper = $slider.find(".wrapper");
$ulHeight = ul.height(); $ulHeight = ul.height();
$wrapper.width($wrapperWidth); $wrapper.width($wrapperWidth);
$wrapper.height($ulHeight); $wrapper.height($ulHeight);
$wrapperCss= { $wrapperCss = {
'overflow':'hidden', 'overflow': 'hidden',
'float':'left', 'float': 'left',
'position':'relative' 'position': 'relative'
}; };
$wrapper.css($wrapperCss); $wrapper.css($wrapperCss);
@@ -79,19 +75,19 @@
$("div.rb").css('float', 'right'); $("div.rb").css('float', 'right');
rightCss = { rightCss = {
'width' : $scrollWidth - ($wrapper.outerWidth(true) - $wrapper.innerWidth()), 'width': $scrollWidth - ($wrapper.outerWidth(true) - $wrapper.innerWidth()),
'height' : liHeight + 5, 'height': liHeight + 5,
'float' : 'right', 'float': 'right',
'background-color' : o.color, 'background-color': o.color,
'cursor': 'pointer', 'cursor': 'pointer',
' user-select': 'none' ' user-select': 'none'
}; };
leftCss = { leftCss = {
'width' : $scrollWidth - ($wrapper.outerWidth(true) - $wrapper.innerWidth()), 'width': $scrollWidth - ($wrapper.outerWidth(true) - $wrapper.innerWidth()),
'height' : liHeight + 5, 'height': liHeight + 5,
'float' : 'left', 'float': 'left',
'background-color' : o.color, 'background-color': o.color,
'cursor': 'pointer', 'cursor': 'pointer',
' user-select': 'none' ' user-select': 'none'
}; };
@@ -108,13 +104,12 @@
//scroll a droite //scroll a droite
rightScroll.bind("click", function(e){ rightScroll.bind("click", function (e) {
var x = e.pageX - ($(this).offset().left); var x = e.pageX - ($(this).offset().left);
scrollXpos = Math.round((x / rightScrollWidth) * scrollStepSpeed); scrollXpos = Math.round((x / rightScrollWidth) * scrollStepSpeed);
shift += (scrollXpos * speed); shift += (scrollXpos * speed);
if(shift > (ulWidth - $wrapperWidth) + 50) if (shift > (ulWidth - $wrapperWidth) + 50) {
{
shift = (ulWidth - $wrapperWidth) + 50; shift = (ulWidth - $wrapperWidth) + 50;
} }
ul.animate({ ul.animate({
@@ -123,14 +118,13 @@
}); });
//scroll a gauche //scroll a gauche
leftScroll.bind("click", function(e){ leftScroll.bind("click", function (e) {
var x = $(this).innerWidth() - (e.pageX - $(this).offset().left); var x = $(this).innerWidth() - (e.pageX - $(this).offset().left);
scrollXpos = Math.round((x / leftScrollWidth) * scrollStepSpeed); scrollXpos = Math.round((x / leftScrollWidth) * scrollStepSpeed);
shift -= (scrollXpos * speed); shift -= (scrollXpos * speed);
if(shift < 0) if (shift < 0) {
{
shift = 0; shift = 0;
} }

View File

@@ -1,12 +1,15 @@
$(document).ready(function(){ $(document).ready(function () {
$('#tabs').tabs(); $('#tabs').tabs();
$('input.input-button').hover( $('input.input-button').hover(
function(){parent.$(this).addClass('hover');}, function () {
function(){parent.$(this).removeClass('hover');} parent.$(this).addClass('hover');
},
function () {
parent.$(this).removeClass('hover');
}
); );
$(this).bind('keydown',function(event){ $(this).bind('keydown', function (event) {
switch(event.keyCode) switch (event.keyCode) {
{
case 27: case 27:
parent.hideDwnl(); parent.hideDwnl();
break; break;

View File

@@ -1,14 +1,13 @@
var prevAjax,prevAjaxrunning; var prevAjax, prevAjaxrunning;
prevAjaxrunning = false; prevAjaxrunning = false;
p4.slideShow = false; p4.slideShow = false;
$(document).ready(function(){ $(document).ready(function () {
$('#PREVIEWIMGDESC').tabs(); $('#PREVIEWIMGDESC').tabs();
}); });
function getNewVideoToken(lst, obj) function getNewVideoToken(lst, obj) {
{
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "../prod/records/renew-url/", url: "../prod/records/renew-url/",
@@ -16,11 +15,11 @@ function getNewVideoToken(lst, obj)
data: { data: {
lst: lst lst: lst
}, },
success: function(data){ success: function (data) {
if(!data[lst]) if (!data[lst])
return; return;
obj.unload(); obj.unload();
obj.setClip({url:data[lst]}); obj.setClip({url: data[lst]});
obj.play(); obj.play();
return; return;
} }
@@ -28,7 +27,7 @@ function getNewVideoToken(lst, obj)
}); });
} }
function openPreview(env, pos, contId, reload){ function openPreview(env, pos, contId, reload) {
if (contId == undefined) if (contId == undefined)
contId = ''; contId = '';
@@ -47,8 +46,7 @@ function openPreview(env, pos, contId, reload){
'display': 'block', 'display': 'block',
'opacity': 0 'opacity': 0
}).fadeTo(500, 1); }).fadeTo(500, 1);
}else } else {
{
$('#PREVIEWBOX').css({ $('#PREVIEWBOX').css({
'display': 'block', 'display': 'block',
'opacity': 1 'opacity': 1
@@ -58,12 +56,12 @@ function openPreview(env, pos, contId, reload){
p4.preview.nCurrent = 5; p4.preview.nCurrent = 5;
$('#PREVIEWCURRENT, #PREVIEWOTHERSINNER, #SPANTITLE').empty(); $('#PREVIEWCURRENT, #PREVIEWOTHERSINNER, #SPANTITLE').empty();
resizePreview(); resizePreview();
if(env == 'BASK') if (env == 'BASK')
roll = 1; roll = 1;
} }
if(reload === true) if (reload === true)
roll = 1; roll = 1;
@@ -85,37 +83,36 @@ function openPreview(env, pos, contId, reload){
pos: pos, pos: pos,
cont: contId, cont: contId,
roll: roll, roll: roll,
options_serial:options_serial, options_serial: options_serial,
query:query query: query
}, },
beforeSend: function(){ beforeSend: function () {
if (prevAjaxrunning) if (prevAjaxrunning)
prevAjax.abort(); prevAjax.abort();
if(env == 'RESULT') if (env == 'RESULT')
$('#current_result_n').empty().append(parseInt(pos)+1); $('#current_result_n').empty().append(parseInt(pos) + 1);
prevAjaxrunning = true; prevAjaxrunning = true;
$('#PREVIEWIMGDESC, #PREVIEWOTHERS').addClass('loading'); $('#PREVIEWIMGDESC, #PREVIEWOTHERS').addClass('loading');
}, },
error: function(data){ error: function (data) {
prevAjaxrunning = false; prevAjaxrunning = false;
$('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading'); $('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
posAsk = null; posAsk = null;
}, },
timeout: function(){ timeout: function () {
prevAjaxrunning = false; prevAjaxrunning = false;
$('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading'); $('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
posAsk = null; posAsk = null;
}, },
success: function(data){ success: function (data) {
cancelPreview(); cancelPreview();
prevAjaxrunning = false; prevAjaxrunning = false;
posAsk = null; posAsk = null;
if(data.error) if (data.error) {
{
$('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading'); $('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
alert(data.error); alert(data.error);
if(justOpen) if (justOpen)
closePreview(); closePreview();
return; return;
} }
@@ -123,20 +120,18 @@ function openPreview(env, pos, contId, reload){
$('#PREVIEWIMGCONT').empty().append(data.html_preview); $('#PREVIEWIMGCONT').empty().append(data.html_preview);
$('#PREVIEWIMGCONT .thumb_wrapper') $('#PREVIEWIMGCONT .thumb_wrapper')
.width('100%').height('100%').image_enhance({zoomable:true}); .width('100%').height('100%').image_enhance({zoomable: true});
$('#PREVIEWIMGDESCINNER').empty().append(data.desc); $('#PREVIEWIMGDESCINNER').empty().append(data.desc);
$('#HISTORICOPS').empty().append(data.history); $('#HISTORICOPS').empty().append(data.history);
$('#popularity').empty().append(data.popularity); $('#popularity').empty().append(data.popularity);
if($('#popularity .bitly_link').length>0) if ($('#popularity .bitly_link').length > 0) {
{
BitlyCB.statsResponse = function(data) { BitlyCB.statsResponse = function (data) {
var result = data.results; var result = data.results;
if( $( '#popularity .bitly_link_' + result.userHash ).length > 0 ) if ($('#popularity .bitly_link_' + result.userHash).length > 0) {
{ $('#popularity .bitly_link_' + result.userHash).append(' (' + result.clicks + ' clicks)');
$( '#popularity .bitly_link_' + result.userHash ).append( ' (' + result.clicks + ' clicks)');
} }
}; };
BitlyClient.stats($('#popularity .bitly_link').html(), 'BitlyCB.statsResponse'); BitlyClient.stats($('#popularity .bitly_link').html(), 'BitlyCB.statsResponse');
@@ -148,36 +143,30 @@ function openPreview(env, pos, contId, reload){
p4.preview.current.tot = data.tot; p4.preview.current.tot = data.tot;
p4.preview.current.pos = data.pos; p4.preview.current.pos = data.pos;
if($('#PREVIEWBOX img.record.zoomable').length > 0) if ($('#PREVIEWBOX img.record.zoomable').length > 0) {
{
$('#PREVIEWBOX img.record.zoomable').draggable(); $('#PREVIEWBOX img.record.zoomable').draggable();
} }
setTitle(data.title); setTitle(data.title);
setPreview(); setPreview();
if(env != 'RESULT') if (env != 'RESULT') {
{
setCurrent(data.current); setCurrent(data.current);
viewCurrent($('#PREVIEWCURRENT li.selected')); viewCurrent($('#PREVIEWCURRENT li.selected'));
} }
else else {
{ if (!justOpen) {
if(!justOpen)
{
$('#PREVIEWCURRENT li.selected').removeClass('selected'); $('#PREVIEWCURRENT li.selected').removeClass('selected');
$('#PREVIEWCURRENTCONT li.current'+pos).addClass('selected'); $('#PREVIEWCURRENTCONT li.current' + pos).addClass('selected');
} }
if(justOpen || ($('#PREVIEWCURRENTCONT li.current'+pos).length === 0) || ($('#PREVIEWCURRENTCONT li:last')[0] == $('#PREVIEWCURRENTCONT li.selected')[0]) || ($('#PREVIEWCURRENTCONT li:first')[0] == $('#PREVIEWCURRENTCONT li.selected')[0])) if (justOpen || ($('#PREVIEWCURRENTCONT li.current' + pos).length === 0) || ($('#PREVIEWCURRENTCONT li:last')[0] == $('#PREVIEWCURRENTCONT li.selected')[0]) || ($('#PREVIEWCURRENTCONT li:first')[0] == $('#PREVIEWCURRENTCONT li.selected')[0])) {
{ getAnswerTrain(pos, data.tools, query, options_serial);
getAnswerTrain(pos, data.tools, query,options_serial);
} }
viewCurrent($('#PREVIEWCURRENT li.selected')); viewCurrent($('#PREVIEWCURRENT li.selected'));
} }
if(env == 'REG' && $('#PREVIEWCURRENT').html() === '') if (env == 'REG' && $('#PREVIEWCURRENT').html() === '') {
{ getRegTrain(contId, pos, data.tools);
getRegTrain(contId,pos,data.tools);
} }
setOthers(data.others); setOthers(data.others);
setTools(data.tools); setTools(data.tools);
@@ -185,7 +174,7 @@ function openPreview(env, pos, contId, reload){
'display': 'none' 'display': 'none'
}); });
$('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading'); $('#PREVIEWIMGDESC, #PREVIEWOTHERS').removeClass('loading');
if(!justOpen || (p4.preview.mode != env)) if (!justOpen || (p4.preview.mode != env))
resizePreview(); resizePreview();
p4.preview.mode = env; p4.preview.mode = env;
@@ -200,11 +189,11 @@ function openPreview(env, pos, contId, reload){
} }
function zoomPreview(bool){ function zoomPreview(bool) {
var el = $('#PREVIEWIMGCONT img.record'); var el = $('#PREVIEWIMGCONT img.record');
if(el.length === 0) if (el.length === 0)
return; return;
var t1 = parseInt(el.css('top')); var t1 = parseInt(el.css('top'));
@@ -212,18 +201,16 @@ function zoomPreview(bool){
var w1 = el.width(); var w1 = el.width();
var h1 = el.height(); var h1 = el.height();
var w2,t2; var w2, t2;
if(bool) if (bool) {
{ if (w1 * 1.08 < 32767)
if(w1 * 1.08 < 32767)
w2 = w1 * 1.08; w2 = w1 * 1.08;
else else
w2 = w1; w2 = w1;
} }
else else {
{ if (w1 / 1.08 > 20)
if(w1 / 1.08 > 20)
w2 = w1 / 1.08; w2 = w1 / 1.08;
else else
w2 = w1; w2 = w1;
@@ -233,11 +220,11 @@ function zoomPreview(bool){
h2 = Math.round(w2 / ratio); h2 = Math.round(w2 / ratio);
w2 = Math.round(w2); w2 = Math.round(w2);
t2 = Math.round(t1 - (h2 - h1) / 2)+'px'; t2 = Math.round(t1 - (h2 - h1) / 2) + 'px';
var l2 = Math.round(l1 - (w2 - w1) / 2)+'px'; var l2 = Math.round(l1 - (w2 - w1) / 2) + 'px';
var wPreview = $('#PREVIEWIMGCONT').width()/2; var wPreview = $('#PREVIEWIMGCONT').width() / 2;
var hPreview = $('#PREVIEWIMGCONT').height()/2; var hPreview = $('#PREVIEWIMGCONT').height() / 2;
var nt = Math.round((h2 / h1) * (t1 - hPreview) + hPreview); var nt = Math.round((h2 / h1) * (t1 - hPreview) + hPreview);
var nl = Math.round(((w2 / w1) * (l1 - wPreview)) + wPreview); var nl = Math.round(((w2 / w1) * (l1 - wPreview)) + wPreview);
@@ -248,19 +235,18 @@ function zoomPreview(bool){
}).width(w2).height(h2); }).width(w2).height(h2);
} }
function getAnswerTrain(pos, tools, query,options_serial) function getAnswerTrain(pos, tools, query, options_serial) {
{
$('#PREVIEWCURRENTCONT').fadeOut('fast'); $('#PREVIEWCURRENTCONT').fadeOut('fast');
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/prod/query/answer-train/", url: "/prod/query/answer-train/",
dataType: 'json', dataType: 'json',
data: { data: {
pos:pos, pos: pos,
options_serial:options_serial, options_serial: options_serial,
query:query query: query
}, },
success: function(data){ success: function (data) {
setCurrent(data.current); setCurrent(data.current);
viewCurrent($('#PREVIEWCURRENT li.selected')); viewCurrent($('#PREVIEWCURRENT li.selected'));
setTools(tools); setTools(tools);
@@ -270,43 +256,42 @@ function getAnswerTrain(pos, tools, query,options_serial)
} }
function getRegTrain(contId,pos,tools) function getRegTrain(contId, pos, tools) {
{
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/prod/query/reg-train/", url: "/prod/query/reg-train/",
dataType: 'json', dataType: 'json',
data: { data: {
cont:contId, cont: contId,
pos:pos pos: pos
}, },
success: function(data){ success: function (data) {
setCurrent(data.current); setCurrent(data.current);
viewCurrent($('#PREVIEWCURRENT li.selected')); viewCurrent($('#PREVIEWCURRENT li.selected'));
if(typeof(tools) != 'undefined') if (typeof(tools) != 'undefined')
setTools(tools); setTools(tools);
return; return;
} }
}); });
} }
function bounce(sbid, term, field){ function bounce(sbid, term, field) {
doThesSearch('T', sbid, term, field); doThesSearch('T', sbid, term, field);
closePreview(); closePreview();
} }
function setTitle(title){ function setTitle(title) {
$('#SPANTITLE').empty().append(title); $('#SPANTITLE').empty().append(title);
} }
function cancelPreview(){ function cancelPreview() {
$('#PREVIEWIMGDESCINNER').empty(); $('#PREVIEWIMGDESCINNER').empty();
$('#PREVIEWIMGCONT').empty(); $('#PREVIEWIMGCONT').empty();
p4.preview.current = false; p4.preview.current = false;
} }
function startSlide(){ function startSlide() {
if (!p4.slideShow) { if (!p4.slideShow) {
p4.slideShow = true; p4.slideShow = true;
} }
@@ -316,8 +301,7 @@ function startSlide(){
$('#start_slide').show(); $('#start_slide').show();
$('#stop_slide').hide(); $('#stop_slide').hide();
} }
if(!p4.preview.open) if (!p4.preview.open) {
{
p4.slideShowCancel = false; p4.slideShowCancel = false;
p4.slideShow = false; p4.slideShow = false;
$('#start_slide').show(); $('#start_slide').show();
@@ -331,7 +315,7 @@ function startSlide(){
} }
} }
function stopSlide(){ function stopSlide() {
p4.slideShowCancel = true; p4.slideShowCancel = true;
$('#start_slide').show(); $('#start_slide').show();
$('#stop_slide').hide(); $('#stop_slide').hide();
@@ -339,7 +323,7 @@ function stopSlide(){
//var posAsk = null; //var posAsk = null;
function getNext(){ function getNext() {
if (p4.preview.mode == 'REG' && parseInt(p4.preview.current.pos) === 0) if (p4.preview.mode == 'REG' && parseInt(p4.preview.current.pos) === 0)
$('#PREVIEWCURRENTCONT li img:first').trigger("click"); $('#PREVIEWCURRENTCONT li img:first').trigger("click");
else { else {
@@ -348,9 +332,8 @@ function getNext(){
posAsk = (posAsk > parseInt(p4.tot) || isNaN(posAsk)) ? 0 : posAsk; posAsk = (posAsk > parseInt(p4.tot) || isNaN(posAsk)) ? 0 : posAsk;
openPreview('RESULT', posAsk); openPreview('RESULT', posAsk);
} }
else else {
{ if (!$('#PREVIEWCURRENT li.selected').is(':last-child'))
if(!$('#PREVIEWCURRENT li.selected').is(':last-child'))
$('#PREVIEWCURRENT li.selected').next().children('img').trigger("click"); $('#PREVIEWCURRENT li.selected').next().children('img').trigger("click");
else else
$('#PREVIEWCURRENT li:first-child').children('img').trigger("click"); $('#PREVIEWCURRENT li:first-child').children('img').trigger("click");
@@ -358,27 +341,25 @@ function getNext(){
} }
} }
function reloadPreview(){ function reloadPreview() {
$('#PREVIEWCURRENT li.selected img').trigger("click"); $('#PREVIEWCURRENT li.selected img').trigger("click");
} }
function getPrevious(){ function getPrevious() {
if (p4.preview.mode == 'RESULT') if (p4.preview.mode == 'RESULT') {
{
posAsk = parseInt(p4.preview.current.pos) - 1; posAsk = parseInt(p4.preview.current.pos) - 1;
posAsk = (posAsk < 0) ? ((parseInt(p4.tot) - 1)) : posAsk; posAsk = (posAsk < 0) ? ((parseInt(p4.tot) - 1)) : posAsk;
openPreview('RESULT', posAsk); openPreview('RESULT', posAsk);
} }
else else {
{ if (!$('#PREVIEWCURRENT li.selected').is(':first-child'))
if(!$('#PREVIEWCURRENT li.selected').is(':first-child'))
$('#PREVIEWCURRENT li.selected').prev().children('img').trigger("click"); $('#PREVIEWCURRENT li.selected').prev().children('img').trigger("click");
else else
$('#PREVIEWCURRENT li:last-child').children('img').trigger("click"); $('#PREVIEWCURRENT li:last-child').children('img').trigger("click");
} }
} }
function setOthers(others){ function setOthers(others) {
$('#PREVIEWOTHERSINNER').empty(); $('#PREVIEWOTHERSINNER').empty();
if (others !== '') { if (others !== '') {
@@ -388,31 +369,29 @@ function setOthers(others){
} }
} }
function setTools(tools){ function setTools(tools) {
$('#PREVIEWTOOL').empty().append(tools); $('#PREVIEWTOOL').empty().append(tools);
if(!p4.slideShowCancel && p4.slideShow) if (!p4.slideShowCancel && p4.slideShow) {
{
$('#start_slide').hide(); $('#start_slide').hide();
$('#stop_slide').show(); $('#stop_slide').show();
}else } else {
{
$('#start_slide').show(); $('#start_slide').show();
$('#stop_slide').hide(); $('#stop_slide').hide();
} }
} }
function setCurrent(current){ function setCurrent(current) {
if (current !== '') { if (current !== '') {
var el = $('#PREVIEWCURRENT'); var el = $('#PREVIEWCURRENT');
el.removeClass('loading').empty().append(current); el.removeClass('loading').empty().append(current);
$('ul',el).width($('li',el).length * 80); $('ul', el).width($('li', el).length * 80);
$('img.prevRegToolTip',el).tooltip(); $('img.prevRegToolTip', el).tooltip();
$.each($('img.openPreview'), function(i, el){ $.each($('img.openPreview'), function (i, el) {
var jsopt = $(el).attr('jsargs').split('|'); var jsopt = $(el).attr('jsargs').split('|');
$(el).removeAttr('jsargs'); $(el).removeAttr('jsargs');
$(el).removeClass('openPreview'); $(el).removeClass('openPreview');
$(el).bind('click', function(){ $(el).bind('click', function () {
viewCurrent($(this).parent()); viewCurrent($(this).parent());
openPreview(jsopt[0], jsopt[1], jsopt[2]); openPreview(jsopt[0], jsopt[1], jsopt[2]);
}); });
@@ -420,23 +399,22 @@ function setCurrent(current){
} }
} }
function viewCurrent(el){ function viewCurrent(el) {
if (el.length === 0) if (el.length === 0) {
{
return; return;
} }
$('#PREVIEWCURRENT li.selected').removeClass('selected'); $('#PREVIEWCURRENT li.selected').removeClass('selected');
el.addClass('selected'); el.addClass('selected');
$('#PREVIEWCURRENTCONT').animate({'scrollLeft':($('#PREVIEWCURRENT li.selected').position().left + $('#PREVIEWCURRENT li.selected').width()/2 - ($('#PREVIEWCURRENTCONT').width() / 2 ))}); $('#PREVIEWCURRENTCONT').animate({'scrollLeft': ($('#PREVIEWCURRENT li.selected').position().left + $('#PREVIEWCURRENT li.selected').width() / 2 - ($('#PREVIEWCURRENTCONT').width() / 2 ))});
return; return;
} }
function setPreview(){ function setPreview() {
if (!p4.preview.current) if (!p4.preview.current)
return; return;
var zoomable = $('img.record.zoomable'); var zoomable = $('img.record.zoomable');
if(zoomable.length > 0 && zoomable.hasClass('zoomed')) if (zoomable.length > 0 && zoomable.hasClass('zoomed'))
return; return;
var h = parseInt(p4.preview.current.height); var h = parseInt(p4.preview.current.height);
@@ -446,14 +424,13 @@ function setPreview(){
// var h = parseInt(p4.preview.current.flashcontent.height); // var h = parseInt(p4.preview.current.flashcontent.height);
// var w = parseInt(p4.preview.current.flashcontent.width); // var w = parseInt(p4.preview.current.flashcontent.width);
// } // }
var t=20; var t = 20;
var de = 0; var de = 0;
var margX = 0; var margX = 0;
var margY = 0; var margY = 0;
if($('#PREVIEWIMGCONT .record_audio').length > 0) if ($('#PREVIEWIMGCONT .record_audio').length > 0) {
{
margY = 100; margY = 100;
de = 60; de = 60;
} }
@@ -491,15 +468,15 @@ function setPreview(){
height: h, height: h,
top: t, top: t,
left: l left: l
}).attr('width',w).attr('height',h); }).attr('width', w).attr('height', h);
} }
function classicMode(){ function classicMode() {
$('#PREVIEWCURRENTCONT').animate({'scrollLeft' : ($('#PREVIEWCURRENT li.selected').position().left - 160)}); $('#PREVIEWCURRENTCONT').animate({'scrollLeft': ($('#PREVIEWCURRENT li.selected').position().left - 160)});
p4.currentViewMode = 'classic'; p4.currentViewMode = 'classic';
} }
function doudouMode(){ function doudouMode() {
$('#PREVIEWCURRENT li').removeClass('see-all'); $('#PREVIEWCURRENT li').removeClass('see-all');
$('#PREVIEWCURRENT ul').width('auto'); $('#PREVIEWCURRENT ul').width('auto');
$('#PREVIEWCURRENTCONT').css({ $('#PREVIEWCURRENTCONT').css({
@@ -509,12 +486,12 @@ function doudouMode(){
viewCurrent($('#PREVIEWCURRENT li.selected')); viewCurrent($('#PREVIEWCURRENT li.selected'));
} }
function closePreview(){ function closePreview() {
p4.preview.open = false; p4.preview.open = false;
hideOverlay(); hideOverlay();
$('#PREVIEWBOX').fadeTo(500, 0); $('#PREVIEWBOX').fadeTo(500, 0);
$('#PREVIEWBOX').queue(function(){ $('#PREVIEWBOX').queue(function () {
$(this).css({ $(this).css({
'display': 'none' 'display': 'none'
}); });

View File

@@ -13,7 +13,7 @@
* http://www.gnu.org/licenses/gpl.html * http://www.gnu.org/licenses/gpl.html
*/ */
(function($) { (function ($) {
// the tooltip element // the tooltip element
var helper = {}, var helper = {},
@@ -28,15 +28,15 @@
$.tooltip = { $.tooltip = {
blocked: false, blocked: false,
ajaxTimeout : false, ajaxTimeout: false,
ajaxRequest : false, ajaxRequest: false,
ajaxEvent : false, ajaxEvent: false,
current: null, current: null,
visible: false, visible: false,
defaults: { defaults: {
delay: 700, delay: 700,
fixable:false, fixable: false,
fixableIndex:100, fixableIndex: 100,
fade: true, fade: true,
showURL: true, showURL: true,
outside: true, outside: true,
@@ -45,27 +45,26 @@
left: 15, left: 15,
id: "tooltip" id: "tooltip"
}, },
block: function() { block: function () {
$.tooltip.blocked = !$.tooltip.blocked; $.tooltip.blocked = !$.tooltip.blocked;
}, },
delayAjax : function(a,b,c) delayAjax: function (a, b, c) {
{
var options_serial = p4.tot_options; var options_serial = p4.tot_options;
var query = p4.tot_query; var query = p4.tot_query;
var datas = { var datas = {
options_serial:options_serial, options_serial: options_serial,
query:query query: query
}; };
$.tooltip.ajaxRequest = $.ajax({ $.tooltip.ajaxRequest = $.ajax({
url: $.tooltip.current.tooltipSrc, url: $.tooltip.current.tooltipSrc,
type:'post', type: 'post',
data:datas, data: datas,
success: function(data) { success: function (data) {
title = data; title = data;
positioning($.tooltip.ajaxEvent); positioning($.tooltip.ajaxEvent);
}, },
"error":function(){ "error": function () {
return; return;
} }
}); });
@@ -73,10 +72,10 @@
}; };
$.fn.extend({ $.fn.extend({
tooltip: function(settings) { tooltip: function (settings) {
settings = $.extend({}, $.tooltip.defaults, settings); settings = $.extend({}, $.tooltip.defaults, settings);
createHelper(settings); createHelper(settings);
return this.each(function() { return this.each(function () {
$.data(this, "tooltip", settings); $.data(this, "tooltip", settings);
// copy tooltip into its own expando and remove the title // copy tooltip into its own expando and remove the title
this.tooltipText = $(this).attr('title'); this.tooltipText = $(this).attr('title');
@@ -94,7 +93,7 @@
.mouseout(hide) .mouseout(hide)
.mousedown(fix); .mousedown(fix);
}, },
fixPNG: IE ? function() { fixPNG: IE ? function () {
return this.each(function () { return this.each(function () {
var image = $(this).css('backgroundImage'); var image = $(this).css('backgroundImage');
if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) { if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
@@ -109,32 +108,32 @@
}); });
} }
}); });
} : function() { } : function () {
return this; return this;
}, },
unfixPNG: IE ? function() { unfixPNG: IE ? function () {
return this.each(function () { return this.each(function () {
$(this).css({ $(this).css({
'filter': '', 'filter': '',
backgroundImage: '' backgroundImage: ''
}); });
}); });
} : function() { } : function () {
return this; return this;
}, },
hideWhenEmpty: function() { hideWhenEmpty: function () {
return this.each(function() { return this.each(function () {
$(this)[ $(this).html() ? "show" : "hide" ](); $(this)[ $(this).html() ? "show" : "hide" ]();
}); });
}, },
url: function() { url: function () {
return this.attr('href') || this.attr('src'); return this.attr('href') || this.attr('src');
} }
}); });
function createHelper(settings) { function createHelper(settings) {
// there can be only one tooltip helper // there can be only one tooltip helper
if( helper.parent ) if (helper.parent)
return; return;
// create the helper, h3 for title, div for url // create the helper, h3 for title, div for url
helper.parent = $('<div id="' + settings.id + '"><div class="body"></div></div>') helper.parent = $('<div id="' + settings.id + '"><div class="body"></div></div>')
@@ -144,7 +143,7 @@
.hide(); .hide();
// apply bgiframe if available // apply bgiframe if available
if ( $.fn.bgiframe ) if ($.fn.bgiframe)
helper.parent.bgiframe(); helper.parent.bgiframe();
// save references to title and url elements // save references to title and url elements
@@ -160,11 +159,11 @@
// main event handler to start showing tooltips // main event handler to start showing tooltips
function handle(event) { function handle(event) {
if($($.tooltip.current).hasClass('SSTT') && $($.tooltip.current).hasClass('ui-state-active')) if ($($.tooltip.current).hasClass('SSTT') && $($.tooltip.current).hasClass('ui-state-active'))
return; return;
// show helper, either with timeout or on instant // show helper, either with timeout or on instant
if( settings(this).delay ) if (settings(this).delay)
tID = setTimeout(visible, settings(this).delay); tID = setTimeout(visible, settings(this).delay);
else else
visible(); visible();
@@ -181,12 +180,12 @@
// save elements title before the tooltip is displayed // save elements title before the tooltip is displayed
function save(event) { function save(event) {
// if this is the current source, or it has no title (occurs with click event), stop // if this is the current source, or it has no title (occurs with click event), stop
if(event.stopPropagation) if (event.stopPropagation)
event.stopPropagation(); event.stopPropagation();
event.cancelBubble = true; event.cancelBubble = true;
if ( $.tooltip.blocked || this == $.tooltip.current || (!this.tooltipText && !this.tooltipSrc && !settings(this).bodyHandler) ) if ($.tooltip.blocked || this == $.tooltip.current || (!this.tooltipText && !this.tooltipSrc && !settings(this).bodyHandler))
return; return;
// save current // save current
@@ -194,28 +193,26 @@
title = this.tooltipText; title = this.tooltipText;
// if element has href or src, add and show it, otherwise hide it // if element has href or src, add and show it, otherwise hide it
if( settings(this).showURL && $(this).url() ) if (settings(this).showURL && $(this).url())
helper.url.html( $(this).url().replace('http://', '') ).show(); helper.url.html($(this).url().replace('http://', '')).show();
else else
helper.url.hide(); helper.url.hide();
// add an optional class for this tip // add an optional class for this tip
// helper.parent.addClass(settings(this).extraClass); // helper.parent.addClass(settings(this).extraClass);
if(this.ajaxLoad) if (this.ajaxLoad) {
{
clearTimeout($.tooltip.ajaxTimeout); clearTimeout($.tooltip.ajaxTimeout);
$.tooltip.ajaxTimeout = setTimeout("$.tooltip.delayAjax()", 300); $.tooltip.ajaxTimeout = setTimeout("$.tooltip.delayAjax()", 300);
$.tooltip.ajaxEvent = event; $.tooltip.ajaxEvent = event;
} }
else else {
{ title = '<div class="popover" style="display:block;position:relative;">' +
title = '<div class="popover" style="display:block;position:relative;">'+ '<div class="arrow"></div>' +
'<div class="arrow"></div>'+ '<div class="popover-inner" style="width:auto;">' +
'<div class="popover-inner" style="width:auto;">'+ '<div class="popover-content">' +
'<div class="popover-content">'+ title +
title+ '</div>' +
'</div>'+ '</div>' +
'</div>'+
'</div>'; '</div>';
positioning.apply(this, arguments); positioning.apply(this, arguments);
@@ -224,16 +221,14 @@
} }
function positioning(event) function positioning(event) {
{
helper.body.html(title); helper.body.html(title);
helper.body.show(); helper.body.show();
$this = $.tooltip.current; $this = $.tooltip.current;
// fix PNG background for IE // fix PNG background for IE
if (settings($this).fixPNG ) if (settings($this).fixPNG)
helper.parent.fixPNG(); helper.parent.fixPNG();
if(settings($this).outside) if (settings($this).outside) {
{
var width = 'auto'; var width = 'auto';
var height = 'auto'; var height = 'auto';
var ratio = 1; var ratio = 1;
@@ -245,53 +240,52 @@
resizeImgTips = true; resizeImgTips = true;
width = parseInt($imgTips[0].style.width); width = parseInt($imgTips[0].style.width);
height = parseInt($imgTips[0].style.height); height = parseInt($imgTips[0].style.height);
ratio = width/height; ratio = width / height;
$imgTips.css({top:'0px',left:'0px'}); $imgTips.css({top: '0px', left: '0px'});
} }
if ($videoTips[0] && $('#' + settings($.tooltip.current).id + ' .noToolTipResize').length === 0) { if ($videoTips[0] && $('#' + settings($.tooltip.current).id + ' .noToolTipResize').length === 0) {
resizeVideoTips = true; resizeVideoTips = true;
width = parseInt($videoTips.attr('width')); width = parseInt($videoTips.attr('width'));
height = parseInt($videoTips.attr('height')); height = parseInt($videoTips.attr('height'));
ratio = width/height; ratio = width / height;
$videoTips.css({top:'0px',left:'0px'}); $videoTips.css({top: '0px', left: '0px'});
} }
var v = viewport(), var v = viewport(),
h = helper.parent; h = helper.parent;
helper.parent.css({ helper.parent.css({
width:width, width: width,
top:0, top: 0,
left:0, left: 0,
visibility:'hidden', visibility: 'hidden',
// visibility:'visible', // visibility:'visible',
display:'block', display: 'block',
height:height height: height
}); });
$(h).width($(h).width()); $(h).width($(h).width());
width = ($(h).width()>(v.x-40))?(v.x-40):$(h).width(); width = ($(h).width() > (v.x - 40)) ? (v.x - 40) : $(h).width();
height = ($(h).height()>(v.y-40))?(v.y-40):$(h).height(); height = ($(h).height() > (v.y - 40)) ? (v.y - 40) : $(h).height();
// $('#' + settings($.tooltip.current).id + ' .thumb_wrapper').width('auto').height('auto'); // $('#' + settings($.tooltip.current).id + ' .thumb_wrapper').width('auto').height('auto');
if($('#' + settings($.tooltip.current).id + ' .audioTips').length > 0) if ($('#' + settings($.tooltip.current).id + ' .audioTips').length > 0) {
{
height = height < 26 ? 26 : height; height = height < 26 ? 26 : height;
} }
$(h).css({ $(h).css({
width:width, width: width,
height:height height: height
}); });
if (event) { if (event) {
var vert, vertS, hor, horS, top, left,ratioH,ratioV; var vert, vertS, hor, horS, top, left, ratioH, ratioV;
// ratio = $(h).width()/$(h).height(); // ratio = $(h).width()/$(h).height();
var ratioSurfaceH; var ratioSurfaceH;
var ratioSurfaceV, wiH,wiV,heH,heV; var ratioSurfaceV, wiH, wiV, heH, heV;
var ratioImage = $(h).width()/$(h).height(); var ratioImage = $(h).width() / $(h).height();
//position de l'image //position de l'image
if ($(event.target).offset().left > (v.x - $(event.target).offset().left - $(event.target).width())) { if ($(event.target).offset().left > (v.x - $(event.target).offset().left - $(event.target).width())) {
@@ -325,66 +319,58 @@
//correction par ratio //correction par ratio
if (resizeImgTips && $('#' + settings($.tooltip.current).id + ' .imgTips')[0]) { if (resizeImgTips && $('#' + settings($.tooltip.current).id + ' .imgTips')[0]) {
if(ratioSurfaceH > ratioImage) if (ratioSurfaceH > ratioImage) {
{ horS = v.y * ratioImage * v.y;
horS = v.y * ratioImage*v.y;
} }
else else {
{ horS = wiH * wiH / ratioImage;
horS = wiH * wiH/ratioImage;
} }
if(ratioSurfaceV > ratioImage) if (ratioSurfaceV > ratioImage) {
{ vertS = heV * ratioImage * heV;
vertS = heV * ratioImage*heV;
} }
else else {
{ vertS = v.x * v.x / ratioImage;
vertS = v.x * v.x/ratioImage;
} }
} }
var zH; var zH;
if((Math.abs(ratioSurfaceV - ratioImage) < Math.abs(ratioSurfaceH - ratioImage))) if ((Math.abs(ratioSurfaceV - ratioImage) < Math.abs(ratioSurfaceH - ratioImage))) {
{
var zL = event.pageX; var zL = event.pageX;
var zW = $(h).width(); var zW = $(h).width();
zH = $(h).height(); zH = $(h).height();
var ETOT = $(event.target).offset().top; var ETOT = $(event.target).offset().top;
var ETH = $(event.target).height(); var ETH = $(event.target).height();
left = (zL - zW/2)<20?20:(((zL + zW/2+20)>v.x)?(v.x-zW-20):(zL -zW/2)); left = (zL - zW / 2) < 20 ? 20 : (((zL + zW / 2 + 20) > v.x) ? (v.x - zW - 20) : (zL - zW / 2));
switch(vert) switch (vert) {
{
case 'haut': case 'haut':
height = (zH>(ETOT-40))?(ETOT-40):zH; height = (zH > (ETOT - 40)) ? (ETOT - 40) : zH;
top = ETOT - height-20; top = ETOT - height - 20;
break; break;
case 'bas': case 'bas':
height = ((v.y-ETH-ETOT-40)>zH)?zH:(v.y-ETH-ETOT-40); height = ((v.y - ETH - ETOT - 40) > zH) ? zH : (v.y - ETH - ETOT - 40);
top = ETOT +ETH+20; top = ETOT + ETH + 20;
break; break;
default: default:
break; break;
} }
} }
else else {
{
// height = ($(h).height()>(v.y-40))?(v.y-40):$(h).height(); // height = ($(h).height()>(v.y-40))?(v.y-40):$(h).height();
zH = $(h).height(); zH = $(h).height();
var zT = event.pageY; var zT = event.pageY;
var EOTL = $(event.target).offset().left; var EOTL = $(event.target).offset().left;
var ETW = $(event.target).width(); var ETW = $(event.target).width();
var zw = $(h).width(); var zw = $(h).width();
top = (zT - zH/2)<20?20:(((zT + zH/2+20)>v.y)?(v.y-zH-20):(zT - zH/2)); top = (zT - zH / 2) < 20 ? 20 : (((zT + zH / 2 + 20) > v.y) ? (v.y - zH - 20) : (zT - zH / 2));
switch(hor) switch (hor) {
{
case 'gauche': case 'gauche':
width = (zw>(EOTL-40))?(EOTL-40):zw; width = (zw > (EOTL - 40)) ? (EOTL - 40) : zw;
left = EOTL - width-20; left = EOTL - width - 20;
break; break;
case 'droite': case 'droite':
width = ((v.x-ETW-EOTL-40)>zw)?zw:(v.x-ETW-EOTL-40); width = ((v.x - ETW - EOTL - 40) > zw) ? zw : (v.x - ETW - EOTL - 40);
left = EOTL +ETW+20; left = EOTL + ETW + 20;
break; break;
default: default:
break; break;
@@ -401,9 +387,9 @@
//si ya une image on re-ajuste au ratio //si ya une image on re-ajuste au ratio
if (resizeImgTips && $('#' + settings($.tooltip.current).id + ' .imgTips')[0]) { if (resizeImgTips && $('#' + settings($.tooltip.current).id + ' .imgTips')[0]) {
if(width == 'auto') if (width == 'auto')
width = $('#' + settings($.tooltip.current).id).width(); width = $('#' + settings($.tooltip.current).id).width();
if(height == 'auto') if (height == 'auto')
height = $('#' + settings($.tooltip.current).id).height(); height = $('#' + settings($.tooltip.current).id).height();
if (ratio > 1) { if (ratio > 1) {
var nh = width / ratio; var nh = width / ratio;
@@ -421,16 +407,13 @@
} }
width = nw; width = nw;
} }
}else } else {
{ if (vertS < horS) {
if(vertS < horS)
{
height = 'auto'; height = 'auto';
} }
} }
if(resizeImgTips) if (resizeImgTips) {
{
var factor = Math.min((width - 45) / width, (height - 75) / height); var factor = Math.min((width - 45) / width, (height - 75) / height);
var imgWidth = Math.round(width * factor); var imgWidth = Math.round(width * factor);
var imgHeight = Math.round(height * factor); var imgHeight = Math.round(height * factor);
@@ -444,8 +427,7 @@
}); });
} }
if(resizeVideoTips) if (resizeVideoTips) {
{
var factor = Math.min((width - 45) / width, (height - 75) / height); var factor = Math.min((width - 45) / width, (height - 75) / height);
var imgWidth = Math.round(width * factor); var imgWidth = Math.round(width * factor);
var imgHeight = Math.round(height * factor); var imgHeight = Math.round(height * factor);
@@ -488,25 +470,23 @@
update(); update();
} }
function fix(event) function fix(event) {
{ if (!settings(this).fixable) {
if(!settings(this).fixable)
{
hide(event); hide(event);
return; return;
} }
event.cancelBubble = true; event.cancelBubble = true;
if(event.stopPropagation) if (event.stopPropagation)
event.stopPropagation(); event.stopPropagation();
showOverlay('_tooltip','body',unfix_tooltip, settings(this).fixableIndex); showOverlay('_tooltip', 'body', unfix_tooltip, settings(this).fixableIndex);
$('#tooltip .tooltip_closer').show().bind('click', unfix_tooltip); $('#tooltip .tooltip_closer').show().bind('click', unfix_tooltip);
$.tooltip.blocked = true; $.tooltip.blocked = true;
} }
function visible(){ function visible() {
$.tooltip.visible = true; $.tooltip.visible = true;
helper.parent.css({ helper.parent.css({
visibility:'visible' visibility: 'visible'
}); });
} }
@@ -517,7 +497,7 @@
*/ */
function update(event) { function update(event) {
if($.tooltip.blocked) if ($.tooltip.blocked)
return; return;
if (event && event.target.tagName == "OPTION") { if (event && event.target.tagName == "OPTION") {
@@ -525,12 +505,12 @@
} }
// stop updating when tracking is disabled and the tooltip is visible // stop updating when tracking is disabled and the tooltip is visible
if ( !track && helper.parent.is(":visible")) { if (!track && helper.parent.is(":visible")) {
$(document.body).unbind('mousemove', update); $(document.body).unbind('mousemove', update);
} }
// if no current element is available, remove this listener // if no current element is available, remove this listener
if( $.tooltip.current === null ) { if ($.tooltip.current === null) {
$(document.body).unbind('mousemove', update); $(document.body).unbind('mousemove', update);
return; return;
} }
@@ -538,8 +518,7 @@
// remove position helper classes // remove position helper classes
helper.parent.removeClass("viewport-right").removeClass("viewport-bottom"); helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
if(!settings($.tooltip.current).outside) if (!settings($.tooltip.current).outside) {
{
var left = helper.parent[0].offsetLeft; var left = helper.parent[0].offsetLeft;
var top = helper.parent[0].offsetTop; var top = helper.parent[0].offsetTop;
helper.parent.width('auto'); helper.parent.width('auto');
@@ -548,7 +527,7 @@
// position the helper 15 pixel to bottom right, starting from mouse position // position the helper 15 pixel to bottom right, starting from mouse position
left = event.pageX + settings($.tooltip.current).left; left = event.pageX + settings($.tooltip.current).left;
top = event.pageY + settings($.tooltip.current).top; top = event.pageY + settings($.tooltip.current).top;
var right='auto'; var right = 'auto';
if (settings($.tooltip.current).positionLeft) { if (settings($.tooltip.current).positionLeft) {
right = $(window).width() - left; right = $(window).width() - left;
left = 'auto'; left = 'auto';
@@ -590,27 +569,26 @@
} }
// hide helper and restore added classes and the title // hide helper and restore added classes and the title
function hide(event) function hide(event) {
{ if ($.tooltip.blocked || !$.tooltip.current)
if($.tooltip.blocked || !$.tooltip.current)
return; return;
// clear timeout if possible // clear timeout if possible
if(tID) if (tID)
clearTimeout(tID); clearTimeout(tID);
// no more current element // no more current element
$.tooltip.visible = false; $.tooltip.visible = false;
var tsettings = settings($.tooltip.current); var tsettings = settings($.tooltip.current);
clearTimeout($.tooltip.ajaxTimeout); clearTimeout($.tooltip.ajaxTimeout);
if($.tooltip.ajaxRequest && $.tooltip.ajaxRequest.abort) if ($.tooltip.ajaxRequest && $.tooltip.ajaxRequest.abort) {
{
$.tooltip.ajaxRequest.abort(); $.tooltip.ajaxRequest.abort();
} }
helper.body.empty(); helper.body.empty();
$.tooltip.current = null; $.tooltip.current = null;
function complete() { function complete() {
helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", ""); helper.parent.removeClass(tsettings.extraClass).hide().css("opacity", "");
} }
if ((!IE || !$.fn.bgiframe) && tsettings.fade) { if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
if (helper.parent.is(':animated')) if (helper.parent.is(':animated'))
helper.parent.stop().fadeTo(tsettings.fade, 0, complete); helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
@@ -619,14 +597,13 @@
} else } else
complete(); complete();
if( tsettings.fixPNG ) if (tsettings.fixPNG)
helper.parent.unfixPNG(); helper.parent.unfixPNG();
} }
})(jQuery); })(jQuery);
function unfix_tooltip() function unfix_tooltip() {
{
$.tooltip.blocked = false; $.tooltip.blocked = false;
$.tooltip.visible = false; $.tooltip.visible = false;
$.tooltip.current = null; $.tooltip.current = null;
@@ -636,9 +613,8 @@ function unfix_tooltip()
} }
$(document).bind('keydown', function(event){ $(document).bind('keydown', function (event) {
if(event.keyCode == 27 && $.tooltip.blocked === true) if (event.keyCode == 27 && $.tooltip.blocked === true) {
{
unfix_tooltip(); unfix_tooltip();
} }
}); });

View File

@@ -1,47 +1,45 @@
(function (window) {
(function( window ) { function checkVocabId(VocabularyId) {
if (typeof VocabularyId === 'undefined')
function checkVocabId(VocabularyId)
{
if(typeof VocabularyId === 'undefined')
VocabularyId = null; VocabularyId = null;
if(VocabularyId === '') if (VocabularyId === '')
VocabularyId = null; VocabularyId = null;
return VocabularyId; return VocabularyId;
} }
var recordFieldValue = function(meta_id, value, VocabularyId) { var recordFieldValue = function (meta_id, value, VocabularyId) {
VocabularyId = checkVocabId(VocabularyId); VocabularyId = checkVocabId(VocabularyId);
this.datas = { this.datas = {
meta_id:meta_id, meta_id: meta_id,
value:value, value: value,
VocabularyId:VocabularyId VocabularyId: VocabularyId
}; };
var $this = this; var $this = this;
}; };
recordFieldValue.prototype = { recordFieldValue.prototype = {
getValue : function() { getValue: function () {
return this.datas.value; return this.datas.value;
}, },
getMetaId : function() { getMetaId: function () {
return this.datas.meta_id; return this.datas.meta_id;
}, },
getVocabularyId : function() { getVocabularyId: function () {
return this.datas.VocabularyId; return this.datas.VocabularyId;
}, },
setValue : function(value, VocabularyId) { setValue: function (value, VocabularyId) {
this.datas.value = value; this.datas.value = value;
this.datas.VocabularyId = checkVocabId(VocabularyId); this.datas.VocabularyId = checkVocabId(VocabularyId);
return this; return this;
}, },
remove : function() { remove: function () {
this.datas.value = ''; this.datas.value = '';
this.datas.VocabularyId = null; this.datas.VocabularyId = null;
@@ -49,23 +47,22 @@
} }
}; };
var databoxField = function(name, label, meta_struct_id, options) { var databoxField = function (name, label, meta_struct_id, options) {
var defaults = { var defaults = {
multi : false, multi: false,
required : false, required: false,
readonly : false, readonly: false,
maxLength : null, maxLength: null,
minLength : null, minLength: null,
type : 'string', type: 'string',
separator : null, separator: null,
vocabularyControl : null, vocabularyControl: null,
vocabularyRestricted : false vocabularyRestricted: false
}, },
options = (typeof options == 'object') ? options : {}; options = (typeof options == 'object') ? options : {};
if(isNaN(meta_struct_id)) if (isNaN(meta_struct_id)) {
{
throw 'meta_struct_id should be a number'; throw 'meta_struct_id should be a number';
} }
@@ -74,93 +71,83 @@
this.meta_struct_id = meta_struct_id; this.meta_struct_id = meta_struct_id;
this.options = jQuery.extend(defaults, options); this.options = jQuery.extend(defaults, options);
if(this.options.multi === true && this.options.separator === null) if (this.options.multi === true && this.options.separator === null) {
{
this.options.separator = ';'; this.options.separator = ';';
} }
}; };
databoxField.prototype = { databoxField.prototype = {
getMetaStructId : function() { getMetaStructId: function () {
return this.meta_struct_id; return this.meta_struct_id;
}, },
getName : function() { getName: function () {
return this.name; return this.name;
}, },
getLabel : function() { getLabel: function () {
return this.label; return this.label;
}, },
isMulti : function() { isMulti: function () {
return this.options.multi; return this.options.multi;
}, },
isRequired : function() { isRequired: function () {
return this.options.required; return this.options.required;
}, },
isReadonly : function() { isReadonly: function () {
return this.options.readonly; return this.options.readonly;
}, },
getMaxLength : function() { getMaxLength: function () {
return this.options.maxLength; return this.options.maxLength;
}, },
getMinLength : function() { getMinLength: function () {
return this.options.minLength; return this.options.minLength;
}, },
getType : function() { getType: function () {
return this.options.type; return this.options.type;
}, },
getSeparator : function() { getSeparator: function () {
return this.options.separator; return this.options.separator;
} }
}; };
var recordField = function(databoxField, arrayValues) { var recordField = function (databoxField, arrayValues) {
this.databoxField = databoxField; this.databoxField = databoxField;
this.options = { this.options = {
dirty : false dirty: false
}; };
this.datas = new Array(); this.datas = new Array();
if(arrayValues instanceof Array) if (arrayValues instanceof Array) {
{ if (arrayValues.length > 1 && !databoxField.isMulti())
if(arrayValues.length > 1 && !databoxField.isMulti())
throw 'You can not add multiple values to a non multi field ' + databoxField.getName(); throw 'You can not add multiple values to a non multi field ' + databoxField.getName();
var first = true; var first = true;
for(v in arrayValues) for (v in arrayValues) {
{ if (typeof arrayValues[v] !== 'object') {
if(typeof arrayValues[v] !== 'object') if (window.console) {
{
if(window.console)
{
console.error('Trying to add a non-recordFieldValue to the field...'); console.error('Trying to add a non-recordFieldValue to the field...');
} }
continue; continue;
} }
if(isNaN(arrayValues[v].getMetaId())) if (isNaN(arrayValues[v].getMetaId())) {
{ if (window.console) {
if(window.console)
{
console.error('Trying to add a recordFieldValue without metaId...'); console.error('Trying to add a recordFieldValue without metaId...');
} }
continue; continue;
} }
if(!first && this.options.multi === false) if (!first && this.options.multi === false) {
{ if (window.console) {
if(window.console)
{
console.error('Trying to add multi values in a non-multi field'); console.error('Trying to add multi values in a non-multi field');
} }
} }
if(window.console) if (window.console) {
{
console.log('adding a value : ', arrayValues[v]); console.log('adding a value : ', arrayValues[v]);
} }
@@ -172,101 +159,81 @@
var $this = this; var $this = this;
} }
recordField.prototype = { recordField.prototype = {
getName : function() { getName: function () {
return this.databoxField.getName(); return this.databoxField.getName();
}, },
getMetaStructId : function() { getMetaStructId: function () {
return this.databoxField.getMetaStructId(); return this.databoxField.getMetaStructId();
}, },
isMulti : function() { isMulti: function () {
return this.databoxField.isMulti(); return this.databoxField.isMulti();
}, },
isRequired : function() { isRequired: function () {
return this.databoxField.isRequired(); return this.databoxField.isRequired();
}, },
isDirty : function() { isDirty: function () {
return this.options.dirty; return this.options.dirty;
}, },
addValue : function(value, merge, VocabularyId) { addValue: function (value, merge, VocabularyId) {
VocabularyId = checkVocabId(VocabularyId); VocabularyId = checkVocabId(VocabularyId);
merge = !!merge; merge = !!merge;
if(this.databoxField.isReadonly()) if (this.databoxField.isReadonly()) {
{ if (window.console) {
if(window.console)
{
console.error('Unable to set a value to a readonly field'); console.error('Unable to set a value to a readonly field');
} }
return; return;
} }
if(window.console) if (window.console) {
{ console.log('adding value ', value, ' vocId : ', VocabularyId, ' ; merge is ', merge);
console.log('adding value ',value,' vocId : ', VocabularyId , ' ; merge is ',merge);
} }
if(this.isMulti()) if (this.isMulti()) {
{ if (!this.hasValue(value, VocabularyId)) {
if(!this.hasValue(value, VocabularyId)) if (window.console) {
{ console.log('adding new multi value ', value);
if(window.console)
{
console.log('adding new multi value ',value);
} }
this.datas.push(new recordFieldValue(null, value, VocabularyId)); this.datas.push(new recordFieldValue(null, value, VocabularyId));
this.options.dirty = true; this.options.dirty = true;
} }
else else {
{ if (window.console) {
if(window.console) console.log('already have ', value);
{
console.log('already have ',value);
} }
} }
} }
else else {
{ if (merge === true && this.isEmpty() === false && VocabularyId === null) {
if(merge === true && this.isEmpty() === false && VocabularyId === null) if (window.console) {
{ console.log('Merging value ', value);
if(window.console)
{
console.log('Merging value ',value);
} }
this.datas[0].setValue(this.datas[0].getValue() + ' ' + value, VocabularyId); this.datas[0].setValue(this.datas[0].getValue() + ' ' + value, VocabularyId);
this.options.dirty = true; this.options.dirty = true;
} }
else else {
{ if (merge === true && this.isEmpty() === false && VocabularyId !== null) {
if(merge === true && this.isEmpty() === false && VocabularyId !== null) if (window.console) {
{
if(window.console)
{
console.error('Cannot merge vocabularies'); console.error('Cannot merge vocabularies');
} }
this.datas[0].setValue(value, VocabularyId); this.datas[0].setValue(value, VocabularyId);
} }
else else {
{
if(!this.hasValue(value, VocabularyId)) if (!this.hasValue(value, VocabularyId)) {
{ if (this.datas.length === 0) {
if(this.datas.length === 0) if (window.console) {
{ console.log('Adding new value ', value);
if(window.console)
{
console.log('Adding new value ',value);
} }
this.datas.push(new recordFieldValue(null, value, VocabularyId)); this.datas.push(new recordFieldValue(null, value, VocabularyId));
} }
else else {
{ if (window.console) {
if(window.console) console.log('Updating value ', value);
{
console.log('Updating value ',value);
} }
this.datas[0].setValue(value, VocabularyId); this.datas[0].setValue(value, VocabularyId);
} }
@@ -278,35 +245,27 @@
return this; return this;
}, },
hasValue : function(value, VocabularyId) { hasValue: function (value, VocabularyId) {
if(typeof value === 'undefined') if (typeof value === 'undefined') {
{ if (window.console) {
if(window.console)
{
console.error('Trying to check the presence of an undefined value'); console.error('Trying to check the presence of an undefined value');
} }
} }
VocabularyId = checkVocabId(VocabularyId); VocabularyId = checkVocabId(VocabularyId);
for(d in this.datas) for (d in this.datas) {
{ if (VocabularyId !== null) {
if(VocabularyId !== null) if (this.datas[d].getVocabularyId() === VocabularyId) {
{ if (window.console) {
if(this.datas[d].getVocabularyId() === VocabularyId)
{
if(window.console)
{
console.log('already got the vocab ID'); console.log('already got the vocab ID');
} }
return true; return true;
} }
} }
else if(this.datas[d].getVocabularyId() === null && this.datas[d].getValue() == value) else if (this.datas[d].getVocabularyId() === null && this.datas[d].getValue() == value) {
{ if (window.console) {
if(window.console)
{
console.log('already got this value'); console.log('already got this value');
} }
return true; return true;
@@ -314,12 +273,10 @@
} }
return false; return false;
}, },
removeValue : function(value, vocabularyId) { removeValue: function (value, vocabularyId) {
if(this.databoxField.isReadonly()) if (this.databoxField.isReadonly()) {
{ if (window.console) {
if(window.console)
{
console.error('Unable to set a value to a readonly field'); console.error('Unable to set a value to a readonly field');
} }
@@ -328,33 +285,25 @@
vocabularyId = checkVocabId(vocabularyId); vocabularyId = checkVocabId(vocabularyId);
if(window.console) if (window.console) {
{
console.log('Try to remove value ', value, vocabularyId, this.datas); console.log('Try to remove value ', value, vocabularyId, this.datas);
} }
for(d in this.datas) for (d in this.datas) {
{ if (window.console) {
if(window.console)
{
console.log('loopin... ', this.datas[d].getValue()); console.log('loopin... ', this.datas[d].getValue());
} }
if(this.datas[d].getVocabularyId() !== null) if (this.datas[d].getVocabularyId() !== null) {
{ if (this.datas[d].getVocabularyId() == vocabularyId) {
if(this.datas[d].getVocabularyId() == vocabularyId) if (window.console) {
{
if(window.console)
{
console.log('Found within the vocab ! removing... '); console.log('Found within the vocab ! removing... ');
} }
this.datas[d].remove(); this.datas[d].remove();
this.options.dirty = true; this.options.dirty = true;
} }
} }
else if(this.datas[d].getValue() == value) else if (this.datas[d].getValue() == value) {
{ if (window.console) {
if(window.console)
{
console.log('Found ! removing... '); console.log('Found ! removing... ');
} }
this.datas[d].remove(); this.datas[d].remove();
@@ -363,60 +312,54 @@
} }
return this; return this;
}, },
isEmpty : function() { isEmpty: function () {
var empty = true; var empty = true;
for(d in this.datas) for (d in this.datas) {
{ if (this.datas[d].getValue() !== '')
if(this.datas[d].getValue() !== '')
empty = false; empty = false;
} }
return empty; return empty;
}, },
empty : function() { empty: function () {
if(this.databoxField.isReadonly()) if (this.databoxField.isReadonly()) {
{ if (window.console) {
if(window.console)
{
console.error('Unable to set a value to a readonly field'); console.error('Unable to set a value to a readonly field');
} }
return; return;
} }
for(d in this.datas) for (d in this.datas) {
{
this.datas[d].remove(); this.datas[d].remove();
this.options.dirty = true; this.options.dirty = true;
} }
return this; return this;
}, },
getValue : function() { getValue: function () {
if(this.isMulti()) if (this.isMulti())
throw 'This field is multi, I can not give you a single value'; throw 'This field is multi, I can not give you a single value';
if(this.isEmpty()) if (this.isEmpty())
return null; return null;
return this.datas[0]; return this.datas[0];
}, },
getValues : function() { getValues: function () {
if(!this.isMulti()) if (!this.isMulti()) {
{
throw 'This field is not multi, I can not give you multiple values'; throw 'This field is not multi, I can not give you multiple values';
} }
if(this.isEmpty()) if (this.isEmpty())
return new Array(); return new Array();
var arrayValues = []; var arrayValues = [];
for(d in this.datas) for (d in this.datas) {
{ if (this.datas[d].getValue() === '')
if(this.datas[d].getValue() === '')
continue; continue;
arrayValues.push(this.datas[d]); arrayValues.push(this.datas[d]);
@@ -424,29 +367,26 @@
return arrayValues; return arrayValues;
}, },
sort : function(algo) { sort: function (algo) {
this.datas.sort(algo); this.datas.sort(algo);
return this; return this;
}, },
getSerializedValues : function() { getSerializedValues: function () {
var arrayValues = []; var arrayValues = [];
var values = this.getValues(); var values = this.getValues();
for(v in values) for (v in values) {
{
arrayValues.push(values[v].getValue()); arrayValues.push(values[v].getValue());
} }
return arrayValues.join(' ' + this.databoxField.getSeparator() + ' '); return arrayValues.join(' ' + this.databoxField.getSeparator() + ' ');
}, },
replaceValue : function(search, replace) { replaceValue: function (search, replace) {
if(this.databoxField.isReadonly()) if (this.databoxField.isReadonly()) {
{ if (window.console) {
if(window.console)
{
console.error('Unable to set a value to a readonly field'); console.error('Unable to set a value to a readonly field');
} }
@@ -455,18 +395,15 @@
var n = 0; var n = 0;
for(d in this.datas) for (d in this.datas) {
{ if (this.datas[d].getVocabularyId() !== null) {
if(this.datas[d].getVocabularyId() !== null)
{
continue; continue;
} }
var value = this.datas[d].getValue(); var value = this.datas[d].getValue();
var replacedValue = value.replace(search, replace); var replacedValue = value.replace(search, replace);
if(value === replacedValue) if (value === replacedValue) {
{
continue; continue;
} }
@@ -474,8 +411,7 @@
this.removeValue(value); this.removeValue(value);
if(!this.hasValue(replacedValue)) if (!this.hasValue(replacedValue)) {
{
this.addValue(replacedValue); this.addValue(replacedValue);
} }
@@ -484,20 +420,18 @@
return n; return n;
}, },
exportDatas : function() { exportDatas: function () {
var returnValue = new Array(); var returnValue = new Array();
for(d in this.datas) for (d in this.datas) {
{
var temp = { var temp = {
meta_id : this.datas[d].getMetaId() ? this.datas[d].getMetaId() : '', meta_id: this.datas[d].getMetaId() ? this.datas[d].getMetaId() : '',
meta_struct_id : this.getMetaStructId(), meta_struct_id: this.getMetaStructId(),
value : this.datas[d].getValue() value: this.datas[d].getValue()
}; };
if(this.datas[d].getVocabularyId()) if (this.datas[d].getVocabularyId()) {
{
temp.vocabularyId = this.datas[d].getVocabularyId(); temp.vocabularyId = this.datas[d].getVocabularyId();
} }
returnValue.push(temp); returnValue.push(temp);

View File

@@ -4,27 +4,25 @@
* *
*/ */
(function( window ) { (function (window) {
var Selectable = function($container, options) { var Selectable = function ($container, options) {
var defaults = { var defaults = {
allow_multiple : false, allow_multiple: false,
selector : '', selector: '',
callbackSelection : null, callbackSelection: null,
selectStart : null, selectStart: null,
selectStop : null, selectStop: null,
limit : null limit: null
}, },
options = (typeof options == 'object') ? options : {}; options = (typeof options == 'object') ? options : {};
var $this = this; var $this = this;
if($container.data('selectionnable')) if ($container.data('selectionnable')) {
{
/* this container is already selectionnable */ /* this container is already selectionnable */
if(window.console) if (window.console) {
{
console.error('Trying to apply new selection to existing one'); console.error('Trying to apply new selection to existing one');
} }
@@ -39,10 +37,9 @@
this.$container.addClass('selectionnable'); this.$container.addClass('selectionnable');
jQuery(this.options.selector, this.$container) jQuery(this.options.selector, this.$container)
.live('click', function(event){ .live('click', function (event) {
if(typeof $this.options.selectStart === 'function') if (typeof $this.options.selectStart === 'function') {
{
$this.options.selectStart(jQuery.extend(jQuery.Event('selectStart'), event), $this); $this.options.selectStart(jQuery.extend(jQuery.Event('selectStart'), event), $this);
} }
@@ -50,15 +47,13 @@
var k = get_value($that, $this); var k = get_value($that, $this);
if(is_shift_key(event) && jQuery('.last_selected', this.$container).filter($this.options.selector).length != 0) if (is_shift_key(event) && jQuery('.last_selected', this.$container).filter($this.options.selector).length != 0) {
{
var lst = jQuery($this.options.selector, this.$container); var lst = jQuery($this.options.selector, this.$container);
var index1 = jQuery.inArray( jQuery('.last_selected', this.$container).filter($this.options.selector)[0], lst ); var index1 = jQuery.inArray(jQuery('.last_selected', this.$container).filter($this.options.selector)[0], lst);
var index2 = jQuery.inArray( $that[0], lst ); var index2 = jQuery.inArray($that[0], lst);
if(index2<index1) if (index2 < index1) {
{
var tmp = index1; var tmp = index1;
index1 = (index2 - 1) < 0 ? index2 : (index2 - 1); index1 = (index2 - 1) < 0 ? index2 : (index2 - 1);
index2 = tmp; index2 = tmp;
@@ -66,21 +61,17 @@
var stopped = false; var stopped = false;
if(index2 != -1 && index1 != -1) if (index2 != -1 && index1 != -1) {
{ var exp = $this.options.selector + ':gt(' + index1 + '):lt(' + (index2 - index1) + ')';
var exp = $this.options.selector + ':gt(' + index1 + '):lt(' + (index2-index1) + ')';
$.each(jQuery(exp, this.$container),function(i,n){ $.each(jQuery(exp, this.$container), function (i, n) {
if(!jQuery(n).hasClass('selected') && stopped === false) if (!jQuery(n).hasClass('selected') && stopped === false) {
{ if (!$this.hasReachLimit()) {
if(!$this.hasReachLimit())
{
var k = get_value(jQuery(n), $this); var k = get_value(jQuery(n), $this);
$this.push(k); $this.push(k);
jQuery(n).addClass('selected'); jQuery(n).addClass('selected');
} }
else else {
{
alert(language.max_record_selected); alert(language.max_record_selected);
stopped = true; stopped = true;
} }
@@ -88,43 +79,33 @@
}); });
} }
if($this.has(k) === false && stopped === false) if ($this.has(k) === false && stopped === false) {
{ if (!$this.hasReachLimit()) {
if(!$this.hasReachLimit())
{
$this.push(k); $this.push(k);
$that.addClass('selected'); $that.addClass('selected');
} }
else else {
{
alert(language.max_record_selected); alert(language.max_record_selected);
} }
} }
} }
else else {
{ if (!is_ctrl_key(event)) {
if(!is_ctrl_key(event))
{
$this.empty().push(k); $this.empty().push(k);
jQuery('.selected', this.$container).filter($this.options.selector).removeClass('selected'); jQuery('.selected', this.$container).filter($this.options.selector).removeClass('selected');
$that.addClass('selected'); $that.addClass('selected');
} }
else else {
{ if ($this.has(k) === true) {
if($this.has(k) === true)
{
$this.remove(k); $this.remove(k);
$that.removeClass('selected'); $that.removeClass('selected');
} }
else else {
{ if (!$this.hasReachLimit()) {
if(!$this.hasReachLimit())
{
$this.push(k); $this.push(k);
$that.addClass('selected'); $that.addClass('selected');
} }
else else {
{
alert(language.max_record_selected); alert(language.max_record_selected);
} }
} }
@@ -135,8 +116,7 @@
$that.addClass('last_selected'); $that.addClass('last_selected');
if(typeof $this.options.selectStop === 'function') if (typeof $this.options.selectStop === 'function') {
{
$this.options.selectStop(jQuery.extend(jQuery.Event('selectStop'), event), $this); $this.options.selectStop(jQuery.extend(jQuery.Event('selectStop'), event), $this);
} }
@@ -147,122 +127,110 @@
return; return;
}; };
function get_value(element, Selectable) function get_value(element, Selectable) {
{ if (typeof Selectable.options.callbackSelection === 'function') {
if(typeof Selectable.options.callbackSelection === 'function')
{
return Selectable.options.callbackSelection(jQuery(element)); return Selectable.options.callbackSelection(jQuery(element));
} }
else else {
{
return jQuery('input[name="id"]', jQuery(element)).val(); return jQuery('input[name="id"]', jQuery(element)).val();
} }
} }
function is_ctrl_key(event) function is_ctrl_key(event) {
{ if (event.altKey)
if(event.altKey)
return true; return true;
if(event.ctrlKey) if (event.ctrlKey)
return true; return true;
if(event.metaKey) // apple key opera if (event.metaKey) // apple key opera
return true; return true;
if(event.keyCode == '17') // apple key opera if (event.keyCode == '17') // apple key opera
return true; return true;
if(event.keyCode == '224') // apple key mozilla if (event.keyCode == '224') // apple key mozilla
return true; return true;
if(event.keyCode == '91') // apple key safari if (event.keyCode == '91') // apple key safari
return true; return true;
return false; return false;
} }
function is_shift_key(event) function is_shift_key(event) {
{ if (event.shiftKey)
if(event.shiftKey)
return true; return true;
return false; return false;
} }
Selectable.prototype = { Selectable.prototype = {
push : function(element){ push: function (element) {
if(this.options.allow_multiple === true || !this.has(element)) if (this.options.allow_multiple === true || !this.has(element)) {
{
this.datas.push(element); this.datas.push(element);
} }
return this; return this;
}, },
hasReachLimit : function() { hasReachLimit: function () {
if(this.options.limit !== null && this.options.limit <= this.datas.length) if (this.options.limit !== null && this.options.limit <= this.datas.length) {
{
return true; return true;
} }
return false; return false;
}, },
remove : function(element){ remove: function (element) {
this.datas = jQuery.grep(this.datas, function(n){ this.datas = jQuery.grep(this.datas, function (n) {
return(n !== element); return(n !== element);
}); });
return this; return this;
}, },
has : function(element){ has: function (element) {
return jQuery.inArray(element,this.datas) >= 0; return jQuery.inArray(element, this.datas) >= 0;
}, },
get : function(){ get: function () {
return this.datas; return this.datas;
}, },
empty : function(){ empty: function () {
var $this = this; var $this = this;
this.datas = new Array(); this.datas = new Array();
jQuery(this.options.selector, this.$container).filter('.selected:visible').removeClass('selected'); jQuery(this.options.selector, this.$container).filter('.selected:visible').removeClass('selected');
if(typeof $this.options.selectStop === 'function') if (typeof $this.options.selectStop === 'function') {
{
$this.options.selectStop(jQuery.Event('selectStop'), $this); $this.options.selectStop(jQuery.Event('selectStop'), $this);
} }
return this; return this;
}, },
length : function(){ length: function () {
return this.datas.length; return this.datas.length;
}, },
size : function(){ size: function () {
return this.datas.length; return this.datas.length;
}, },
serialize : function(separator){ serialize: function (separator) {
separator = separator || ';'; separator = separator || ';';
return this.datas.join(separator); return this.datas.join(separator);
}, },
selectAll : function(){ selectAll: function () {
this.select('*'); this.select('*');
return this; return this;
}, },
select : function(selector){ select: function (selector) {
var $this = this, var $this = this,
stopped = false; stopped = false;
jQuery(this.options.selector, this.$container).filter(selector).not('.selected').filter(':visible').each(function(){ jQuery(this.options.selector, this.$container).filter(selector).not('.selected').filter(':visible').each(function () {
if(!$this.hasReachLimit()) if (!$this.hasReachLimit()) {
{
$this.push(get_value(this, $this)); $this.push(get_value(this, $this));
$(this).addClass('selected'); $(this).addClass('selected');
} }
else else {
{ if (stopped === false) {
if(stopped === false)
{
alert(language.max_record_selected); alert(language.max_record_selected);
} }
stopped = true; stopped = true;
@@ -270,8 +238,7 @@
}); });
if(typeof $this.options.selectStop === 'function') if (typeof $this.options.selectStop === 'function') {
{
$this.options.selectStop(jQuery.Event('selectStop'), $this); $this.options.selectStop(jQuery.Event('selectStop'), $this);
} }

View File

@@ -1,15 +1,14 @@
var p4 = p4 || {}; var p4 = p4 || {};
(function( window, p4, $ ) { (function (window, p4, $) {
var Lists = function() { var Lists = function () {
}; };
var List = function (id) { var List = function (id) {
if(parseInt(id) <= 0) if (parseInt(id) <= 0) {
{
throw 'Invalid list id'; throw 'Invalid list id';
} }
@@ -17,7 +16,7 @@ var p4 = p4 || {};
}; };
Lists.prototype = { Lists.prototype = {
create : function(name, callback){ create: function (name, callback) {
var $this = this; var $this = this;
@@ -25,27 +24,24 @@ var p4 = p4 || {};
type: 'POST', type: 'POST',
url: '/prod/lists/list/', url: '/prod/lists/list/',
dataType: 'json', dataType: 'json',
data: {name : name}, data: {name: name},
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
var list = new List(data.list_id); var list = new List(data.list_id);
callback(list); callback(list);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
get : function(callback, type) { get: function (callback, type) {
var $this = this; var $this = this;
type = typeof type === 'undefined' ? 'json' : type; type = typeof type === 'undefined' ? 'json' : type;
@@ -55,27 +51,21 @@ var p4 = p4 || {};
url: '/prod/lists/all/', url: '/prod/lists/all/',
dataType: type, dataType: type,
data: {}, data: {},
success: function(data){ success: function (data) {
if(type == 'json') if (type == 'json') {
{ if (data.success) {
if(data.success)
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback(data.result); callback(data.result);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
else else {
{ if (typeof callback === 'function') {
if(typeof callback === 'function')
{
callback(data); callback(data);
} }
} }
@@ -86,42 +76,38 @@ var p4 = p4 || {};
} }
List.prototype = { List.prototype = {
addUsers : function(arrayUsers, callback) { addUsers: function (arrayUsers, callback) {
if(!arrayUsers instanceof Array) if (!arrayUsers instanceof Array) {
{
throw 'addUsers takes array as argument'; throw 'addUsers takes array as argument';
} }
var $this = this; var $this = this;
var data = {usr_ids : $(arrayUsers).toArray()}; var data = {usr_ids: $(arrayUsers).toArray()};
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '/prod/lists/list/' + $this.id + '/add/', url: '/prod/lists/list/' + $this.id + '/add/',
dataType: 'json', dataType: 'json',
data: data, data: data,
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this, data); callback($this, data);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
addUser : function(usr_id, callback) { addUser: function (usr_id, callback) {
this.addUsers([usr_id], callback); this.addUsers([usr_id], callback);
}, },
remove : function(callback) { remove: function (callback) {
var $this = this; var $this = this;
@@ -130,24 +116,21 @@ var p4 = p4 || {};
url: '/prod/lists/list/' + this.id + '/delete/', url: '/prod/lists/list/' + this.id + '/delete/',
dataType: 'json', dataType: 'json',
data: {}, data: {},
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this); callback($this);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
update : function(name, callback) { update: function (name, callback) {
var $this = this; var $this = this;
@@ -155,25 +138,22 @@ var p4 = p4 || {};
type: 'POST', type: 'POST',
url: '/prod/lists/list/' + this.id + '/update/', url: '/prod/lists/list/' + this.id + '/update/',
dataType: 'json', dataType: 'json',
data: { name : name }, data: { name: name },
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this); callback($this);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
removeUser : function(usr_id, callback) { removeUser: function (usr_id, callback) {
var $this = this; var $this = this;
@@ -182,24 +162,21 @@ var p4 = p4 || {};
url: '/prod/lists/list/' + this.id + '/remove/' + usr_id + '/', url: '/prod/lists/list/' + this.id + '/remove/' + usr_id + '/',
dataType: 'json', dataType: 'json',
data: {}, data: {},
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this, data); callback($this, data);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
shareWith : function(usr_id, role, callback) { shareWith: function (usr_id, role, callback) {
var $this = this; var $this = this;
@@ -207,25 +184,22 @@ var p4 = p4 || {};
type: 'POST', type: 'POST',
url: '/prod/lists/list/' + this.id + '/share/' + usr_id + '/', url: '/prod/lists/list/' + this.id + '/share/' + usr_id + '/',
dataType: 'json', dataType: 'json',
data: {role : role}, data: {role: role},
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this); callback($this);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
unshareWith : function(callback) { unshareWith: function (callback) {
var $this = this; var $this = this;
@@ -234,24 +208,21 @@ var p4 = p4 || {};
url: '/prod/lists/list/' + this.id + '/unshare/' + usr_id + '/', url: '/prod/lists/list/' + this.id + '/unshare/' + usr_id + '/',
dataType: 'json', dataType: 'json',
data: {}, data: {},
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this); callback($this);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
get : function(callback) { get: function (callback) {
var $this = this; var $this = this;
@@ -260,18 +231,15 @@ var p4 = p4 || {};
url: '/prod/lists/list/' + this.id + '/', url: '/prod/lists/list/' + this.id + '/',
dataType: 'json', dataType: 'json',
data: {}, data: {},
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback($this, data); callback($this, data);
} }
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }

View File

@@ -1,18 +1,17 @@
(function( $ ){ (function ($) {
var methods = { var methods = {
init : function( options ) { init: function (options) {
var settings = { var settings = {
'url' : '/admin/tests/pathurl/path/' 'url': '/admin/tests/pathurl/path/'
}; };
return this.each(function() { return this.each(function () {
var $this = $(this), data = $(this).data('path_file_tests'); var $this = $(this), data = $(this).data('path_file_tests');
if ( ! data ) if (!data) {
{ if (options) {
if ( options ) { $.extend(settings, options);
$.extend( settings, options );
} }
$this.data('path_file_tests', {}); $this.data('path_file_tests', {});
@@ -21,19 +20,18 @@
$this.after('<img class="status" src="/skins/icons/delete.png"/>'); $this.after('<img class="status" src="/skins/icons/delete.png"/>');
$this.bind('keyup blur', function(){ $this.bind('keyup blur', function () {
var el_loader = $this.nextAll('.loader'); var el_loader = $this.nextAll('.loader');
var el_status = $this.nextAll('.status'); var el_status = $this.nextAll('.status');
if($this.data('ajax_path_test') && typeof $this.data('ajax_path_test').abort == 'function') if ($this.data('ajax_path_test') && typeof $this.data('ajax_path_test').abort == 'function')
$this.data('ajax_path_test').abort(); $this.data('ajax_path_test').abort();
if(!$this.hasClass('test_executable') && !$this.hasClass('test_writeable') && !$this.hasClass('test_readable')) if (!$this.hasClass('test_executable') && !$this.hasClass('test_writeable') && !$this.hasClass('test_readable'))
return; return;
if(!$this.hasClass('required') && $.trim($this.val()) === '') if (!$this.hasClass('required') && $.trim($this.val()) === '') {
{
el_status.css('visibility', 'hidden'); el_status.css('visibility', 'hidden');
return; return;
} }
@@ -43,43 +41,39 @@
type: "GET", type: "GET",
url: settings.url, url: settings.url,
data: { data: {
path : $this.val() path: $this.val()
}, },
beforeSend:function(){ beforeSend: function () {
el_loader.css('visibility', 'visible'); el_loader.css('visibility', 'visible');
}, },
success: function(data){ success: function (data) {
el_loader.css('visibility', 'hidden'); el_loader.css('visibility', 'hidden');
if($this.hasClass('required')) if ($this.hasClass('required')) {
{
$this.addClass('field_error'); $this.addClass('field_error');
} }
if($this.hasClass('test_executable') && (data.executable === false || data.file !== true)) if ($this.hasClass('test_executable') && (data.executable === false || data.file !== true)) {
{ el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible');
return; return;
} }
if($this.hasClass('test_writeable') && data.writeable === false) if ($this.hasClass('test_writeable') && data.writeable === false) {
{ el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible');
return; return;
} }
if($this.hasClass('test_readable') && data.readable === false) if ($this.hasClass('test_readable') && data.readable === false) {
{ el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible');
return; return;
} }
el_status.attr('src','/skins/icons/ok.png').css('visibility', 'visible'); el_status.attr('src', '/skins/icons/ok.png').css('visibility', 'visible');
$this.removeClass('field_error'); $this.removeClass('field_error');
return; return;
}, },
timeout:function(){ timeout: function () {
el_loader.css('visibility', 'hidden'); el_loader.css('visibility', 'hidden');
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible'); el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
}, },
error:function(){ error: function () {
el_loader.css('visibility', 'hidden'); el_loader.css('visibility', 'hidden');
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible'); el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
} }
}); });
$this.data('ajax_path_test', ajax); $this.data('ajax_path_test', ajax);
@@ -87,49 +81,46 @@
$this.trigger('keyup'); $this.trigger('keyup');
$this.nextAll('.reload').bind('click', function(){ $this.nextAll('.reload').bind('click', function () {
$this.trigger('keyup'); $this.trigger('keyup');
}); });
} }
}); });
}, },
destroy : function( ) { destroy: function () {
return this.each(function() { return this.each(function () {
$(this).data('path_file_tests', null); $(this).data('path_file_tests', null);
}); });
} }
}; };
$.fn.path_file_test = function(method) { $.fn.path_file_test = function (method) {
if ( methods[method] ) { if (methods[method]) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if ( typeof method === 'object' || ! method ) { } else if (typeof method === 'object' || !method) {
return methods.init.apply( this, arguments ); return methods.init.apply(this, arguments);
} else { } else {
$.error( 'Method ' + method + ' does not exist on jQuery.path_file_test' ); $.error('Method ' + method + ' does not exist on jQuery.path_file_test');
} }
}; };
})( jQuery ); })(jQuery);
(function ($) {
(function( $ ){
var methods = { var methods = {
init : function( options ) { init: function (options) {
var settings = { var settings = {
'url' : '/admin/tests/pathurl/url/' 'url': '/admin/tests/pathurl/url/'
}; };
return this.each(function() { return this.each(function () {
var $this = $(this), data = $(this).data('url_tests'); var $this = $(this), data = $(this).data('url_tests');
if ( ! data ) if (!data) {
{ if (options) {
if ( options ) { $.extend(settings, options);
$.extend( settings, options );
} }
$this.data('url_tests', {}); $this.data('url_tests', {});
@@ -137,7 +128,7 @@
$this.after('<img class="reload" src="/skins/icons/reload.png"/>'); $this.after('<img class="reload" src="/skins/icons/reload.png"/>');
$this.after('<img class="status" src="/skins/icons/delete.png"/>'); $this.after('<img class="status" src="/skins/icons/delete.png"/>');
$this.bind('keyup blur', function(){ $this.bind('keyup blur', function () {
var el_loader = $(this).nextAll('.loader'); var el_loader = $(this).nextAll('.loader');
var el_status = $(this).nextAll('.status'); var el_status = $(this).nextAll('.status');
@@ -147,91 +138,84 @@
var value = $.trim($this.val()); var value = $.trim($this.val());
if(!required && value === '') if (!required && value === '') {
{ el_status.attr('src', '/skins/icons/ok.png');
el_status.attr('src','/skins/icons/ok.png');
return; return;
} }
if(required && value === '') if (required && value === '') {
{ el_status.attr('src', '/skins/icons/delete.png');
el_status.attr('src','/skins/icons/delete.png');
return; return;
} }
if(same_domain && value.substring(0,1) != '/') if (same_domain && value.substring(0, 1) != '/') {
{ value = '/' + value;
value = '/'+value;
} }
if(same_domain) if (same_domain) {
{ value = location.protocol + '//' + location.hostname + value;
value = location.protocol+'//'+location.hostname+value;
} }
if($this.data('ajax_url_test') && typeof $this.data('ajax_url_test').abort == 'function') if ($this.data('ajax_url_test') && typeof $this.data('ajax_url_test').abort == 'function')
$this.data('ajax_url_test').abort(); $this.data('ajax_url_test').abort();
var ajax = $.ajax({ var ajax = $.ajax({
type: "GET", type: "GET",
url: settings.url, url: settings.url,
dataType:'json', dataType: 'json',
data: { data: {
url : value url: value
}, },
beforeSend:function(){ beforeSend: function () {
el_loader.css('visibility', 'visible'); el_loader.css('visibility', 'visible');
}, },
success: function(datas){ success: function (datas) {
el_loader.css('visibility', 'hidden'); el_loader.css('visibility', 'hidden');
if(datas.code === 404) if (datas.code === 404) {
{ el_status.attr('src', '/skins/icons/delete.png');
el_status.attr('src','/skins/icons/delete.png');
return; return;
} }
if(!listable && datas.code === 403) if (!listable && datas.code === 403) {
{ el_status.attr('src', '/skins/icons/ok.png');
el_status.attr('src','/skins/icons/ok.png');
} }
else else {
{ el_status.attr('src', '/skins/icons/delete.png');
el_status.attr('src','/skins/icons/delete.png');
} }
return; return;
}, },
timeout:function(){ timeout: function () {
el_loader.css('visibility', 'hidden'); el_loader.css('visibility', 'hidden');
el_status.attr('src','/skins/icons/delete.png'); el_status.attr('src', '/skins/icons/delete.png');
}, },
error:function(datas){ error: function (datas) {
el_loader.css('visibility', 'hidden'); el_loader.css('visibility', 'hidden');
el_status.attr('src','/skins/icons/delete.png'); el_status.attr('src', '/skins/icons/delete.png');
} }
}); });
$this.data('ajax_url_test', ajax); $this.data('ajax_url_test', ajax);
}); });
$this.trigger('keyup'); $this.trigger('keyup');
$this.nextAll('.reload').bind('click', function(){ $this.nextAll('.reload').bind('click', function () {
$this.trigger('keyup'); $this.trigger('keyup');
}); });
} }
}); });
}, },
destroy : function( ) { destroy: function () {
return this.each(function() { return this.each(function () {
$(this).data('url_tests', null); $(this).data('url_tests', null);
}); });
} }
}; };
$.fn.url_test = function(method) { $.fn.url_test = function (method) {
if ( methods[method] ) { if (methods[method]) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if ( typeof method === 'object' || ! method ) { } else if (typeof method === 'object' || !method) {
return methods.init.apply( this, arguments ); return methods.init.apply(this, arguments);
} else { } else {
$.error( 'Method ' + method + ' does not exist on jQuery.url_test' ); $.error('Method ' + method + ' does not exist on jQuery.url_test');
} }
}; };
})( jQuery ); })(jQuery);

View File

@@ -19,19 +19,17 @@ define([
"apps/admin/fields/views/save", "apps/admin/fields/views/save",
"apps/admin/fields/views/fieldError", "apps/admin/fields/views/fieldError",
"apps/admin/fields/errors/errorManager" "apps/admin/fields/errors/errorManager"
], function( ], function ($, _, Backbone, i18n, FieldsCollection, VocabulariesCollection, DcFieldsCollection, FieldListView, SaveView, FieldErrorView, ErrorManager) {
$, _, Backbone, i18n, FieldsCollection, VocabulariesCollection, var initialize = function () {
DcFieldsCollection, FieldListView, SaveView, FieldErrorView, ErrorManager) {
var initialize = function() {
AdminFieldApp = { AdminFieldApp = {
$window : $(window), $window: $(window),
$scope : $("#admin-field-app"), $scope: $("#admin-field-app"),
$top : $(".row-top", this.$scope), $top: $(".row-top", this.$scope),
$bottom : $(".row-bottom", this.$scope), $bottom: $(".row-bottom", this.$scope),
$leftBlock : $(".left-block", this.$bottom), $leftBlock: $(".left-block", this.$bottom),
$rightBlock : $(".right-block", this.$bottom), $rightBlock: $(".right-block", this.$bottom),
fieldsToDelete : [], fieldsToDelete: [],
lng : function() { lng: function () {
return typeof p4 === "undefined" ? "en" : (p4.lng || "en"); return typeof p4 === "undefined" ? "en" : (p4.lng || "en");
}, },
resizeListBlock: function () { resizeListBlock: function () {
@@ -56,7 +54,7 @@ define([
// initiliaze collections // initiliaze collections
AdminFieldApp.fieldsCollection = new FieldsCollection(null, { AdminFieldApp.fieldsCollection = new FieldsCollection(null, {
sbas_id : AdminFieldApp.sbas_id sbas_id: AdminFieldApp.sbas_id
}); });
AdminFieldApp.vocabularyCollection = new VocabulariesCollection(); AdminFieldApp.vocabularyCollection = new VocabulariesCollection();
AdminFieldApp.dcFieldsCollection = new DcFieldsCollection(); AdminFieldApp.dcFieldsCollection = new DcFieldsCollection();
@@ -71,12 +69,12 @@ define([
AdminFieldApp.dcFieldsCollection.fetch(), AdminFieldApp.dcFieldsCollection.fetch(),
$.ajax({ $.ajax({
url: '/available-languages', url: '/available-languages',
success: function(languages) { success: function (languages) {
AdminFieldApp.languages = languages; AdminFieldApp.languages = languages;
} }
}) })
]).done( ]).done(
function() { function () {
// register views // register views
AdminFieldApp.saveView = new SaveView({ AdminFieldApp.saveView = new SaveView({
el: $(".save-block", AdminFieldApp.scope) el: $(".save-block", AdminFieldApp.scope)
@@ -96,7 +94,7 @@ define([
AdminFieldApp.$window.trigger("resize"); AdminFieldApp.$window.trigger("resize");
// click on first item list // click on first item list
if (AdminFieldApp.fieldListView.itemViews.length > 0 ) { if (AdminFieldApp.fieldListView.itemViews.length > 0) {
_.first(AdminFieldApp.fieldListView.itemViews).clickAction().animate(); _.first(AdminFieldApp.fieldListView.itemViews).clickAction().animate();
} }
} }

View File

@@ -11,13 +11,13 @@ define([
"underscore", "underscore",
"backbone", "backbone",
"models/dcField" "models/dcField"
], function(_, Backbone, DcFieldModel) { ], function (_, Backbone, DcFieldModel) {
var DcFieldCollection = Backbone.Collection.extend({ var DcFieldCollection = Backbone.Collection.extend({
model: DcFieldModel, model: DcFieldModel,
url: function() { url: function () {
return "/admin/fields/dc-fields"; return "/admin/fields/dc-fields";
}, },
comparator: function(item) { comparator: function (item) {
return item.get("label"); return item.get("label");
} }
}); });

View File

@@ -11,9 +11,9 @@ define([
"underscore", "underscore",
"backbone", "backbone",
"models/field" "models/field"
], function(_, Backbone, FieldModel) { ], function (_, Backbone, FieldModel) {
var FieldCollection = Backbone.Collection.extend({ var FieldCollection = Backbone.Collection.extend({
initialize: function(models, options) { initialize: function (models, options) {
options = options || {}; options = options || {};
if (typeof options === "object" && false === "sbas_id" in options) { if (typeof options === "object" && false === "sbas_id" in options) {
throw "You must set a sbas id" throw "You must set a sbas id"
@@ -21,23 +21,23 @@ define([
this.sbasId = options.sbas_id; this.sbasId = options.sbas_id;
}, },
model: FieldModel, model: FieldModel,
url: function() { url: function () {
return "/admin/fields/" + this.sbasId + "/fields"; return "/admin/fields/" + this.sbasId + "/fields";
}, },
search: function(letters) { search: function (letters) {
if (letters === "") if (letters === "")
return this; return this;
var pattern = new RegExp(letters, "gi"); var pattern = new RegExp(letters, "gi");
return _(this.filter(function(data) { return _(this.filter(function (data) {
return pattern.test(data.get("name")); return pattern.test(data.get("name"));
})); }));
}, },
comparator: function(item) { comparator: function (item) {
return item.get("sorter"); return item.get("sorter");
}, },
nextIndex: function(model) { nextIndex: function (model) {
var index = this.indexOf(model); var index = this.indexOf(model);
if (index < 0) { if (index < 0) {
@@ -50,7 +50,7 @@ define([
return index + 1; return index + 1;
}, },
previousIndex: function(model) { previousIndex: function (model) {
var index = this.indexOf(model); var index = this.indexOf(model);
if (index < 0) { if (index < 0) {
@@ -64,7 +64,7 @@ define([
return index - 1; return index - 1;
}, },
// save all collection // save all collection
save: function(options) { save: function (options) {
return Backbone.sync("update", this, options || {}); return Backbone.sync("update", this, options || {});
} }
}); });

View File

@@ -11,13 +11,13 @@ define([
"underscore", "underscore",
"backbone", "backbone",
"models/vocabulary" "models/vocabulary"
], function(_, Backbone, VocabularyModel) { ], function (_, Backbone, VocabularyModel) {
var VocabularyCollection = Backbone.Collection.extend({ var VocabularyCollection = Backbone.Collection.extend({
model: VocabularyModel, model: VocabularyModel,
url: function() { url: function () {
return "/admin/fields/vocabularies"; return "/admin/fields/vocabularies";
}, },
comparator: function(item) { comparator: function (item) {
return item.get("name"); return item.get("name");
} }
}); });

View File

@@ -10,7 +10,7 @@
define([ define([
"jquery", "jquery",
"underscore" "underscore"
], function($, _) { ], function ($, _) {
var Error = function (model, fieldId, message) { var Error = function (model, fieldId, message) {
this.model = model; this.model = model;

View File

@@ -12,9 +12,9 @@ define([
"underscore", "underscore",
"backbone", "backbone",
"apps/admin/fields/errors/errorModel" "apps/admin/fields/errors/errorModel"
], function($, _, Backbone, ErrorModel) { ], function ($, _, Backbone, ErrorModel) {
var ErrorManager = function() { var ErrorManager = function () {
this.errors = {}; this.errors = {};
_.extend(this, Backbone.Events); _.extend(this, Backbone.Events);
}; };
@@ -38,8 +38,8 @@ define([
containsModelError: function (model) { containsModelError: function (model) {
return "undefined" !== typeof this.errors[model.get("id")]; return "undefined" !== typeof this.errors[model.get("id")];
}, },
addModelFieldError: function(error) { addModelFieldError: function (error) {
if (! error instanceof Error) { if (!error instanceof Error) {
throw "Item must be an error object"; throw "Item must be an error object";
} }
@@ -56,7 +56,7 @@ define([
return this; return this;
}, },
removeModelFieldError: function(model, fieldId) { removeModelFieldError: function (model, fieldId) {
var modelError = this.getModelError(model); var modelError = this.getModelError(model);
if (modelError) { if (modelError) {
@@ -72,7 +72,7 @@ define([
} }
} }
}, },
clearModelFieldErrors: function(model, fieldId) { clearModelFieldErrors: function (model, fieldId) {
var modelError = this.getModelError(model); var modelError = this.getModelError(model);
if (modelError) { if (modelError) {
@@ -93,7 +93,7 @@ define([
return false; return false;
}, },
getModelFieldError: function(model, fieldId) { getModelFieldError: function (model, fieldId) {
var modelError = this.getModelError(model); var modelError = this.getModelError(model);
if (modelError) { if (modelError) {
@@ -102,7 +102,7 @@ define([
return null; return null;
}, },
clearAll: function() { clearAll: function () {
this.errors = {}; this.errors = {};
this.trigger("no-error"); this.trigger("no-error");
}, },
@@ -120,8 +120,8 @@ define([
}, },
all: function () { all: function () {
var errors = []; var errors = [];
_.each(this.errors, function(modelErrors) { _.each(this.errors, function (modelErrors) {
_.each(modelErrors.all(), function(error) { _.each(modelErrors.all(), function (error) {
errors.push(error); errors.push(error);
}); });
}); });

View File

@@ -10,21 +10,21 @@
define([ define([
"jquery", "jquery",
"underscore" "underscore"
], function($, _) { ], function ($, _) {
var ErrorModel = function(id) { var ErrorModel = function (id) {
this.id = id; this.id = id;
this.errors = {}; this.errors = {};
}; };
ErrorModel.prototype = { ErrorModel.prototype = {
add: function(id, error) { add: function (id, error) {
if (! error instanceof Error) { if (!error instanceof Error) {
throw "Item must be an error object"; throw "Item must be an error object";
} }
this.errors[id] = error; this.errors[id] = error;
}, },
get: function(id) { get: function (id) {
if (this.has(id)) { if (this.has(id)) {
return this.errors[id]; return this.errors[id];
} }
@@ -33,12 +33,12 @@ define([
has: function (id) { has: function (id) {
return "undefined" !== typeof this.errors[id]; return "undefined" !== typeof this.errors[id];
}, },
remove: function(id) { remove: function (id) {
if (this.has(id)) { if (this.has(id)) {
delete this.errors[id]; delete this.errors[id];
} }
}, },
count: function() { count: function () {
var count = 0; var count = 0;
for (var k in this.errors) { for (var k in this.errors) {
if (this.errors.hasOwnProperty(k)) { if (this.errors.hasOwnProperty(k)) {

View File

@@ -19,7 +19,7 @@ require.config({
bootstrap: "../skins/build/bootstrap/js/bootstrap.min" bootstrap: "../skins/build/bootstrap/js/bootstrap.min"
}, },
shim: { shim: {
bootstrap : ["jquery"], bootstrap: ["jquery"],
jqueryui: { jqueryui: {
deps: [ "jquery" ] deps: [ "jquery" ]
} }
@@ -27,6 +27,6 @@ require.config({
}); });
// launch application // launch application
require(["apps/admin/fields/app"], function(App) { require(["apps/admin/fields/app"], function (App) {
App.initialize(); App.initialize();
}); });

View File

@@ -13,11 +13,11 @@ define([
"backbone", "backbone",
"i18n", "i18n",
"bootstrap" "bootstrap"
], function($, _, Backbone, i18n, bootstrap) { ], function ($, _, Backbone, i18n, bootstrap) {
var AlertView = Backbone.View.extend({ var AlertView = Backbone.View.extend({
tagName: "div", tagName: "div",
className: "alert", className: "alert",
initialize: function(options) { initialize: function (options) {
var self = this; var self = this;
if (options) { if (options) {
@@ -30,7 +30,7 @@ define([
self.remove(); self.remove();
}); });
}, },
render: function() { render: function () {
var self = this; var self = this;
var template = _.template($("#alert_template").html(), { var template = _.template($("#alert_template").html(), {
msg: this.message msg: this.message
@@ -39,7 +39,9 @@ define([
this.$el.addClass("alert-" + this.alert).html(template).alert(); this.$el.addClass("alert-" + this.alert).html(template).alert();
if (this.delay > 0) { if (this.delay > 0) {
window.setTimeout(function() { self.$el.alert('close') }, this.delay); window.setTimeout(function () {
self.$el.alert('close')
}, this.delay);
} }
$(".block-alert").empty().append(this.$el); $(".block-alert").empty().append(this.$el);

View File

@@ -15,7 +15,7 @@ define([
"bootstrap", "bootstrap",
"apps/admin/fields/views/alert", "apps/admin/fields/views/alert",
"models/field" "models/field"
], function($, _, Backbone, i18n, bootstrap, AlertView, FieldModel) { ], function ($, _, Backbone, i18n, bootstrap, AlertView, FieldModel) {
var CreateView = Backbone.View.extend({ var CreateView = Backbone.View.extend({
tagName: "div", tagName: "div",
events: { events: {
@@ -24,22 +24,22 @@ define([
"click .btn-cancel-field": "toggleCreateFormAction", "click .btn-cancel-field": "toggleCreateFormAction",
"keyup input": "onKeyupInput" "keyup input": "onKeyupInput"
}, },
render: function() { render: function () {
var template = _.template($("#create_template").html()); var template = _.template($("#create_template").html());
this.$el.html(template); this.$el.html(template);
$("#new-source", this.$el).autocomplete({ $("#new-source", this.$el).autocomplete({
minLength: 2, minLength: 2,
source: function(request, response) { source: function (request, response) {
$.ajax({ $.ajax({
url: "/admin/fields/tags/search", url: "/admin/fields/tags/search",
dataType: "json", dataType: "json",
data: { data: {
term: request.term term: request.term
}, },
success: function(data) { success: function (data) {
response($.map(data, function(item) { response($.map(data, function (item) {
return { return {
label: item.label, label: item.label,
value: item.value value: item.value
@@ -59,7 +59,7 @@ define([
.find(".help-block") .find(".help-block")
.empty(); .empty();
}, },
createAction: function(event) { createAction: function (event) {
var self = this; var self = this;
var formErrors = 0; var formErrors = 0;
@@ -81,7 +81,7 @@ define([
} }
// check for duplicate field name // check for duplicate field name
if ("undefined" !== typeof AdminFieldApp.fieldsCollection.find(function(model){ if ("undefined" !== typeof AdminFieldApp.fieldsCollection.find(function (model) {
return model.get("name").toLowerCase() === fieldNameValue.toLowerCase(); return model.get("name").toLowerCase() === fieldNameValue.toLowerCase();
})) { })) {
fieldName fieldName
@@ -118,7 +118,7 @@ define([
formErrors++; formErrors++;
} }
if (formErrors > 0 ) { if (formErrors > 0) {
return; return;
} }
@@ -126,15 +126,15 @@ define([
"sbas-id": AdminFieldApp.sbas_id, "sbas-id": AdminFieldApp.sbas_id,
"name": fieldNameValue, "name": fieldNameValue,
"tag": fieldTagValue, "tag": fieldTagValue,
"label_en" : $("#new-label_en", this.$el).val(), "label_en": $("#new-label_en", this.$el).val(),
"label_fr" : $("#new-label_fr", this.$el).val(), "label_fr": $("#new-label_fr", this.$el).val(),
"label_de" : $("#new-label_de", this.$el).val(), "label_de": $("#new-label_de", this.$el).val(),
"label_nl" : $("#new-label_nl", this.$el).val(), "label_nl": $("#new-label_nl", this.$el).val(),
"multi": $("#new-multivalued", this.$el).is(":checked") "multi": $("#new-multivalued", this.$el).is(":checked")
}); });
field.save(null, { field.save(null, {
success: function(field, response, options) { success: function (field, response, options) {
AdminFieldApp.fieldsCollection.add(field); AdminFieldApp.fieldsCollection.add(field);
_.last(AdminFieldApp.fieldListView.itemViews).clickAction().animate(); _.last(AdminFieldApp.fieldListView.itemViews).clickAction().animate();
@@ -144,7 +144,7 @@ define([
}) })
}).render(); }).render();
}, },
error: function(xhr, textStatus, errorThrown) { error: function (xhr, textStatus, errorThrown) {
new AlertView({ new AlertView({
alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong")} alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong")}
).render(); ).render();
@@ -155,7 +155,7 @@ define([
return this; return this;
}, },
toggleCreateFormAction: function(event) { toggleCreateFormAction: function (event) {
var fieldBlock = $(".add-field-block", this.$el); var fieldBlock = $(".add-field-block", this.$el);
var addBtn = $(".btn-add-field", this.$el); var addBtn = $(".btn-add-field", this.$el);

View File

@@ -17,22 +17,22 @@ define([
"apps/admin/fields/views/modal", "apps/admin/fields/views/modal",
"apps/admin/fields/views/dcField", "apps/admin/fields/views/dcField",
"apps/admin/fields/errors/error" "apps/admin/fields/errors/error"
], function($, _, Backbone, i18n, MultiViews, AlertView, ModalView, DcFieldView, Error) { ], function ($, _, Backbone, i18n, MultiViews, AlertView, ModalView, DcFieldView, Error) {
// Add multiview methods // Add multiview methods
var FieldEditView = Backbone.View.extend(_.extend({}, MultiViews, { var FieldEditView = Backbone.View.extend(_.extend({}, MultiViews, {
tagName: "div", tagName: "div",
className: "field-edit", className: "field-edit",
initialize: function() { initialize: function () {
this.model.on("change", this._onModelChange, this); this.model.on("change", this._onModelChange, this);
}, },
updateModel: function(model) { updateModel: function (model) {
// unbind event to previous model // unbind event to previous model
this.model.off("change"); this.model.off("change");
this.model = model; this.model = model;
return this; return this;
}, },
render: function() { render: function () {
var self = this; var self = this;
var template = _.template($("#edit_template").html(), { var template = _.template($("#edit_template").html(), {
lng: AdminFieldApp.lng(), lng: AdminFieldApp.lng(),
@@ -45,7 +45,7 @@ define([
this.$el.empty().html(template); this.$el.empty().html(template);
this._assignView({ this._assignView({
".dc-fields-subview" : new DcFieldView({ ".dc-fields-subview": new DcFieldView({
collection: AdminFieldApp.dcFieldsCollection, collection: AdminFieldApp.dcFieldsCollection,
field: this.model field: this.model
}) })
@@ -53,15 +53,15 @@ define([
var completer = $("#tag", this.$el).autocomplete({ var completer = $("#tag", this.$el).autocomplete({
minLength: 2, minLength: 2,
source: function(request, response) { source: function (request, response) {
$.ajax({ $.ajax({
url: "/admin/fields/tags/search", url: "/admin/fields/tags/search",
dataType: "json", dataType: "json",
data: { data: {
term: request.term term: request.term
}, },
success: function(data) { success: function (data) {
response($.map(data, function(item) { response($.map(data, function (item) {
return { return {
label: item.label, label: item.label,
value: item.value value: item.value
@@ -70,7 +70,7 @@ define([
} }
}); });
}, },
close: function(e) { close: function (e) {
self.tagFieldChangedAction(e); self.tagFieldChangedAction(e);
} }
}); });
@@ -95,7 +95,7 @@ define([
"change select": "selectionChangedAction", "change select": "selectionChangedAction",
"click .lng-label a": "_toggleLabels" "click .lng-label a": "_toggleLabels"
}, },
triggerControlledVocabulary: function(e) { triggerControlledVocabulary: function (e) {
if ($(e.target, this.$el).find("option:selected").val() === "") { if ($(e.target, this.$el).find("option:selected").val() === "") {
this.model.set("vocabulary-type", false); this.model.set("vocabulary-type", false);
this.render(); this.render();
@@ -105,7 +105,7 @@ define([
this.render(); this.render();
} }
}, },
selectionChangedAction: function(e) { selectionChangedAction: function (e) {
var field = $(e.target); var field = $(e.target);
var data = {}; var data = {};
data[field.attr("id")] = $("option:selected", field).val(); data[field.attr("id")] = $("option:selected", field).val();
@@ -113,7 +113,7 @@ define([
return this; return this;
}, },
fieldChangedAction: function(e) { fieldChangedAction: function (e) {
var field = $(e.target); var field = $(e.target);
var fieldId = field.attr("id"); var fieldId = field.attr("id");
var data = {}; var data = {};
@@ -122,7 +122,7 @@ define([
return this; return this;
}, },
labelChangedAction: function(e) { labelChangedAction: function (e) {
var field = $(e.target); var field = $(e.target);
var fieldId = field.attr("id"); var fieldId = field.attr("id");
var data = this.model.get("labels"); var data = this.model.get("labels");
@@ -133,13 +133,13 @@ define([
return this; return this;
}, },
tagFieldChangedAction: function(e) { tagFieldChangedAction: function (e) {
var $this = this; var $this = this;
var fieldTag = $(e.target); var fieldTag = $(e.target);
var fieldTagId = fieldTag.attr("id"); var fieldTagId = fieldTag.attr("id");
var fieldTagValue = fieldTag.val(); var fieldTagValue = fieldTag.val();
var onFieldValid = function() { var onFieldValid = function () {
if (fieldTag.closest(".control-group").hasClass("error")) { if (fieldTag.closest(".control-group").hasClass("error")) {
// remove error // remove error
AdminFieldApp.errorManager.removeModelFieldError( AdminFieldApp.errorManager.removeModelFieldError(
@@ -157,7 +157,7 @@ define([
} }
if ("" !== fieldTagValue) { if ("" !== fieldTagValue) {
var jqxhr = $.get( "/admin/fields/tags/"+fieldTagValue, onFieldValid).fail(function() { var jqxhr = $.get("/admin/fields/tags/" + fieldTagValue, onFieldValid).fail(function () {
fieldTag fieldTag
.closest(".control-group") .closest(".control-group")
.addClass("error") .addClass("error")
@@ -173,7 +173,7 @@ define([
onFieldValid(); onFieldValid();
} }
}, },
deleteAction: function() { deleteAction: function () {
var self = this; var self = this;
var modalView = new ModalView({ var modalView = new ModalView({
model: this.model, model: this.model,
@@ -191,7 +191,7 @@ define([
var index = previousIndex ? previousIndex : (nextIndex ? nextIndex - 1 : -1); var index = previousIndex ? previousIndex : (nextIndex ? nextIndex - 1 : -1);
modalView.render(); modalView.render();
modalView.on("modal:confirm", function() { modalView.on("modal:confirm", function () {
AdminFieldApp.fieldsToDelete.push(self.model); AdminFieldApp.fieldsToDelete.push(self.model);
AdminFieldApp.fieldListView.collection.remove(self.model); AdminFieldApp.fieldListView.collection.remove(self.model);
self._selectModelView(index); self._selectModelView(index);
@@ -200,19 +200,19 @@ define([
return this; return this;
}, },
_onModelChange: function() { _onModelChange: function () {
AdminFieldApp.fieldListView.collection.remove(this.model, {silent: true}); AdminFieldApp.fieldListView.collection.remove(this.model, {silent: true});
AdminFieldApp.fieldListView.collection.add(this.model, {silent: true}); AdminFieldApp.fieldListView.collection.add(this.model, {silent: true});
AdminFieldApp.saveView.updateStateButton(); AdminFieldApp.saveView.updateStateButton();
}, },
// select temView by index in itemList // select temView by index in itemList
_selectModelView: function(index) { _selectModelView: function (index) {
// select previous or next itemview // select previous or next itemview
if (index >= 0) { if (index >= 0) {
AdminFieldApp.fieldListView.itemViews[index].select().animate().click(); AdminFieldApp.fieldListView.itemViews[index].select().animate().click();
} }
}, },
_toggleLabels: function(event) { _toggleLabels: function (event) {
event.preventDefault(); event.preventDefault();
var curLabel = $(event.target); var curLabel = $(event.target);
$('.lng-label', this.$el).removeClass("select"); $('.lng-label', this.$el).removeClass("select");

View File

@@ -12,20 +12,20 @@ define([
"underscore", "underscore",
"backbone", "backbone",
"i18n" "i18n"
], function($, _, Backbone, i18n) { ], function ($, _, Backbone, i18n) {
var FieldErrorView = Backbone.View.extend({ var FieldErrorView = Backbone.View.extend({
initialize: function() { initialize: function () {
AdminFieldApp.errorManager.on("add-error", this.render, this); AdminFieldApp.errorManager.on("add-error", this.render, this);
AdminFieldApp.errorManager.on("remove-error", this.render, this); AdminFieldApp.errorManager.on("remove-error", this.render, this);
}, },
render: function() { render: function () {
var messages = []; var messages = [];
var errors = AdminFieldApp.errorManager.all(); var errors = AdminFieldApp.errorManager.all();
_.each(_.groupBy(errors, function(error) { _.each(_.groupBy(errors, function (error) {
return error.model.get("name"); return error.model.get("name");
}), function(groupedErrors) { }), function (groupedErrors) {
_.each(groupedErrors, function(error) { _.each(groupedErrors, function (error) {
messages.push(i18n.t("field_error", { messages.push(i18n.t("field_error", {
postProcess: "sprintf", postProcess: "sprintf",
sprintf: [error.model.get("name")] sprintf: [error.model.get("name")]

View File

@@ -16,13 +16,13 @@ define([
"common/multiviews", "common/multiviews",
"apps/admin/fields/views/listRow", "apps/admin/fields/views/listRow",
"apps/admin/fields/views/create" "apps/admin/fields/views/create"
], function($, jqueryui, _, Backbone, i18n, MultiViews, FieldListRowView, CreateView) { ], function ($, jqueryui, _, Backbone, i18n, MultiViews, FieldListRowView, CreateView) {
var FieldListView = Backbone.View.extend(_.extend({}, MultiViews, { var FieldListView = Backbone.View.extend(_.extend({}, MultiViews, {
events: { events: {
"keyup #live_search": "searchAction", "keyup #live_search": "searchAction",
"update-sort": "updateSortAction" "update-sort": "updateSortAction"
}, },
initialize: function() { initialize: function () {
var self = this; var self = this;
// store all single rendered views // store all single rendered views
this.itemViews = []; this.itemViews = [];
@@ -40,9 +40,9 @@ define([
this.collection.bind("remove", this._onRemove, this); this.collection.bind("remove", this._onRemove, this);
this.collection.bind("remove", this.render, this); this.collection.bind("remove", this.render, this);
AdminFieldApp.errorManager.on('add-error', function(error) { AdminFieldApp.errorManager.on('add-error', function (error) {
var model = error.model; var model = error.model;
var itemView = _.find(self.itemViews, function(view) { var itemView = _.find(self.itemViews, function (view) {
return model.get('id') === view.model.get('id'); return model.get('id') === view.model.get('id');
}); });
@@ -51,8 +51,8 @@ define([
} }
}); });
AdminFieldApp.errorManager.on('remove-error', function(model) { AdminFieldApp.errorManager.on('remove-error', function (model) {
var itemView = _.find(self.itemViews, function(view) { var itemView = _.find(self.itemViews, function (view) {
return model.get('id') === view.model.get('id'); return model.get('id') === view.model.get('id');
}); });
@@ -61,7 +61,7 @@ define([
} }
}); });
}, },
render: function() { render: function () {
var template = _.template($("#item_list_view_template").html()); var template = _.template($("#item_list_view_template").html());
this.$el.empty().html(template); this.$el.empty().html(template);
@@ -71,7 +71,7 @@ define([
this._renderList(this.collection); this._renderList(this.collection);
this._assignView({ this._assignView({
".create-subview" : new CreateView() ".create-subview": new CreateView()
}); });
AdminFieldApp.resizeListBlock(); AdminFieldApp.resizeListBlock();
@@ -79,13 +79,13 @@ define([
return this; return this;
}, },
// render list by appending single item view, also fill itemViews // render list by appending single item view, also fill itemViews
_renderList: function(fields) { _renderList: function (fields) {
var that = this; var that = this;
this.$listEl.empty(); this.$listEl.empty();
this.itemViews = []; this.itemViews = [];
fields.each(function(field) { fields.each(function (field) {
var fieldErrors = AdminFieldApp.errorManager.getModelError(field); var fieldErrors = AdminFieldApp.errorManager.getModelError(field);
var singleView = new FieldListRowView({ var singleView = new FieldListRowView({
@@ -100,10 +100,10 @@ define([
this.$listEl.sortable({ this.$listEl.sortable({
handle: ".handle", handle: ".handle",
placeholder: "item-list-placeholder", placeholder: "item-list-placeholder",
start: function(event, ui) { start: function (event, ui) {
ui.item.addClass("border-bottom"); ui.item.addClass("border-bottom");
}, },
stop: function(event, ui) { stop: function (event, ui) {
ui.firstItemPosition = $("li:first", $(this).sortable('widget')).position().top; ui.firstItemPosition = $("li:first", $(this).sortable('widget')).position().top;
ui.item.trigger("drop", ui); ui.item.trigger("drop", ui);
} }
@@ -115,14 +115,14 @@ define([
return this; return this;
}, },
searchAction: function(event) { searchAction: function (event) {
this._renderList(this.collection.search($("#live_search", this.$el).val())); this._renderList(this.collection.search($("#live_search", this.$el).val()));
return this; return this;
}, },
_onRemove : function (model) { _onRemove: function (model) {
var models = []; var models = [];
this.collection.each(function(m) { this.collection.each(function (m) {
if (m.get("sorter") > model.get("sorter")) { if (m.get("sorter") > model.get("sorter")) {
m.set("sorter", m.get("sorter") - 1); m.set("sorter", m.get("sorter") - 1);
} }
@@ -132,7 +132,7 @@ define([
this.collection.reset(models); this.collection.reset(models);
}, },
updateSortAction: function(event, model, ui) { updateSortAction: function (event, model, ui) {
var newPosition = ui.item.index(); var newPosition = ui.item.index();
this.collection.remove(model, {silent: true}); this.collection.remove(model, {silent: true});
this.collection.each(function (model, index) { this.collection.each(function (model, index) {
@@ -145,7 +145,7 @@ define([
this.itemViews[0].animate(Math.abs(ui.firstItemPosition)); this.itemViews[0].animate(Math.abs(ui.firstItemPosition));
// update edit view model // update edit view model
AdminFieldApp.fieldEditView.updateModel(this.collection.find(function(el) { AdminFieldApp.fieldEditView.updateModel(this.collection.find(function (el) {
return el.get("id") === AdminFieldApp.fieldEditView.model.get("id"); return el.get("id") === AdminFieldApp.fieldEditView.model.get("id");
})); }));

View File

@@ -12,18 +12,18 @@ define([
"underscore", "underscore",
"backbone", "backbone",
"apps/admin/fields/views/edit" "apps/admin/fields/views/edit"
], function($, _, Backbone, FieldEditView) { ], function ($, _, Backbone, FieldEditView) {
var FieldListRowView = Backbone.View.extend({ var FieldListRowView = Backbone.View.extend({
tagName: "li", tagName: "li",
className: "field-row", className: "field-row",
initialize: function() { initialize: function () {
// destroy view is model is deleted // destroy view is model is deleted
this.model.on("change", this.onChange, this); this.model.on("change", this.onChange, this);
this.model.on("destroy", this.remove, this); this.model.on("destroy", this.remove, this);
}, },
events : { events: {
"click .trigger-click": "clickAction", "click .trigger-click": "clickAction",
"drop" : "dropAction" "drop": "dropAction"
}, },
clickAction: function (e) { clickAction: function (e) {
this.select(); this.select();
@@ -41,17 +41,17 @@ define([
return this; return this;
}, },
dropAction: function(event, ui) { dropAction: function (event, ui) {
this.$el.trigger("update-sort", [this.model, ui]); this.$el.trigger("update-sort", [this.model, ui]);
return this; return this;
}, },
onChange: function() { onChange: function () {
if (this.model.hasChanged("tag")) { if (this.model.hasChanged("tag")) {
this.render(); this.render();
} }
}, },
render: function() { render: function () {
var template = _.template($("#list_row_template").html(), { var template = _.template($("#list_row_template").html(), {
id: this.model.get("id"), id: this.model.get("id"),
position: this.model.get("sorter"), position: this.model.get("sorter"),
@@ -76,7 +76,7 @@ define([
return this; return this;
}, },
click: function() { click: function () {
this.$el.find('.trigger-click').first().trigger('click'); this.$el.find('.trigger-click').first().trigger('click');
return this; return this;
}, },

View File

@@ -13,7 +13,7 @@ define([
"backbone", "backbone",
"i18n", "i18n",
"bootstrap" "bootstrap"
], function($, _, Backbone, i18n, bootstrap) { ], function ($, _, Backbone, i18n, bootstrap) {
var ModalView = Backbone.View.extend({ var ModalView = Backbone.View.extend({
tagName: "div", tagName: "div",
className: "modal", className: "modal",
@@ -23,7 +23,7 @@ define([
initialize: function (options) { initialize: function (options) {
var self = this; var self = this;
// remove view when modal is closed // remove view when modal is closed
this.$el.on("hidden", function() { this.$el.on("hidden", function () {
self.remove(); self.remove();
}); });
@@ -31,7 +31,7 @@ define([
this.message = options.message; this.message = options.message;
} }
}, },
render: function() { render: function () {
var template = _.template($("#modal_template").html(), { var template = _.template($("#modal_template").html(), {
msg: this.message || "" msg: this.message || ""
}); });

View File

@@ -14,46 +14,46 @@ define([
"i18n", "i18n",
"bootstrap", "bootstrap",
"apps/admin/fields/views/alert" "apps/admin/fields/views/alert"
], function($, _, Backbone, i18n, bootstrap, AlertView) { ], function ($, _, Backbone, i18n, bootstrap, AlertView) {
var SaveView = Backbone.View.extend({ var SaveView = Backbone.View.extend({
initialize: function() { initialize: function () {
var self = this; var self = this;
this.previousAttributes = []; this.previousAttributes = [];
this.$overlay = null; this.$overlay = null;
AdminFieldApp.errorManager.on("add-error", function(errors) { AdminFieldApp.errorManager.on("add-error", function (errors) {
self._disableSaveButton(true); self._disableSaveButton(true);
}); });
AdminFieldApp.errorManager.on("no-error", function() { AdminFieldApp.errorManager.on("no-error", function () {
self._disableSaveButton(false); self._disableSaveButton(false);
}); });
}, },
events: { events: {
"click button.save-all" : "clickSaveAction" "click button.save-all": "clickSaveAction"
}, },
clickSaveAction: function(event) { clickSaveAction: function (event) {
var self = this; var self = this;
if (this._isModelDesync()) { if (this._isModelDesync()) {
this._loadingState(true); this._loadingState(true);
$.when.apply($, _.map(AdminFieldApp.fieldsToDelete, function(m){ $.when.apply($, _.map(AdminFieldApp.fieldsToDelete, function (m) {
return m.destroy({ return m.destroy({
success: function(model, response) { success: function (model, response) {
AdminFieldApp.fieldsToDelete = _.filter(AdminFieldApp.fieldsToDelete, function(m){ AdminFieldApp.fieldsToDelete = _.filter(AdminFieldApp.fieldsToDelete, function (m) {
return model.get("id") !== m.get("id"); return model.get("id") !== m.get("id");
}); });
}, },
error: function(xhr, textStatus, errorThrown) { error: function (xhr, textStatus, errorThrown) {
new AlertView({ new AlertView({
alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong") alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong")
}).render(); }).render();
} }
}); });
})).done( })).done(
function() { function () {
AdminFieldApp.fieldsCollection.save({ AdminFieldApp.fieldsCollection.save({
success: function(fields) { success: function (fields) {
// reset collection with new one // reset collection with new one
AdminFieldApp.fieldsCollection.reset(fields); AdminFieldApp.fieldsCollection.reset(fields);
@@ -63,12 +63,12 @@ define([
delay: 2000 delay: 2000
}).render(); }).render();
}, },
error: function(xhr, textStatus, errorThrown) { error: function (xhr, textStatus, errorThrown) {
new AlertView({ new AlertView({
alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong") alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong")
}).render(); }).render();
} }
}).done(function() { }).done(function () {
self._loadingState(false); self._loadingState(false);
}); });
} }
@@ -84,18 +84,18 @@ define([
return this; return this;
}, },
updateStateButton: function() { updateStateButton: function () {
this._disableSaveButton(!this._isModelDesync()); this._disableSaveButton(!this._isModelDesync());
}, },
// check whether model has changed or not // check whether model has changed or not
_isModelDesync: function () { _isModelDesync: function () {
return "undefined" !== typeof AdminFieldApp.fieldsCollection.find(function(model) { return "undefined" !== typeof AdminFieldApp.fieldsCollection.find(function (model) {
return !_.isEmpty(model.previousAttributes()); return !_.isEmpty(model.previousAttributes());
}); });
}, },
// create a transparent overlay on top of the application // create a transparent overlay on top of the application
_overlay: function(showOrHide) { _overlay: function (showOrHide) {
if(showOrHide && !this.$overlay) { if (showOrHide && !this.$overlay) {
this.$overlay = $("<div>").addClass("overlay"); this.$overlay = $("<div>").addClass("overlay");
AdminFieldApp.$bottom.append(this.$overlay); AdminFieldApp.$bottom.append(this.$overlay);
} else if (!showOrHide && this.$overlay) { } else if (!showOrHide && this.$overlay) {
@@ -107,7 +107,7 @@ define([
$("button.save-all", this.$el).attr("disabled", active); $("button.save-all", this.$el).attr("disabled", active);
}, },
// put application on loading state (add overlay, add spinner, disable global save button) // put application on loading state (add overlay, add spinner, disable global save button)
_loadingState: function(active) { _loadingState: function (active) {
if (active) { if (active) {
$(".save-block", AdminFieldApp.$top).addClass("loading"); $(".save-block", AdminFieldApp.$top).addClass("loading");
$(".block-alert", AdminFieldApp.$top).empty(); $(".block-alert", AdminFieldApp.$top).empty();

View File

@@ -12,24 +12,27 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, LoginForm) { ], function ($, i18n, Common, LoginForm) {
Common.initialize(); Common.initialize();
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
new LoginForm({ new LoginForm({
el : $("form[name=loginForm]"), el: $("form[name=loginForm]"),
rules: [{ rules: [
{
name: "login", name: "login",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password", name: "password",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
}] }
]
}); });
}); });
}); });

View File

@@ -14,28 +14,28 @@ define([
"backbone", "backbone",
"bootstrap", "bootstrap",
"multiselect" "multiselect"
], function($, _, i18n, Backbone, bootstrap, multiselect) { ], function ($, _, i18n, Backbone, bootstrap, multiselect) {
var initialize = function() { var initialize = function () {
// close alerts // close alerts
$(document).on("click", ".alert .alert-block-close a", function(e){ $(document).on("click", ".alert .alert-block-close a", function (e) {
e.preventDefault(); e.preventDefault();
$(this).closest('.alert').alert('close'); $(this).closest('.alert').alert('close');
return false; return false;
}); });
$("select[multiple='multiple']").multiselect({ $("select[multiple='multiple']").multiselect({
buttonWidth : "100%", buttonWidth: "100%",
buttonClass: 'btn btn-inverse', buttonClass: 'btn btn-inverse',
maxHeight: 185, maxHeight: 185,
includeSelectAllOption: true, includeSelectAllOption: true,
selectAllValue: 'all', selectAllValue: 'all',
selectAllText: i18n.t("all_collections"), selectAllText: i18n.t("all_collections"),
buttonText: function(options, select) { buttonText: function (options, select) {
if (options.length === 0) { if (options.length === 0) {
return i18n.t("no_collection_selected") + '<b class="caret"></b>'; return i18n.t("no_collection_selected") + '<b class="caret"></b>';
} else { } else {
return i18n.t( return i18n.t(
options.length === 1 ? "one_collection_selected": "collections_selected", { options.length === 1 ? "one_collection_selected" : "collections_selected", {
postProcess: "sprintf", postProcess: "sprintf",
sprintf: [options.length] sprintf: [options.length]
}) + ' <b class="caret"></b>'; }) + ' <b class="caret"></b>';

View File

@@ -21,11 +21,11 @@ require.config({
"jquery.geonames": "../assets/geonames-server-jquery-plugin/jquery.geonames" "jquery.geonames": "../assets/geonames-server-jquery-plugin/jquery.geonames"
}, },
shim: { shim: {
bootstrap : ["jquery"], bootstrap: ["jquery"],
jqueryui: { jqueryui: {
deps: ["jquery"] deps: ["jquery"]
}, },
"jquery.geonames" : { "jquery.geonames": {
deps: ['jquery', 'jqueryui'], deps: ['jquery', 'jqueryui'],
exports: '$.fn.geocompleter' exports: '$.fn.geocompleter'
}, },

View File

@@ -12,24 +12,27 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, ForgotPassWordForm) { ], function ($, i18n, Common, ForgotPassWordForm) {
Common.initialize(); Common.initialize();
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
new ForgotPassWordForm({ new ForgotPassWordForm({
el : $("form[name=forgottenPasswordForm]"), el: $("form[name=forgottenPasswordForm]"),
rules: [{ rules: [
{
name: "email", name: "email",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "email", name: "email",
rules: "valid_email", rules: "valid_email",
message: i18n.t("validation_email") message: i18n.t("validation_email")
}] }
]
}); });
}); });
}); });

View File

@@ -12,24 +12,27 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, LoginForm) { ], function ($, i18n, Common, LoginForm) {
Common.initialize(); Common.initialize();
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
new LoginForm({ new LoginForm({
el : $("form[name=loginForm]"), el: $("form[name=loginForm]"),
rules: [{ rules: [
{
name: "login", name: "login",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password", name: "password",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
}] }
]
}); });
}); });
}); });

View File

@@ -12,24 +12,27 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, LoginForm) { ], function ($, i18n, Common, LoginForm) {
Common.initialize(); Common.initialize();
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
new LoginForm({ new LoginForm({
el : $("form[name=loginForm]"), el: $("form[name=loginForm]"),
rules: [{ rules: [
{
name: "login", name: "login",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password", name: "password",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
}] }
]
}); });
}); });
}); });

View File

@@ -12,24 +12,27 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, LoginForm) { ], function ($, i18n, Common, LoginForm) {
Common.initialize(); Common.initialize();
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
new LoginForm({ new LoginForm({
el : $("form[name=loginForm]"), el: $("form[name=loginForm]"),
rules: [{ rules: [
{
name: "login", name: "login",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password", name: "password",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
}] }
]
}); });
}); });
}); });

View File

@@ -12,31 +12,35 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/formType/passwordSetter" "common/forms/views/formType/passwordSetter"
], function($, i18n, Common, RenewPassword) { ], function ($, i18n, Common, RenewPassword) {
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
Common.initialize(); Common.initialize();
new RenewPassword({ new RenewPassword({
el : $("form[name=passwordRenewForm]"), el: $("form[name=passwordRenewForm]"),
rules: [{ rules: [
{
name: "password[password]", name: "password[password]",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password[password]", name: "password[password]",
rules: "min_length[5]", rules: "min_length[5]",
message: i18n.t("validation_length_min", { message: i18n.t("validation_length_min", {
postProcess: "sprintf", postProcess: "sprintf",
sprintf: ["5"] sprintf: ["5"]
}) })
},{ },
{
name: "password[confirm]", name: "password[confirm]",
rules: "matches[password[password]]", rules: "matches[password[password]]",
message: i18n.t("password_match") message: i18n.t("password_match")
}] }
]
}); });
}); });
}); });

View File

@@ -14,52 +14,59 @@ require([
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/formType/passwordSetter", "common/forms/views/formType/passwordSetter",
"common/geonames" "common/geonames"
], function($, i18n, Common, RegisterForm, geonames) { ], function ($, i18n, Common, RegisterForm, geonames) {
var fieldsConfiguration = []; var fieldsConfiguration = [];
$.when.apply($, [ $.when.apply($, [
$.ajax({ $.ajax({
url: '/login/registration-fields/', url: '/login/registration-fields/',
success: function(config) { success: function (config) {
fieldsConfiguration = config; fieldsConfiguration = config;
} }
}) })
]).done(function(){ ]).done(function () {
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
Common.initialize(); Common.initialize();
var rules = [{ var rules = [
{
name: "email", name: "email",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "email", name: "email",
rules: "valid_email", rules: "valid_email",
message: i18n.t("validation_email") message: i18n.t("validation_email")
},{ },
{
name: "password[password]", name: "password[password]",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password[password]", name: "password[password]",
rules: "min_length[5]", rules: "min_length[5]",
message: i18n.t("validation_length_min", { message: i18n.t("validation_length_min", {
postProcess: "sprintf", postProcess: "sprintf",
sprintf: ["5"] sprintf: ["5"]
}) })
},{ },
{
name: "password[confirm]", name: "password[confirm]",
rules: "matches[password[password]]", rules: "matches[password[password]]",
message: i18n.t("password_match") message: i18n.t("password_match")
},{ },
{
name: "accept-tou", name: "accept-tou",
rules: "required", rules: "required",
message: i18n.t("accept_tou"), message: i18n.t("accept_tou"),
type: "checkbox" type: "checkbox"
},{ },
{
name: "collections[]", name: "collections[]",
rules: "min_length[1]", rules: "min_length[1]",
message: i18n.t("validation_choice_min", { message: i18n.t("validation_choice_min", {
@@ -67,9 +74,10 @@ require([
sprintf: ["1"] sprintf: ["1"]
}), }),
type: "multiple" type: "multiple"
}]; }
];
_.each(fieldsConfiguration, function(field) { _.each(fieldsConfiguration, function (field) {
if (field.required) { if (field.required) {
var rule = { var rule = {
"name": field.name, "name": field.name,
@@ -84,7 +92,7 @@ require([
var $form = $("form[name=registerForm]"); var $form = $("form[name=registerForm]");
new RegisterForm({ new RegisterForm({
el : $form, el: $form,
rules: rules rules: rules
}); });
@@ -92,7 +100,7 @@ require([
"server": $form.data("geonames-server-adress"), "server": $form.data("geonames-server-adress"),
"limit": 40, "limit": 40,
"init-input": false, "init-input": false,
"onInit": function(input, autoinput) { "onInit": function (input, autoinput) {
// Set default name to geonameid-completer // Set default name to geonameid-completer
autoinput.prop("name", "geonameid-completer"); autoinput.prop("name", "geonameid-completer");
} }
@@ -106,7 +114,7 @@ require([
}); });
// On open menu calculate max-width // On open menu calculate max-width
geocompleter.geocompleter("autocompleter", "on", "autocompleteopen", function(event, ui) { geocompleter.geocompleter("autocompleter", "on", "autocompleteopen", function (event, ui) {
$(this).autocomplete("widget").css("min-width", geocompleter.closest(".input-table").outerWidth()); $(this).autocomplete("widget").css("min-width", geocompleter.closest(".input-table").outerWidth());
}); });
}); });

View File

@@ -13,7 +13,7 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, RegisterForm) { ], function ($, i18n, Common, RegisterForm) {
Common.initialize(); Common.initialize();
var fieldsConfiguration = []; var fieldsConfiguration = [];
@@ -21,44 +21,51 @@ require([
$.when.apply($, [ $.when.apply($, [
$.ajax({ $.ajax({
url: '/login/registration-fields/', url: '/login/registration-fields/',
success: function(config) { success: function (config) {
fieldsConfiguration = config; fieldsConfiguration = config;
} }
}) })
]).done(function(){ ]).done(function () {
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
var rules = [{ var rules = [
{
name: "email", name: "email",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "email", name: "email",
rules: "valid_email", rules: "valid_email",
message: i18n.t("validation_email") message: i18n.t("validation_email")
},{ },
{
name: "password", name: "password",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password", name: "password",
rules: "min_length[5]", rules: "min_length[5]",
message: i18n.t("validation_length_min", { message: i18n.t("validation_length_min", {
postProcess: "sprintf", postProcess: "sprintf",
sprintf: ["5"] sprintf: ["5"]
}) })
},{ },
{
name: "passwordConfirm", name: "passwordConfirm",
rules: "matches[password]", rules: "matches[password]",
message: i18n.t("password_match") message: i18n.t("password_match")
},{ },
{
name: "accept-tou", name: "accept-tou",
rules: "required", rules: "required",
message: i18n.t("accept_tou"), message: i18n.t("accept_tou"),
type: "checkbox" type: "checkbox"
},{ },
{
name: "collections[]", name: "collections[]",
rules: "min_length[1]", rules: "min_length[1]",
message: i18n.t("validation_choice_min", { message: i18n.t("validation_choice_min", {
@@ -66,9 +73,10 @@ require([
sprintf: ["1"] sprintf: ["1"]
}), }),
type: "multiple" type: "multiple"
}]; }
];
_.each(fieldsConfiguration, function(field) { _.each(fieldsConfiguration, function (field) {
if (field.required) { if (field.required) {
var rule = { var rule = {
"name": field.name, "name": field.name,
@@ -81,7 +89,7 @@ require([
}); });
new RegisterForm({ new RegisterForm({
el : $("form[name=registerForm]"), el: $("form[name=registerForm]"),
rules: rules rules: rules
}); });
}); });

View File

@@ -12,36 +12,41 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/form" "common/forms/views/form"
], function($, i18n, Common, RenewEmail) { ], function ($, i18n, Common, RenewEmail) {
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
Common.initialize(); Common.initialize();
new RenewEmail({ new RenewEmail({
el : $("form[name=changeEmail]"), el: $("form[name=changeEmail]"),
errorTemplate: "#field_errors_block", errorTemplate: "#field_errors_block",
onRenderError: function(name, $el) { onRenderError: function (name, $el) {
$el.closest(".control-group").addClass("error"); $el.closest(".control-group").addClass("error");
}, },
rules: [{ rules: [
{
name: "form_password", name: "form_password",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "form_email", name: "form_email",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "form_email", name: "form_email",
rules: "email", rules: "email",
message: i18n.t("validation_email") message: i18n.t("validation_email")
},{ },
{
name: "form_email_confirm", name: "form_email_confirm",
rules: "matches[form_email]", rules: "matches[form_email]",
message: i18n.t("email_match") message: i18n.t("email_match")
}] }
]
}); });
}); });
}); });

View File

@@ -12,35 +12,40 @@ require([
"i18n", "i18n",
"apps/login/home/common", "apps/login/home/common",
"common/forms/views/formType/passwordSetter" "common/forms/views/formType/passwordSetter"
], function($, i18n, Common, RenewPassword) { ], function ($, i18n, Common, RenewPassword) {
i18n.init({ i18n.init({
resGetPath: Common.languagePath, resGetPath: Common.languagePath,
useLocalStorage: true useLocalStorage: true
}, function() { }, function () {
Common.initialize(); Common.initialize();
new RenewPassword({ new RenewPassword({
el : $("form[name=passwordChangeForm]"), el: $("form[name=passwordChangeForm]"),
rules: [{ rules: [
{
name: "oldPassword", name: "oldPassword",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password[password]", name: "password[password]",
rules: "required", rules: "required",
message: i18n.t("validation_blank") message: i18n.t("validation_blank")
},{ },
{
name: "password[password]", name: "password[password]",
rules: "min_length[5]", rules: "min_length[5]",
message: i18n.t("validation_length_min", { message: i18n.t("validation_length_min", {
postProcess: "sprintf", postProcess: "sprintf",
sprintf: ["5"] sprintf: ["5"]
}) })
},{ },
{
name: "password[confirm]", name: "password[confirm]",
rules: "matches[password[password]]", rules: "matches[password[password]]",
message: i18n.t("password_match") message: i18n.t("password_match")
}] }
]
}); });
}); });
}); });

View File

@@ -11,8 +11,8 @@ define([
"jquery", "jquery",
"underscore", "underscore",
"backbone" "backbone"
], function($, _, Backbone) { ], function ($, _, Backbone) {
var FormValidator = function(rules, handlers) { var FormValidator = function (rules, handlers) {
// rules setted by user // rules setted by user
this.rules = rules || []; this.rules = rules || [];
// custom callbacks // custom callbacks
@@ -22,7 +22,7 @@ define([
var self = this; var self = this;
_.each(this.rules, function(field) { _.each(this.rules, function (field) {
if ("name" in field && "rules" in field) { if ("name" in field && "rules" in field) {
self._addField(field); self._addField(field);
} }
@@ -30,16 +30,16 @@ define([
}; };
// Validate method, argument is the serialize form // Validate method, argument is the serialize form
FormValidator.prototype.validate = function(inputs) { FormValidator.prototype.validate = function (inputs) {
var self = this; var self = this;
// possible errors // possible errors
this.errors = []; this.errors = [];
// inputs present in form // inputs present in form
this.inputs = {}; this.inputs = {};
_.each(_.groupBy(inputs, function(input){ _.each(_.groupBy(inputs, function (input) {
return input.name; return input.name;
}), function(fields, name) { }), function (fields, name) {
self.inputs[name] = fields; self.inputs[name] = fields;
}); });
@@ -48,19 +48,19 @@ define([
return this; return this;
}; };
FormValidator.prototype.getErrors = function() { FormValidator.prototype.getErrors = function () {
return this.errors; return this.errors;
}; };
FormValidator.prototype.hasErrors = function() { FormValidator.prototype.hasErrors = function () {
return this.errors.length > 0; return this.errors.length > 0;
}; };
FormValidator.prototype.getRules = function() { FormValidator.prototype.getRules = function () {
return this.rules; return this.rules;
}; };
FormValidator.prototype._addField = function(field) { FormValidator.prototype._addField = function (field) {
this.fields.push({ this.fields.push({
name: field.name, name: field.name,
rules: field.rules, rules: field.rules,
@@ -70,15 +70,15 @@ define([
}); });
}; };
FormValidator.prototype._validateForm = function() { FormValidator.prototype._validateForm = function () {
var self = this; var self = this;
this.errors = []; this.errors = [];
_.each(this.fields, function(field){ _.each(this.fields, function (field) {
if (_.has(self.inputs, field.name)) { if (_.has(self.inputs, field.name)) {
// values can be multiple // values can be multiple
var values = []; var values = [];
_.each(self.inputs[field.name], function(field){ _.each(self.inputs[field.name], function (field) {
return values.push(field.value); return values.push(field.value);
}); });
@@ -92,13 +92,13 @@ define([
}); });
}; };
FormValidator.prototype._validateField = function(field) { FormValidator.prototype._validateField = function (field) {
var self = this; var self = this;
var ruleRegex = /^(.+?)\[(.+)\]$/; var ruleRegex = /^(.+?)\[(.+)\]$/;
var rules = field.rules.split('|'); var rules = field.rules.split('|');
// Run through the rules and execute the validation methods as needed // Run through the rules and execute the validation methods as needed
_.every(rules, function(method) { _.every(rules, function (method) {
var param = null; var param = null;
var failed = false; var failed = false;
var parts = ruleRegex.exec(method); var parts = ruleRegex.exec(method);
@@ -141,32 +141,32 @@ define([
}; };
FormValidator.prototype.Regexp = { FormValidator.prototype.Regexp = {
numericRegex : /^[0-9]+$/, numericRegex: /^[0-9]+$/,
integerRegex : /^\-?[0-9]+$/, integerRegex: /^\-?[0-9]+$/,
decimalRegex : /^\-?[0-9]*\.?[0-9]+$/, decimalRegex: /^\-?[0-9]*\.?[0-9]+$/,
emailRegex : /^[^@]+@[^@]+\.[^@]+$/, emailRegex: /^[^@]+@[^@]+\.[^@]+$/,
alphaRegex : /^[a-z]+$/i, alphaRegex: /^[a-z]+$/i,
alphaNumericRegex : /^[a-z0-9]+$/i, alphaNumericRegex: /^[a-z0-9]+$/i,
alphaDashRegex : /^[a-z0-9_\-]+$/i, alphaDashRegex: /^[a-z0-9_\-]+$/i,
naturalRegex : /^[0-9]+$/i, naturalRegex: /^[0-9]+$/i,
naturalNoZeroRegex : /^[1-9][0-9]*$/i, naturalNoZeroRegex: /^[1-9][0-9]*$/i,
// IP v6 a v4 or hostname, by Mikulas Dite see http://stackoverflow.com/a/9209720/96656 // IP v6 a v4 or hostname, by Mikulas Dite see http://stackoverflow.com/a/9209720/96656
ipRegex : /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^(?:(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-fA-F]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,1}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,2}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,3}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:[0-9a-fA-F]{1,4})):)(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,4}(?:(?:[0-9a-fA-F]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,5}(?:(?:[0-9a-fA-F]{1,4})))?::)(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,6}(?:(?:[0-9a-fA-F]{1,4})))?::))))$/i, ipRegex: /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^(?:(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){6})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:::(?:(?:(?:[0-9a-fA-F]{1,4})):){5})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){4})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,1}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){3})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,2}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:(?:[0-9a-fA-F]{1,4})):){2})(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,3}(?:(?:[0-9a-fA-F]{1,4})))?::(?:(?:[0-9a-fA-F]{1,4})):)(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,4}(?:(?:[0-9a-fA-F]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,5}(?:(?:[0-9a-fA-F]{1,4})))?::)(?:(?:[0-9a-fA-F]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-fA-F]{1,4})):){0,6}(?:(?:[0-9a-fA-F]{1,4})))?::))))$/i,
numericDashRegex : /^[\d\-\s]+$/, numericDashRegex: /^[\d\-\s]+$/,
urlRegex : /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/ urlRegex: /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/
}; };
// Object containing all of the validation hooks // Object containing all of the validation hooks
FormValidator.prototype._hooks = { FormValidator.prototype._hooks = {
"required": function(field) { "required": function (field) {
var value = field.value; var value = field.value;
return (value !== null && value !== ''); return (value !== null && value !== '');
}, },
"equal": function(field, defaultName) { "equal": function (field, defaultName) {
return field.value === defaultName; return field.value === defaultName;
}, },
"matches": function(field, matchName) { "matches": function (field, matchName) {
if (typeof this.inputs[matchName] === "undefined") { if (typeof this.inputs[matchName] === "undefined") {
return false; return false;
} }
@@ -179,10 +179,10 @@ define([
return false; return false;
}, },
"valid_email": function(field) { "valid_email": function (field) {
return this.Regexp.emailRegex.test(field.value); return this.Regexp.emailRegex.test(field.value);
}, },
"valid_emails": function(field) { "valid_emails": function (field) {
var result = field.value.split(","); var result = field.value.split(",");
for (var i = 0; i < result.length; i++) { for (var i = 0; i < result.length; i++) {
@@ -193,9 +193,11 @@ define([
return true; return true;
}, },
"min_length": function(field, length) { "min_length": function (field, length) {
if (field.type === "multiple") { if (field.type === "multiple") {
return _.filter(field.value.split(","), function(value){ return value !== ""; }).length >= parseInt(length, 10) return _.filter(field.value.split(","),function (value) {
return value !== "";
}).length >= parseInt(length, 10)
} }
if (!this.Regexp.numericRegex.test(length)) { if (!this.Regexp.numericRegex.test(length)) {
@@ -204,9 +206,11 @@ define([
return (field.value.length >= parseInt(length, 10)); return (field.value.length >= parseInt(length, 10));
}, },
"max_length": function(field, length) { "max_length": function (field, length) {
if (field.type === "multiple") { if (field.type === "multiple") {
return _.filter(field.value.split(","), function(value){ return value !== ""; }).length <= parseInt(length, 10) return _.filter(field.value.split(","),function (value) {
return value !== "";
}).length <= parseInt(length, 10)
} }
if (!this.Regexp.numericRegex.test(length)) { if (!this.Regexp.numericRegex.test(length)) {
@@ -215,9 +219,11 @@ define([
return (field.value.length <= parseInt(length, 10)); return (field.value.length <= parseInt(length, 10));
}, },
"exact_length": function(field, length) { "exact_length": function (field, length) {
if (field.type === "multiple") { if (field.type === "multiple") {
return _.filter(field.value.split(","), function(value){ return value !== ""; }).length === parseInt(length, 10) return _.filter(field.value.split(","),function (value) {
return value !== "";
}).length === parseInt(length, 10)
} }
if (!this.Regexp.numericRegex.test(length)) { if (!this.Regexp.numericRegex.test(length)) {
@@ -226,48 +232,48 @@ define([
return (field.value.length === parseInt(length, 10)); return (field.value.length === parseInt(length, 10));
}, },
"greater_than": function(field, param) { "greater_than": function (field, param) {
if (!this.Regexp.decimalRegex.test(field.value)) { if (!this.Regexp.decimalRegex.test(field.value)) {
return false; return false;
} }
return (parseFloat(field.value) > parseFloat(param)); return (parseFloat(field.value) > parseFloat(param));
}, },
"less_than": function(field, param) { "less_than": function (field, param) {
if (!this.Regexp.decimalRegex.test(field.value)) { if (!this.Regexp.decimalRegex.test(field.value)) {
return false; return false;
} }
return (parseFloat(field.value) < parseFloat(param)); return (parseFloat(field.value) < parseFloat(param));
}, },
"alpha": function(field) { "alpha": function (field) {
return (this.Regexp.alphaRegex.test(field.value)); return (this.Regexp.alphaRegex.test(field.value));
}, },
"alpha_numeric": function(field) { "alpha_numeric": function (field) {
return (this.Regexp.alphaNumericRegex.test(field.value)); return (this.Regexp.alphaNumericRegex.test(field.value));
}, },
"alpha_dash": function(field) { "alpha_dash": function (field) {
return (this.Regexp.alphaDashRegex.test(field.value)); return (this.Regexp.alphaDashRegex.test(field.value));
}, },
"numeric": function(field) { "numeric": function (field) {
return (this.Regexp.numericRegex.test(field.value)); return (this.Regexp.numericRegex.test(field.value));
}, },
"integer": function(field) { "integer": function (field) {
return (this.Regexp.integerRegex.test(field.value)); return (this.Regexp.integerRegex.test(field.value));
}, },
"decimal": function(field) { "decimal": function (field) {
return (this.Regexp.decimalRegex.test(field.value)); return (this.Regexp.decimalRegex.test(field.value));
}, },
"is_natural": function(field) { "is_natural": function (field) {
return (this.Regexp.naturalRegex.test(field.value)); return (this.Regexp.naturalRegex.test(field.value));
}, },
"is_natural_no_zero": function(field) { "is_natural_no_zero": function (field) {
return (this.Regexp.naturalNoZeroRegex.test(field.value)); return (this.Regexp.naturalNoZeroRegex.test(field.value));
}, },
"valid_ip": function(field) { "valid_ip": function (field) {
return (this.Regexp.ipRegex.test(field.value)); return (this.Regexp.ipRegex.test(field.value));
}, },
"valid_url": function(field) { "valid_url": function (field) {
return (this.Regexp.urlRegex.test(field.value)); return (this.Regexp.urlRegex.test(field.value));
} }
}; };

View File

@@ -11,11 +11,11 @@ define([
"jquery", "jquery",
"underscore", "underscore",
"backbone" "backbone"
], function($, _, Backbone) { ], function ($, _, Backbone) {
var ErrorView = Backbone.View.extend({ var ErrorView = Backbone.View.extend({
tagName: "div", tagName: "div",
initialize: function(options) { initialize: function (options) {
options = options || {}; options = options || {};
if (false === "name" in options) { if (false === "name" in options) {
throw "Missing name attribute in error view"; throw "Missing name attribute in error view";
@@ -28,11 +28,11 @@ define([
this.name = options.name; this.name = options.name;
this.errorTemplate = options.errorTemplate; this.errorTemplate = options.errorTemplate;
this.errors = options.errors || {}; this.errors = options.errors || {};
this.onRenderError = options.onRenderError || null; this.onRenderError = options.onRenderError || null;
}, },
render: function() { render: function () {
if (this.errors.length > 0 ) { if (this.errors.length > 0) {
var template = _.template($(this.errorTemplate).html(), { var template = _.template($(this.errorTemplate).html(), {
errors: this.errors errors: this.errors
}); });
@@ -54,7 +54,7 @@ define([
return this; return this;
}, },
reset: function() { reset: function () {
this.$el.empty(); this.$el.empty();
} }
}); });

View File

@@ -14,13 +14,13 @@ define([
"bootstrap", "bootstrap",
"common/forms/validator", "common/forms/validator",
"common/forms/views/input" "common/forms/views/input"
], function($, _, Backbone, bootstrap, Validator, InputView) { ], function ($, _, Backbone, bootstrap, Validator, InputView) {
var Form = Backbone.View.extend({ var Form = Backbone.View.extend({
events: { events: {
"submit": "_onSubmit" "submit": "_onSubmit"
}, },
initialize: function(options) { initialize: function (options) {
options = options || {}; options = options || {};
var self = this; var self = this;
@@ -49,7 +49,7 @@ define([
// cancel submit // cancel submit
event.preventDefault(); event.preventDefault();
// group errors by input // group errors by input
_.each(_.groupBy(this.validator.getErrors(), function(error){ _.each(_.groupBy(this.validator.getErrors(), function (error) {
return error.name; return error.name;
}), function (errors, name) { }), function (errors, name) {
// show new errors in the views // show new errors in the views
@@ -66,17 +66,17 @@ define([
}); });
} }
}, },
_resetInputErrors: function() { _resetInputErrors: function () {
_.each(this.inputViews, function(view) { _.each(this.inputViews, function (view) {
view.resetErrors(); view.resetErrors();
}); });
}, },
_addInputView: function(input) { _addInputView: function (input) {
var name = input.name; var name = input.name;
this.inputViews[name] = new InputView({ this.inputViews[name] = new InputView({
name: name, name: name,
el : $("input[name='"+name+"'], select[name='"+name+"'], textarea[name='"+name+"']", this.$el).first().closest("div"), el: $("input[name='" + name + "'], select[name='" + name + "'], textarea[name='" + name + "']", this.$el).first().closest("div"),
errorTemplate: this.errorTemplate, errorTemplate: this.errorTemplate,
onRenderError: this.onRenderError onRenderError: this.onRenderError
}); });

View File

@@ -14,14 +14,14 @@ define([
"backbone", "backbone",
"bootstrap", "bootstrap",
"common/forms/views/form" "common/forms/views/form"
], function($, _, i18n, Backbone, bootstrap, FormView) { ], function ($, _, i18n, Backbone, bootstrap, FormView) {
var PasswordSetterForm = FormView.extend({ var PasswordSetterForm = FormView.extend({
events: function(){ events: function () {
return _.extend({},FormView.prototype.events,{ return _.extend({}, FormView.prototype.events, {
'keyup input[type=password]' : 'onPasswordKeyup' 'keyup input[type=password]': 'onPasswordKeyup'
}); });
}, },
onPasswordKeyup : function(event) { onPasswordKeyup: function (event) {
var input = $(event.target); var input = $(event.target);
var password = input.val(); var password = input.val();
var inputView = this.inputViews[input.attr("name")]; var inputView = this.inputViews[input.attr("name")];
@@ -34,7 +34,7 @@ define([
}; };
var result = ""; var result = "";
if (password.length > 0 ) { if (password.length > 0) {
var passMeter = zxcvbn(input.val()); var passMeter = zxcvbn(input.val());
switch (passMeter.score) { switch (passMeter.score) {

View File

@@ -13,10 +13,10 @@ define([
"backbone", "backbone",
"common/forms/views/error", "common/forms/views/error",
"common/multiviews" "common/multiviews"
], function($, _, Backbone, ErrorView, MultiViews) { ], function ($, _, Backbone, ErrorView, MultiViews) {
var InputView = Backbone.View.extend(_.extend({}, MultiViews, { var InputView = Backbone.View.extend(_.extend({}, MultiViews, {
initialize: function(options) { initialize: function (options) {
options = options || {}; options = options || {};
if (false === "name" in options) { if (false === "name" in options) {
throw "Missing name attribute in input view"; throw "Missing name attribute in input view";
@@ -35,7 +35,7 @@ define([
}); });
}, },
render: function () { render: function () {
this._assignView({".error-view" : this.errorView}); this._assignView({".error-view": this.errorView});
}, },
showErrors: function (errors) { showErrors: function (errors) {
this.render(); this.render();

View File

@@ -1,4 +1,5 @@
;(function (root, factory) { ;
(function (root, factory) {
if (typeof define === 'function' && define.amd) { if (typeof define === 'function' && define.amd) {
define([''], factory); define([''], factory);
} else { } else {
@@ -6,33 +7,33 @@
} }
}(this, function () { }(this, function () {
return { return {
init: function($field, options) { init: function ($field, options) {
var geocompleter = $field.geocompleter(options); var geocompleter = $field.geocompleter(options);
// On focus add select-state // On focus add select-state
geocompleter.geocompleter("autocompleter", "on", "autocompletefocus", function(event, ui) { geocompleter.geocompleter("autocompleter", "on", "autocompletefocus", function (event, ui) {
$("li", $(event.originalEvent.target)).closest("li").removeClass("selected"); $("li", $(event.originalEvent.target)).closest("li").removeClass("selected");
$("a.ui-state-active, a.ui-state-hover, a.ui-state-focus", $(event.originalEvent.target)).closest("li").addClass("selected"); $("a.ui-state-active, a.ui-state-hover, a.ui-state-focus", $(event.originalEvent.target)).closest("li").addClass("selected");
}); });
// On search request add loading-state // On search request add loading-state
geocompleter.geocompleter("autocompleter", "on", "autocompletesearch", function(event, ui) { geocompleter.geocompleter("autocompleter", "on", "autocompletesearch", function (event, ui) {
$(this).addClass('input-loading'); $(this).addClass('input-loading');
$(this).removeClass('input-error'); $(this).removeClass('input-error');
}); });
// On response remove loading-state // On response remove loading-state
geocompleter.geocompleter("autocompleter", "on", "autocompleteresponse", function(event, ui) { geocompleter.geocompleter("autocompleter", "on", "autocompleteresponse", function (event, ui) {
$(this).removeClass('input-loading'); $(this).removeClass('input-loading');
}); });
// On close menu remove loading-state // On close menu remove loading-state
geocompleter.geocompleter("autocompleter", "on", "autocompleteclose", function(event, ui) { geocompleter.geocompleter("autocompleter", "on", "autocompleteclose", function (event, ui) {
$(this).removeClass('input-loading'); $(this).removeClass('input-loading');
}); });
// On request error add error-state // On request error add error-state
geocompleter.geocompleter("autocompleter", "on", "geotocompleter.request.error", function(jqXhr, status, error) { geocompleter.geocompleter("autocompleter", "on", "geotocompleter.request.error", function (jqXhr, status, error) {
$(this).removeClass('input-loading'); $(this).removeClass('input-loading');
$(this).addClass('input-error'); $(this).addClass('input-error');
}); });

View File

@@ -11,10 +11,10 @@ define([
"jquery", "jquery",
"underscore", "underscore",
"backbone" "backbone"
], function($, _, Backbone) { ], function ($, _, Backbone) {
return { return {
// bind a subview to a DOM element // bind a subview to a DOM element
"_assignView": function(selector, view) { "_assignView": function (selector, view) {
var selectors; var selectors;
if (_.isObject(selector)) { if (_.isObject(selector)) {
selectors = selector; selectors = selector;
@@ -23,7 +23,7 @@ define([
selectors[selector] = view; selectors[selector] = view;
} }
if (!selectors) return; if (!selectors) return;
_.each(selectors, function(view, selector) { _.each(selectors, function (view, selector) {
view.setElement(this.$(selector)).render(); view.setElement(this.$(selector)).render();
}, this); }, this);
} }

View File

@@ -10,7 +10,7 @@
define([ define([
"underscore", "underscore",
"backbone" "backbone"
], function(_, Backbone) { ], function (_, Backbone) {
var DcFieldModel = Backbone.Model.extend({ var DcFieldModel = Backbone.Model.extend({
urlRoot: function () { urlRoot: function () {
return "/admin/fields/dc-fields"; return "/admin/fields/dc-fields";

View File

@@ -10,16 +10,16 @@
define([ define([
"underscore", "underscore",
"backbone" "backbone"
], function(_, Backbone) { ], function (_, Backbone) {
var FieldModel = Backbone.Model.extend({ var FieldModel = Backbone.Model.extend({
initialize : function(attributes, options) { initialize: function (attributes, options) {
attributes = attributes || {}; attributes = attributes || {};
if (typeof attributes === "object" && false === "sbas-id" in attributes) { if (typeof attributes === "object" && false === "sbas-id" in attributes) {
throw "You must set a sbas id"; throw "You must set a sbas id";
} }
}, },
urlRoot: function () { urlRoot: function () {
return "/admin/fields/"+ this.get("sbas-id") +"/fields"; return "/admin/fields/" + this.get("sbas-id") + "/fields";
}, },
defaults: { defaults: {
"business": false, "business": false,
@@ -36,10 +36,10 @@ define([
"vocabulary-type": null, "vocabulary-type": null,
"vocabulary-restricted": false, "vocabulary-restricted": false,
"labels": { "labels": {
"fr" : "", "fr": "",
"en" : "", "en": "",
"de" : "", "de": "",
"nl" : "" "nl": ""
} }
} }
}); });

View File

@@ -10,7 +10,7 @@
define([ define([
"underscore", "underscore",
"backbone" "backbone"
], function(_, Backbone) { ], function (_, Backbone) {
var VocabularyModel = Backbone.Model.extend({ var VocabularyModel = Backbone.Model.extend({
urlRoot: function () { urlRoot: function () {
return "/admin/fields/vocabularies"; return "/admin/fields/vocabularies";

View File

@@ -1,4 +1,4 @@
define(["chai"], function(shai) { define(["chai"], function (shai) {
window.expect = shai.expect; window.expect = shai.expect;
window.assert = shai.assert; window.assert = shai.assert;
}); });

View File

@@ -18,7 +18,7 @@ require.config({
bootstrap: "../skins/build/bootstrap/js/bootstrap.min" bootstrap: "../skins/build/bootstrap/js/bootstrap.min"
}, },
shim: { shim: {
bootstrap : ["jquery"], bootstrap: ["jquery"],
jqueryui: { jqueryui: {
deps: ["jquery"] deps: ["jquery"]
}, },
@@ -39,11 +39,12 @@ mocha.setup({
globals: ['js-fixtures'] globals: ['js-fixtures']
}); });
console = window.console || function() {}; console = window.console || function () {
};
window.notrack = true; window.notrack = true;
var runMocha = function() { var runMocha = function () {
if (window.mochaPhantomJS) { if (window.mochaPhantomJS) {
mochaPhantomJS.run(); mochaPhantomJS.run();
} else { } else {

View File

@@ -15,24 +15,7 @@ define([
'apps/admin/fields/views/modal', 'apps/admin/fields/views/modal',
'apps/admin/fields/views/save', 'apps/admin/fields/views/save',
'apps/admin/fields/views/dcField' 'apps/admin/fields/views/dcField'
], function( ], function (chai, fixtures, $, App, FieldModel, FieldCollection, DcFieldCollection, VocabularyCollection, SingleItemView, ListItemView, AlertView, EditView, FieldErrorView, ModalView, SaveView, DcFieldView) {
chai,
fixtures,
$,
App,
FieldModel,
FieldCollection,
DcFieldCollection,
VocabularyCollection,
SingleItemView,
ListItemView,
AlertView,
EditView,
FieldErrorView,
ModalView,
SaveView,
DcFieldView
) {
var expect = chai.expect; var expect = chai.expect;
var assert = chai.assert; var assert = chai.assert;
var should = chai.should(); var should = chai.should();
@@ -44,36 +27,36 @@ define([
App.initialize(); App.initialize();
describe("Admin field", function() { describe("Admin field", function () {
describe("Initialization", function() { describe("Initialization", function () {
it("should create a global variable", function() { it("should create a global variable", function () {
should.exist(AdminFieldApp); should.exist(AdminFieldApp);
}); });
}); });
describe("Collections", function() { describe("Collections", function () {
describe("DcField Collection", function() { describe("DcField Collection", function () {
beforeEach(function() { beforeEach(function () {
this.collection = new DcFieldCollection([]); this.collection = new DcFieldCollection([]);
}); });
it("should set collection url according to provided 'sbas-id'", function() { it("should set collection url according to provided 'sbas-id'", function () {
this.collection.url().should.equal("/admin/fields/dc-fields"); this.collection.url().should.equal("/admin/fields/dc-fields");
}); });
}); });
describe("Vocabulary Collection", function() { describe("Vocabulary Collection", function () {
beforeEach(function() { beforeEach(function () {
this.collection = new VocabularyCollection([]); this.collection = new VocabularyCollection([]);
}); });
it("should set collection url according to provided 'sbas-id'", function() { it("should set collection url according to provided 'sbas-id'", function () {
this.collection.url().should.equal("/admin/fields/vocabularies"); this.collection.url().should.equal("/admin/fields/vocabularies");
}); });
}); });
describe("Field Collection", function() { describe("Field Collection", function () {
beforeEach(function() { beforeEach(function () {
this.collection = new FieldCollection([ this.collection = new FieldCollection([
{"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"}, {"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"},
{"id": 2, "sbas-id": sbasId, "name": "Object", "tag": "XMP:Object"} {"id": 2, "sbas-id": sbasId, "name": "Object", "tag": "XMP:Object"}
@@ -82,24 +65,24 @@ define([
}); });
}); });
describe("Initialization", function() { describe("Initialization", function () {
it("should throw an exception if 'sbas_id' is missing", function() { it("should throw an exception if 'sbas_id' is missing", function () {
expect(function() { expect(function () {
new FieldCollection([]); new FieldCollection([]);
}).to.throw("You must set a sbas id"); }).to.throw("You must set a sbas id");
}); });
it("should set collection url according to provided 'sbas-id'", function() { it("should set collection url according to provided 'sbas-id'", function () {
this.collection.url().should.equal("/admin/fields/"+sbasId+"/fields"); this.collection.url().should.equal("/admin/fields/" + sbasId + "/fields");
}); });
}); });
describe("Methods", function() { describe("Methods", function () {
it("should retrieve categorie item if searching terms begins with 'cat'", function() { it("should retrieve categorie item if searching terms begins with 'cat'", function () {
this.collection.search('Cat')._wrapped.length.should.equal(1); this.collection.search('Cat')._wrapped.length.should.equal(1);
}); });
it("should retrieve previous and next index for given model", function() { it("should retrieve previous and next index for given model", function () {
expect(this.collection.previousIndex(this.collection.first())).to.be.null; expect(this.collection.previousIndex(this.collection.first())).to.be.null;
this.collection.nextIndex(this.collection.first()).should.equal(1); this.collection.nextIndex(this.collection.first()).should.equal(1);
this.collection.previousIndex(this.collection.last()).should.equal(0); this.collection.previousIndex(this.collection.last()).should.equal(0);
@@ -109,29 +92,29 @@ define([
}); });
}); });
describe("Views", function() { describe("Views", function () {
describe("Single Item Views", function() { describe("Single Item Views", function () {
beforeEach(function() { beforeEach(function () {
this.field = new FieldModel({"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"}); this.field = new FieldModel({"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
this.view = new SingleItemView({model: this.field}); this.view = new SingleItemView({model: this.field});
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a LI element", function() { it("should render as a LI element", function () {
this.view.render().el.nodeName.should.equal("LI"); this.view.render().el.nodeName.should.equal("LI");
}); });
it("should render as a LI element with proper properties", function() { it("should render as a LI element with proper properties", function () {
this.view.render().$el.find('.field-name').html().should.equal("Categorie"); this.view.render().$el.find('.field-name').html().should.equal("Categorie");
this.view.render().$el.find('.field-tag').html().should.equal("XMP:Categorie"); this.view.render().$el.find('.field-tag').html().should.equal("XMP:Categorie");
}); });
}); });
describe("List Item Views", function() { describe("List Item Views", function () {
beforeEach(function() { beforeEach(function () {
this.collection = new FieldCollection([ this.collection = new FieldCollection([
{"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"}, {"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"},
{"sbas-id": sbasId, "name": "Object", "tag": "XMP:Object"} {"sbas-id": sbasId, "name": "Object", "tag": "XMP:Object"}
@@ -145,41 +128,43 @@ define([
}); });
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a DIV block", function() { it("should render as a DIV block", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
}); });
it("should include list items for all models in collection", function() { it("should include list items for all models in collection", function () {
this.view.render(); this.view.render();
this.view.$el.find("li").should.have.length(2); this.view.$el.find("li").should.have.length(2);
}); });
}); });
describe("Alert Views", function() { describe("Alert Views", function () {
beforeEach(function() { beforeEach(function () {
this.view = new AlertView({alert: "info", message: "Hello world!"}); this.view = new AlertView({alert: "info", message: "Hello world!"});
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a DIV element", function() { it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
}); });
}); });
describe("DcField Views", function() { describe("DcField Views", function () {
beforeEach(function() { beforeEach(function () {
this.collection = new DcFieldCollection([{ this.collection = new DcFieldCollection([
{
"label": "Contributor", "label": "Contributor",
"definition": "An entity responsible for making contributions to the resource.", "definition": "An entity responsible for making contributions to the resource.",
"URI": "http://dublincore.org/documents/dces/#contributor" "URI": "http://dublincore.org/documents/dces/#contributor"
}, { },
{
"label": "Coverage", "label": "Coverage",
"definition": "The spatial or temporal topic of the resource, the spatial applicability of the resource,\n or the jurisdiction under which the resource\n is relevant.", "definition": "The spatial or temporal topic of the resource, the spatial applicability of the resource,\n or the jurisdiction under which the resource\n is relevant.",
"URI": "http://dublincore.org/documents/dces/#coverage" "URI": "http://dublincore.org/documents/dces/#coverage"
@@ -194,17 +179,17 @@ define([
}); });
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a DIV element", function() { it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
}); });
}); });
describe("Edit Views", function() { describe("Edit Views", function () {
beforeEach(function() { beforeEach(function () {
var model = new FieldModel({"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"}); var model = new FieldModel({"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
this.view = new EditView({"model": model}); this.view = new EditView({"model": model});
@@ -227,15 +212,15 @@ define([
AdminFieldApp.fieldListView.render(); AdminFieldApp.fieldListView.render();
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a DIV element", function() { it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
}); });
it("should not render an error message if provided tag is empty", function() { it("should not render an error message if provided tag is empty", function () {
var view = this.view.render(); var view = this.view.render();
view.$('input#tag').val("").blur(); view.$('input#tag').val("").blur();
@@ -243,7 +228,7 @@ define([
assert.isFalse(view.$('input#tag').closest(".control-group").hasClass("error")); assert.isFalse(view.$('input#tag').closest(".control-group").hasClass("error"));
}); });
it("should uncheck vocabulary restricted if provided vocabulary is empty", function() { it("should uncheck vocabulary restricted if provided vocabulary is empty", function () {
var view = this.view.render(); var view = this.view.render();
view.$('input#vocabulary-restricted').attr("checked", true); view.$('input#vocabulary-restricted').attr("checked", true);
@@ -253,22 +238,22 @@ define([
}); });
}); });
describe("FieldError Views", function() { describe("FieldError Views", function () {
beforeEach(function() { beforeEach(function () {
this.view = new FieldErrorView(); this.view = new FieldErrorView();
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a DIV element", function() { it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
}); });
}); });
describe("Modal Views", function() { describe("Modal Views", function () {
beforeEach(function() { beforeEach(function () {
var model = new FieldModel({"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"}); var model = new FieldModel({"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
this.view = new ModalView({ this.view = new ModalView({
@@ -277,34 +262,34 @@ define([
}); });
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
this.view.remove(); this.view.remove();
}); });
it("should render as a DIV element", function() { it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
this.view.remove(); this.view.remove();
}); });
}); });
describe("Save Views", function() { describe("Save Views", function () {
beforeEach(function() { beforeEach(function () {
this.view = new SaveView(); this.view = new SaveView();
}); });
it("render() should return the view object", function() { it("render() should return the view object", function () {
this.view.render().should.equal(this.view); this.view.render().should.equal(this.view);
}); });
it("should render as a DIV element", function() { it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV"); this.view.render().el.nodeName.should.equal("DIV");
}); });
}); });
}); });
describe("Edge cases", function() { describe("Edge cases", function () {
beforeEach(function() { beforeEach(function () {
AdminFieldApp.fieldsCollection.reset(); AdminFieldApp.fieldsCollection.reset();
AdminFieldApp.fieldsCollection.add({"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"}); AdminFieldApp.fieldsCollection.add({"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
AdminFieldApp.dcFieldsCollection.add({ AdminFieldApp.dcFieldsCollection.add({
@@ -324,7 +309,7 @@ define([
AdminFieldApp.fieldListView.render(); AdminFieldApp.fieldListView.render();
}); });
it("should update collection when model change", function() { it("should update collection when model change", function () {
AdminFieldApp.fieldListView.itemViews[0].clickAction(); AdminFieldApp.fieldListView.itemViews[0].clickAction();
AdminFieldApp.fieldEditView.model.set({ AdminFieldApp.fieldEditView.model.set({
"name": "new name" "name": "new name"
@@ -332,15 +317,17 @@ define([
assert.equal(AdminFieldApp.fieldListView.itemViews[0].model.get('name'), "new name", 'model is updated'); assert.equal(AdminFieldApp.fieldListView.itemViews[0].model.get('name'), "new name", 'model is updated');
}); });
it("should update edit view when clicking on single element", function() { it("should update edit view when clicking on single element", function () {
AdminFieldApp.fieldListView.itemViews[0].clickAction(); AdminFieldApp.fieldListView.itemViews[0].clickAction();
should.exist(AdminFieldApp.fieldEditView); should.exist(AdminFieldApp.fieldEditView);
assert.equal(AdminFieldApp.fieldEditView.model, AdminFieldApp.fieldListView.collection.first(), 'model is updated'); assert.equal(AdminFieldApp.fieldEditView.model, AdminFieldApp.fieldListView.collection.first(), 'model is updated');
}); });
it("should reorder collection on drop action", function() { it("should reorder collection on drop action", function () {
var ui = {item: {index: function() {return 2;}}}; var ui = {item: {index: function () {
AdminFieldApp.fieldListView.itemViews[0].dropAction({},ui); return 2;
}}};
AdminFieldApp.fieldListView.itemViews[0].dropAction({}, ui);
assert.equal(AdminFieldApp.fieldListView.collection.last().get('sorter'), 3, 'model is updated'); assert.equal(AdminFieldApp.fieldListView.collection.last().get('sorter'), 3, 'model is updated');
}); });
}); });

View File

@@ -5,14 +5,7 @@ define([
'common/forms/views/form', 'common/forms/views/form',
'common/forms/views/input', 'common/forms/views/input',
'common/forms/views/error' 'common/forms/views/error'
], function( ], function (chai, fixtures, $, FormView, InputView, ErrorView) {
chai,
fixtures,
$,
FormView,
InputView,
ErrorView
) {
var expect = chai.expect; var expect = chai.expect;
var assert = chai.assert; var assert = chai.assert;
var should = chai.should(); var should = chai.should();
@@ -20,10 +13,12 @@ define([
fixtures.path = 'fixtures'; fixtures.path = 'fixtures';
$("body").append(fixtures.read('home/login/form', 'home/login/templates')); $("body").append(fixtures.read('home/login/form', 'home/login/templates'));
describe("Login Home", function() { describe("Login Home", function () {
describe("Form View", function() { describe("Form View", function () {
it("should initialize validator with proper rules", function() { it("should initialize validator with proper rules", function () {
var rules = [{name: "hello",rules: "simple_rules"}]; var rules = [
{name: "hello", rules: "simple_rules"}
];
var form = new FormView({ var form = new FormView({
el: $('form[name=loginForm]'), el: $('form[name=loginForm]'),
rules: rules rules: rules
@@ -31,7 +26,7 @@ define([
form.validator.getRules().should.equal(rules); form.validator.getRules().should.equal(rules);
}); });
it("should initialize input views", function() { it("should initialize input views", function () {
var form = new FormView({ var form = new FormView({
el: $('form[name=loginForm]') el: $('form[name=loginForm]')
}); });
@@ -39,7 +34,7 @@ define([
Object.keys(form.inputViews).length.should.equal(5); Object.keys(form.inputViews).length.should.equal(5);
}); });
it("should initialize errors", function() { it("should initialize errors", function () {
var form = new FormView({ var form = new FormView({
el: $('form[name=loginForm]') el: $('form[name=loginForm]')
}); });
@@ -47,14 +42,16 @@ define([
assert.isTrue(_.isEmpty(form.validator.getErrors())); assert.isTrue(_.isEmpty(form.validator.getErrors()));
}); });
it("should render errors on submit", function() { it("should render errors on submit", function () {
var form = new FormView({ var form = new FormView({
el: $('form[name=loginForm]'), el: $('form[name=loginForm]'),
rules: [{ rules: [
{
"name": "login", "name": "login",
"rules": "required", "rules": "required",
"message" : "something is wrong" "message": "something is wrong"
}] }
]
}); });
form._onSubmit(document.createEvent("Event")); form._onSubmit(document.createEvent("Event"));
@@ -62,8 +59,8 @@ define([
}); });
}); });
describe("Input View", function() { describe("Input View", function () {
it("should initialize error view", function() { it("should initialize error view", function () {
var input = new InputView({ var input = new InputView({
"name": "test", "name": "test",
"errorTemplate": "#field_errors" "errorTemplate": "#field_errors"
@@ -72,9 +69,9 @@ define([
}); });
}); });
describe("Error View", function() { describe("Error View", function () {
it("should render errors", function() { it("should render errors", function () {
var error ={ var error = {
name: "test", name: "test",
message: "Something is wrong" message: "Something is wrong"
}; };
@@ -82,7 +79,7 @@ define([
var errorView = new ErrorView({ var errorView = new ErrorView({
"name": "test", "name": "test",
"errors": [error], "errors": [error],
"el" : $(".error-view").first(), "el": $(".error-view").first(),
"errorTemplate": "#field_errors" "errorTemplate": "#field_errors"
}); });
@@ -91,7 +88,7 @@ define([
assert.isTrue(errorView.$el.html().indexOf(error.message) !== -1); assert.isTrue(errorView.$el.html().indexOf(error.message) !== -1);
}); });
it("should empty errors content if there are no errors", function() { it("should empty errors content if there are no errors", function () {
var $el = $(".error-view").first(); var $el = $(".error-view").first();
$el.html('previous error here'); $el.html('previous error here');
@@ -99,7 +96,7 @@ define([
var errorView = new ErrorView({ var errorView = new ErrorView({
"name": "test", "name": "test",
"errors": [], "errors": [],
"el" : $el, "el": $el,
"errorTemplate": "#field_errors" "errorTemplate": "#field_errors"
}); });

View File

@@ -3,108 +3,108 @@ define([
'models/field', 'models/field',
'models/dcField', 'models/dcField',
'models/vocabulary' 'models/vocabulary'
], function(chai, Field, DcField, Vocabulary) { ], function (chai, Field, DcField, Vocabulary) {
var expect = chai.expect; var expect = chai.expect;
var assert = chai.assert; var assert = chai.assert;
var should = chai.should(); var should = chai.should();
describe("Models", function(){ describe("Models", function () {
describe("Field Model", function(){ describe("Field Model", function () {
describe("Initialization", function() { describe("Initialization", function () {
var sbasId = 1; var sbasId = 1;
beforeEach(function() { beforeEach(function () {
this.field = new Field({ this.field = new Field({
"sbas-id" : sbasId "sbas-id": sbasId
}); });
}); });
it("should throw an exception if 'sbas-id' is missing", function() { it("should throw an exception if 'sbas-id' is missing", function () {
expect(function() { expect(function () {
new Field(); new Field();
}).to.throw("You must set a sbas id"); }).to.throw("You must set a sbas id");
}); });
it("should set model url according to provided 'sbas-id'", function() { it("should set model url according to provided 'sbas-id'", function () {
this.field.urlRoot().should.equal("/admin/fields/"+sbasId+"/fields"); this.field.urlRoot().should.equal("/admin/fields/" + sbasId + "/fields");
}); });
it("should default business property to 'false'", function() { it("should default business property to 'false'", function () {
this.field.get('business').should.be.false; this.field.get('business').should.be.false;
}); });
it("should default type property to 'string'", function() { it("should default type property to 'string'", function () {
this.field.get('type').should.equal("string"); this.field.get('type').should.equal("string");
}); });
it("should default thumbtitle property to '0'", function() { it("should default thumbtitle property to '0'", function () {
this.field.get('thumbtitle').should.equal("0"); this.field.get('thumbtitle').should.equal("0");
}); });
it("should default tbranch property to 'empty'", function() { it("should default tbranch property to 'empty'", function () {
this.field.get('tbranch').should.equal(""); this.field.get('tbranch').should.equal("");
}); });
it("should default separator property to 'empty'", function() { it("should default separator property to 'empty'", function () {
this.field.get('separator').should.equal(""); this.field.get('separator').should.equal("");
}); });
it("should default required property to 'false'", function() { it("should default required property to 'false'", function () {
this.field.get('required').should.be.false; this.field.get('required').should.be.false;
}); });
it("should default readonly property to 'false'", function() { it("should default readonly property to 'false'", function () {
this.field.get('readonly').should.be.false; this.field.get('readonly').should.be.false;
}); });
it("should default multi property to 'false'", function() { it("should default multi property to 'false'", function () {
this.field.get('multi').should.be.false; this.field.get('multi').should.be.false;
}); });
it("should default vocabulary-restricted property to 'false'", function() { it("should default vocabulary-restricted property to 'false'", function () {
this.field.get('vocabulary-restricted').should.be.false; this.field.get('vocabulary-restricted').should.be.false;
}); });
it("should default vocabulary-restricted property to 'false'", function() { it("should default vocabulary-restricted property to 'false'", function () {
this.field.get('vocabulary-restricted').should.be.false; this.field.get('vocabulary-restricted').should.be.false;
}); });
it("should default report property to 'true'", function() { it("should default report property to 'true'", function () {
this.field.get('report').should.be.true; this.field.get('report').should.be.true;
}); });
it("should default indexable property to 'true'", function() { it("should default indexable property to 'true'", function () {
this.field.get('indexable').should.be.true; this.field.get('indexable').should.be.true;
}); });
it("should default dces-element property to 'null'", function() { it("should default dces-element property to 'null'", function () {
expect(this.field.get('dces-element')).to.be.null; expect(this.field.get('dces-element')).to.be.null;
}); });
it("should default vocabulary-type property to 'null'", function() { it("should default vocabulary-type property to 'null'", function () {
expect(this.field.get('vocabulary-type')).to.be.null; expect(this.field.get('vocabulary-type')).to.be.null;
}); });
}); });
}); });
describe("DcField Model", function(){ describe("DcField Model", function () {
describe("Initialization", function() { describe("Initialization", function () {
beforeEach(function() { beforeEach(function () {
this.dcField = new DcField(); this.dcField = new DcField();
}); });
it("should set proper model url", function() { it("should set proper model url", function () {
this.dcField.urlRoot().should.equal("/admin/fields/dc-fields"); this.dcField.urlRoot().should.equal("/admin/fields/dc-fields");
}); });
}); });
}); });
describe("DcField Model", function(){ describe("DcField Model", function () {
describe("Initialization", function() { describe("Initialization", function () {
beforeEach(function() { beforeEach(function () {
this.vocabulary = new Vocabulary(); this.vocabulary = new Vocabulary();
}); });
it("should set proper model url", function() { it("should set proper model url", function () {
this.vocabulary.urlRoot().should.equal("/admin/fields/vocabularies"); this.vocabulary.urlRoot().should.equal("/admin/fields/vocabularies");
}); });
}); });

View File

@@ -1,490 +1,611 @@
define([ define([
'chai', 'chai',
'common/forms/validator' 'common/forms/validator'
], function(chai, Validator) { ], function (chai, Validator) {
var expect = chai.expect; var expect = chai.expect;
var assert = chai.assert; var assert = chai.assert;
var should = chai.should(); var should = chai.should();
describe("Validator", function(){ describe("Validator", function () {
describe("Validator rules", function(){ describe("Validator rules", function () {
beforeEach(function() { beforeEach(function () {
this.validator = new Validator([{ this.validator = new Validator([
{
name: "required", name: "required",
rules: "required" rules: "required"
},{ },
{
name: "valid_email", name: "valid_email",
rules: "valid_email" rules: "valid_email"
},{ },
{
name: "equal", name: "equal",
rules: "equal[toto]" rules: "equal[toto]"
},{ },
{
name: "matches", name: "matches",
rules: "matches[to_match]" rules: "matches[to_match]"
},{ },
{
name: "valid_emails", name: "valid_emails",
rules: "valid_emails" rules: "valid_emails"
},{ },
{
name: "min_length", name: "min_length",
rules: "min_length[5]" rules: "min_length[5]"
},{ },
{
name: "max_length", name: "max_length",
rules: "max_length[5]" rules: "max_length[5]"
},{ },
{
name: "exact_length", name: "exact_length",
rules: "exact_length[5]" rules: "exact_length[5]"
},{ },
{
name: "greater_than", name: "greater_than",
rules: "greater_than[5]" rules: "greater_than[5]"
},{ },
{
name: "less_than", name: "less_than",
rules: "less_than[5]" rules: "less_than[5]"
},{ },
{
name: "alpha", name: "alpha",
rules: "alpha" rules: "alpha"
},{ },
{
name: "alpha_numeric", name: "alpha_numeric",
rules: "alpha_numeric" rules: "alpha_numeric"
},{ },
{
name: "alpha_dash", name: "alpha_dash",
rules: "alpha_dash" rules: "alpha_dash"
},{ },
{
name: "numeric", name: "numeric",
rules: "numeric" rules: "numeric"
},{ },
{
name: "integer", name: "integer",
rules: "integer" rules: "integer"
},{ },
{
name: "decimal", name: "decimal",
rules: "decimal" rules: "decimal"
},{ },
{
name: "is_natural", name: "is_natural",
rules: "is_natural" rules: "is_natural"
},{ },
{
name: "is_natural_no_zero", name: "is_natural_no_zero",
rules: "is_natural_no_zero" rules: "is_natural_no_zero"
},{ },
{
name: "valid_ip", name: "valid_ip",
rules: "valid_ip" rules: "valid_ip"
},{ },
{
name: "valid_url", name: "valid_url",
rules: "valid_url" rules: "valid_url"
}]); }
]);
}); });
it("should detect an error if field is required and value is blank", function() { it("should detect an error if field is required and value is blank", function () {
this.validator.validate([{ this.validator.validate([
name :"required", {
name: "required",
value: "" value: ""
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should detect an error if field is not a valid email", function() { it("should detect an error if field is not a valid email", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_email", {
name: "valid_email",
value: "email.not.va@" value: "email.not.va@"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field is a valid email", function() { it("should not detect an error if field is a valid email", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_email", {
name: "valid_email",
value: "valid@email.com" value: "valid@email.com"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"valid_email", {
name: "valid_email",
value: "valid+34@email.com" value: "valid+34@email.com"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field is not a valid emails", function() { it("should detect an error if field is not a valid emails", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_emails", {
name: "valid_emails",
value: "valid@email.com, email.not.va@" value: "valid@email.com, email.not.va@"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field is a valid emails", function() { it("should not detect an error if field is a valid emails", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_emails", {
name: "valid_emails",
value: "valid32@email.com, valid2@email.com" value: "valid32@email.com, valid2@email.com"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"valid_emails", {
name: "valid_emails",
value: "valid@email.com" value: "valid@email.com"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field is not equal to default string toto", function() { it("should detect an error if field is not equal to default string toto", function () {
this.validator.validate([{ this.validator.validate([
name :"equal", {
name: "equal",
value: "tata" value: "tata"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field is equal to default string toto", function() { it("should not detect an error if field is equal to default string toto", function () {
this.validator.validate([{ this.validator.validate([
name :"equal", {
name: "equal",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'match 'is not equal to field value 'to_match'", function() { it("should detect an error if field value 'match 'is not equal to field value 'to_match'", function () {
this.validator.validate([{ this.validator.validate([
name :"matches", {
name: "matches",
value: "toto" value: "toto"
}, { },
{
name: "to_match", name: "to_match",
value: "tata" value: "tata"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'match' is equal to field value 'to_match'", function() { it("should not detect an error if field value 'match' is equal to field value 'to_match'", function () {
this.validator.validate([{ this.validator.validate([
name :"matches", {
name: "matches",
value: "toto" value: "toto"
}, { },
{
name: "to_match", name: "to_match",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'min_length' is < to 5", function() { it("should detect an error if field value 'min_length' is < to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"min_length", {
name: "min_length",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'min_length' is >= to 5", function() { it("should not detect an error if field value 'min_length' is >= to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"min_length", {
name: "min_length",
value: "totos" value: "totos"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'max_length' is > to 5", function() { it("should detect an error if field value 'max_length' is > to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"max_length", {
name: "max_length",
value: "tostos" value: "tostos"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'max_length' is <= to 5", function() { it("should not detect an error if field value 'max_length' is <= to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"max_length", {
name: "max_length",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'greater_than' is < to 5", function() { it("should detect an error if field value 'greater_than' is < to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"greater_than", {
name: "greater_than",
value: "3" value: "3"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'greater_than' is > to 5", function() { it("should not detect an error if field value 'greater_than' is > to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"greater_than", {
name: "greater_than",
value: "6" value: "6"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'less_than' is > to 5", function() { it("should detect an error if field value 'less_than' is > to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"less_than", {
name: "less_than",
value: "6" value: "6"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'less_than' is <= to 5", function() { it("should not detect an error if field value 'less_than' is <= to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"less_than", {
name: "less_than",
value: "3" value: "3"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'exact_length' is = to 5", function() { it("should detect an error if field value 'exact_length' is = to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"exact_length", {
name: "exact_length",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'exact_length' is = to 5", function() { it("should not detect an error if field value 'exact_length' is = to 5", function () {
this.validator.validate([{ this.validator.validate([
name :"exact_length", {
name: "exact_length",
value: "totos" value: "totos"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'alpha' is not alpha", function() { it("should detect an error if field value 'alpha' is not alpha", function () {
this.validator.validate([{ this.validator.validate([
name :"alpha", {
name: "alpha",
value: "toto12" value: "toto12"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'alpha' is alpha", function() { it("should not detect an error if field value 'alpha' is alpha", function () {
this.validator.validate([{ this.validator.validate([
name :"alpha", {
name: "alpha",
value: "totos" value: "totos"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'alpha_numeric' is not alpha numeric", function() { it("should detect an error if field value 'alpha_numeric' is not alpha numeric", function () {
this.validator.validate([{ this.validator.validate([
name :"alpha_numeric", {
name: "alpha_numeric",
value: "toto#" value: "toto#"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'alpha_numeric' is alpha numeric", function() { it("should not detect an error if field value 'alpha_numeric' is alpha numeric", function () {
this.validator.validate([{ this.validator.validate([
name :"alpha_numeric", {
name: "alpha_numeric",
value: "totos12" value: "totos12"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'numeric' is not numeric", function() { it("should detect an error if field value 'numeric' is not numeric", function () {
this.validator.validate([{ this.validator.validate([
name :"numeric", {
name: "numeric",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'numeric' is numeric", function() { it("should not detect an error if field value 'numeric' is numeric", function () {
this.validator.validate([{ this.validator.validate([
name :"numeric", {
name: "numeric",
value: "123" value: "123"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'integer' is not integer", function() { it("should detect an error if field value 'integer' is not integer", function () {
this.validator.validate([{ this.validator.validate([
name :"integer", {
name: "integer",
value: "3.44" value: "3.44"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'integer' is integer", function() { it("should not detect an error if field value 'integer' is integer", function () {
this.validator.validate([{ this.validator.validate([
name :"integer", {
name: "integer",
value: "123" value: "123"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'decimal' is not decimal", function() { it("should detect an error if field value 'decimal' is not decimal", function () {
this.validator.validate([{ this.validator.validate([
name :"decimal", {
name: "decimal",
value: "23a" value: "23a"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'decimal' is decimal", function() { it("should not detect an error if field value 'decimal' is decimal", function () {
this.validator.validate([{ this.validator.validate([
name :"decimal", {
name: "decimal",
value: "1.23" value: "1.23"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"decimal", {
name: "decimal",
value: "123" value: "123"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'natural' is not natural", function() { it("should detect an error if field value 'natural' is not natural", function () {
this.validator.validate([{ this.validator.validate([
name :"is_natural", {
name: "is_natural",
value: "-2" value: "-2"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'natural' is natural", function() { it("should not detect an error if field value 'natural' is natural", function () {
this.validator.validate([{ this.validator.validate([
name :"is_natural", {
name: "is_natural",
value: "0" value: "0"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'is_natural_no_zero' is not a natural no zero", function() { it("should detect an error if field value 'is_natural_no_zero' is not a natural no zero", function () {
this.validator.validate([{ this.validator.validate([
name :"is_natural_no_zero", {
name: "is_natural_no_zero",
value: "0" value: "0"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'is_natural_no_zero' is a natural no zero", function() { it("should not detect an error if field value 'is_natural_no_zero' is a natural no zero", function () {
this.validator.validate([{ this.validator.validate([
name :"is_natural_no_zero", {
name: "is_natural_no_zero",
value: "1" value: "1"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'valid_ip' is not a valid ip", function() { it("should detect an error if field value 'valid_ip' is not a valid ip", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_ip", {
name: "valid_ip",
value: "12.8.1.187.2" value: "12.8.1.187.2"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
this.validator.validate([{ this.validator.validate([
name :"valid_ip", {
name: "valid_ip",
value: "1234.12.12" value: "1234.12.12"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
this.validator.validate([{ this.validator.validate([
name :"valid_ip", {
name: "valid_ip",
value: "0.0" value: "0.0"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'valid_ip' a valid ip", function() { it("should not detect an error if field value 'valid_ip' a valid ip", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_ip", {
name: "valid_ip",
value: "127.0.0.1" value: "127.0.0.1"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"valid_ip", {
name: "valid_ip",
value: "my.domain" value: "my.domain"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });
it("should detect an error if field value 'valid_url' is not a valid http url", function() { it("should detect an error if field value 'valid_url' is not a valid http url", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "toto" value: "toto"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "toto.123s" value: "toto.123s"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "http:/#toto.com" value: "http:/#toto.com"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "htp:/toto.com" value: "htp:/toto.com"
}]); }
]);
this.validator.getErrors().length.should.equal(1); this.validator.getErrors().length.should.equal(1);
}); });
it("should not detect an error if field value 'valid_url' is a valid http url", function() { it("should not detect an error if field value 'valid_url' is a valid http url", function () {
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "http://valid.url.com" value: "http://valid.url.com"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "https://valid.url.com" value: "https://valid.url.com"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "http://valid.url.com/?test=3" value: "http://valid.url.com/?test=3"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
this.validator.validate([{ this.validator.validate([
name :"valid_url", {
name: "valid_url",
value: "http://valid.url.com/?test=3#salut" value: "http://valid.url.com/?test=3#salut"
}]); }
]);
this.validator.getErrors().length.should.equal(0); this.validator.getErrors().length.should.equal(0);
}); });

View File

@@ -1,15 +1,15 @@
$(document).ready(function() { $(document).ready(function () {
// revoke third party application access // revoke third party application access
$("a.app-btn").bind("click", function(e) { $("a.app-btn").bind("click", function (e) {
e.preventDefault(); e.preventDefault();
var $this = $(this); var $this = $(this);
$.ajax({ $.ajax({
type:"GET", type: "GET",
url : $this.attr("href"), url: $this.attr("href"),
dataType: 'json', dataType: 'json',
data : {revoke : $this.hasClass("authorize") ? 1 : 0}, data: {revoke: $this.hasClass("authorize") ? 1 : 0},
success : function(data) { success: function (data) {
if(data.success) { if (data.success) {
var li = $this.closest('li'); var li = $this.closest('li');
var hidden = $('.app-btn.hidden , .status.hidden', li); var hidden = $('.app-btn.hidden , .status.hidden', li);
@@ -23,18 +23,18 @@ $(document).ready(function() {
}); });
// generate new access token // generate new access token
$("a#generate_access").bind("click", function(e) { $("a#generate_access").bind("click", function (e) {
e.preventDefault(); e.preventDefault();
var $this = $(this); var $this = $(this);
$.ajax({ $.ajax({
type:"POST", type: "POST",
url : $this.attr("href"), url: $this.attr("href"),
dataType: 'json', dataType: 'json',
data : { data: {
usr_id : $this.closest("div").attr("id") usr_id: $this.closest("div").attr("id")
}, },
success : function(data){ success: function (data) {
if(data.success) { if (data.success) {
$("#my_access_token").empty().append(data.token); $("#my_access_token").empty().append(data.token);
} }
} }
@@ -42,7 +42,7 @@ $(document).ready(function() {
}); });
//modify application callback url //modify application callback url
$(".modifier_callback").bind("click", function() { $(".modifier_callback").bind("click", function () {
var modifierBtn = $(this); var modifierBtn = $(this);
var saveBtn = $("a.save_callback"); var saveBtn = $("a.save_callback");
var input = $(".url_callback_input"); var input = $(".url_callback_input");
@@ -54,23 +54,23 @@ $(document).ready(function() {
input input
.empty() .empty()
.wrapInner('' .wrapInner(''
+ '<input value = "'+inputVal+'"' + '<input value = "' + inputVal + '"'
+ ' name="oauth_callback" size="50" type="text"/>' + ' name="oauth_callback" size="50" type="text"/>'
); );
$(".url_callback").die(); $(".url_callback").die();
// save new callback // save new callback
saveBtn.bind("click", function(e) { saveBtn.bind("click", function (e) {
e.preventDefault(); e.preventDefault();
var callback = $("input[name=oauth_callback]").val(); var callback = $("input[name=oauth_callback]").val();
$.ajax({ $.ajax({
type:"POST", type: "POST",
url : saveBtn.attr("href"), url: saveBtn.attr("href"),
dataType: 'json', dataType: 'json',
data :{callback : callback}, data: {callback: callback},
success : function(data) { success: function (data) {
if(data.success) { if (data.success) {
input.empty().append(callback); input.empty().append(callback);
} else { } else {
input.empty().append(inputVal); input.empty().append(inputVal);
@@ -81,8 +81,8 @@ $(document).ready(function() {
}); });
// hide or show callback url input whether user choose a web or dektop application // hide or show callback url input whether user choose a web or dektop application
$("#form_create input[name=type]").bind("click", function() { $("#form_create input[name=type]").bind("click", function () {
if($(this).val() === "desktop") { if ($(this).val() === "desktop") {
$("#form_create .callback td").hide().find("input").val(''); $("#form_create .callback td").hide().find("input").val('');
} else { } else {
$("#form_create .callback td").show(); $("#form_create .callback td").show();
@@ -90,30 +90,31 @@ $(document).ready(function() {
}); });
// authorize password grant type or not // authorize password grant type or not
$('.grant-type').bind('click', function(){ $('.grant-type').bind('click', function () {
var $this = $(this); var $this = $(this);
$.ajax({ $.ajax({
type:"POST", type: "POST",
url : $this.attr("value") , url: $this.attr("value"),
dataType: 'json', dataType: 'json',
data : {grant : $this.is(":checked") ? "1": "0"}, data: {grant: $this.is(":checked") ? "1" : "0"},
success : function(data){} success: function (data) {
}
}); });
}); });
// delete an application // delete an application
$("a.delete-app").bind("click", function(e) { $("a.delete-app").bind("click", function (e) {
e.preventDefault(); e.preventDefault();
var $this = $(this); var $this = $(this);
var li = $this.closest("li"); var li = $this.closest("li");
$.ajax({ $.ajax({
type:"DELETE", type: "DELETE",
url : $this.attr('href'), url: $this.attr('href'),
dataType: 'json', dataType: 'json',
data : {}, data: {},
success : function(data){ success: function (data) {
if(data.success) { if (data.success) {
li.find('.modal').modal('hide'); li.find('.modal').modal('hide');
li.remove(); li.remove();
} }

View File

@@ -1,66 +1,62 @@
function ini_edit_usrs(){ function ini_edit_usrs() {
$('.users_col.options').bind('click', function(event){ $('.users_col.options').bind('click', function (event) {
$('#users_check_uncheck').remove(); $('#users_check_uncheck').remove();
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();
check_uncheck_menu($('input[name="right"]', $(this)).val(),$('input[name="sbas_id"]', $(this)).val(), $(this)); check_uncheck_menu($('input[name="right"]', $(this)).val(), $('input[name="sbas_id"]', $(this)).val(), $(this));
return false; return false;
}); });
$(document).unbind('click.usersoptions').bind('click.usersoptions', function(event){ $(document).unbind('click.usersoptions').bind('click.usersoptions', function (event) {
$('#users_check_uncheck').remove(); $('#users_check_uncheck').remove();
}); });
$('table.hoverable tr').hover( $('table.hoverable tr').hover(
function(){ function () {
$(this).addClass('hovered'); $(this).addClass('hovered');
}, },
function(){ function () {
$(this).removeClass('hovered'); $(this).removeClass('hovered');
} }
); );
$('table.hoverable td').hover( $('table.hoverable td').hover(
function(){ function () {
var attr = $('input:first', this).attr('name'); var attr = $('input:first', this).attr('name');
var right = attr ? attr.split('_').shift() : false; var right = attr ? attr.split('_').shift() : false;
if(right) if (right)
$('td.case_right_'+right).addClass('hovered'); $('td.case_right_' + right).addClass('hovered');
}, },
function(){ function () {
var attr = $('input:first', this).attr('name'); var attr = $('input:first', this).attr('name');
var right = attr ? attr.split('_').shift() : false; var right = attr ? attr.split('_').shift() : false;
if(right) if (right)
$('td.hovered').removeClass('hovered'); $('td.hovered').removeClass('hovered');
} }
); );
function user_click_box(event, element, status) function user_click_box(event, element, status) {
{
var newclass, newvalue, boxes; var newclass, newvalue, boxes;
var $element = $(element); var $element = $(element);
if($element.hasClass('right_access')) if ($element.hasClass('right_access')) {
{
var base_id = $element.find('input').attr('name').split('_').pop(); var base_id = $element.find('input').attr('name').split('_').pop();
boxes = $('div.base_'+base_id+':not(:first)'); boxes = $('div.base_' + base_id + ':not(:first)');
} }
if((typeof status !== 'undefined' && status == 'checked') || (typeof status === 'undefined' && (($element.hasClass('mixed') === true) || ($element.hasClass('unchecked') === true)))) if ((typeof status !== 'undefined' && status == 'checked') || (typeof status === 'undefined' && (($element.hasClass('mixed') === true) || ($element.hasClass('unchecked') === true)))) {
{
newclass = 'checked'; newclass = 'checked';
newvalue = '1'; newvalue = '1';
if(boxes) if (boxes)
boxes.show(); boxes.show();
} }
else else {
{
newclass = 'unchecked'; newclass = 'unchecked';
newvalue = '0'; newvalue = '0';
if(boxes) if (boxes)
boxes.hide(); boxes.hide();
} }
@@ -68,23 +64,23 @@ function ini_edit_usrs(){
$element.removeClass('mixed checked unchecked').addClass(newclass); $element.removeClass('mixed checked unchecked').addClass(newclass);
} }
$('#users_rights_form div.switch_right').bind('click', function(event){ $('#users_rights_form div.switch_right').bind('click', function (event) {
user_click_box(event, $(this)); user_click_box(event, $(this));
}); });
$('#right-ajax button.users_rights_valid').bind('click', function(){ $('#right-ajax button.users_rights_valid').bind('click', function () {
var datas = { var datas = {
users:$('#users_rights_form input[name="users"]').val(), users: $('#users_rights_form input[name="users"]').val(),
values:$('#users_rights_form').serialize(), values: $('#users_rights_form').serialize(),
template:$('#users_rights_form select[name="template"]').val(), template: $('#users_rights_form select[name="template"]').val(),
user_infos:$('#user_infos_form').serialize() user_infos: $('#user_infos_form').serialize()
}; };
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/rights/apply/', url: '../admin/users/rights/apply/',
dataType:'json', dataType: 'json',
data: datas, data: datas,
success: function(data){ success: function (data) {
if(!data.error) if (!data.error)
$('a.zone_editusers').trigger('click'); $('a.zone_editusers').trigger('click');
else else
alert(data.message); alert(data.message);
@@ -93,11 +89,11 @@ function ini_edit_usrs(){
return false; return false;
}); });
$('#right-ajax .users_rights_cancel').bind('click', function(){ $('#right-ajax .users_rights_cancel').bind('click', function () {
var $this = $(this); var $this = $(this);
$('#right-ajax').empty().addClass('loading').parent().show(); $('#right-ajax').empty().addClass('loading').parent().show();
$('#right').hide(); $('#right').hide();
$.get($this.attr('href'), function(data) { $.get($this.attr('href'), function (data) {
$('#right-ajax').removeClass('loading').html(data); $('#right-ajax').removeClass('loading').html(data);
}); });
@@ -105,84 +101,82 @@ function ini_edit_usrs(){
}); });
var time_buttons = { var time_buttons = {
'Ok':function(){ 'Ok': function () {
save_time(); save_time();
}, },
'Cancel':function(){ 'Cancel': function () {
$('#time_dialog').dialog('close'); $('#time_dialog').dialog('close');
} }
}; };
$('#time_dialog').dialog({ $('#time_dialog').dialog({
resizable:false, resizable: false,
autoOpen:false, autoOpen: false,
draggable:false, draggable: false,
buttons:time_buttons, buttons: time_buttons,
modal:true modal: true
}); });
var quota_buttons = { var quota_buttons = {
'Ok':function(){ 'Ok': function () {
save_quotas(); save_quotas();
}, },
'Cancel':function(){ 'Cancel': function () {
$('#quotas_dialog').dialog('close'); $('#quotas_dialog').dialog('close');
} }
}; };
$('#quotas_dialog').dialog({ $('#quotas_dialog').dialog({
resizable:false, resizable: false,
autoOpen:false, autoOpen: false,
draggable:false, draggable: false,
buttons:quota_buttons, buttons: quota_buttons,
modal:true modal: true
}); });
var masks_buttons = { var masks_buttons = {
'Ok':function(){ 'Ok': function () {
save_masks(); save_masks();
}, },
'Cancel':function(){ 'Cancel': function () {
$('#masks_dialog').dialog('close'); $('#masks_dialog').dialog('close');
} }
}; };
$('#masks_dialog').dialog({ $('#masks_dialog').dialog({
resizable:false, resizable: false,
autoOpen:false, autoOpen: false,
draggable:false, draggable: false,
buttons:masks_buttons, buttons: masks_buttons,
width:900, width: 900,
height:300, height: 300,
modal:true modal: true
}); });
$('#users_rights_form .time_trigger').bind('click', function(){ $('#users_rights_form .time_trigger').bind('click', function () {
var base_id = $(this).find('input[name="time_base_id"]').val(); var base_id = $(this).find('input[name="time_base_id"]').val();
if ('undefined' !== typeof base_id) { if ('undefined' !== typeof base_id) {
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/rights/time/', url: '../admin/users/rights/time/',
data: { data: {
users:$('#users_rights_form input[name="users"]').val(), users: $('#users_rights_form input[name="users"]').val(),
base_id:base_id base_id: base_id
}, },
success: function(data){ success: function (data) {
var dialog = $('#time_dialog'); var dialog = $('#time_dialog');
if (dialog.data("ui-dialog")) { if (dialog.data("ui-dialog")) {
dialog.html(data).dialog('open'); dialog.html(data).dialog('open');
} }
$('div.switch_time', dialog).bind('click', function(event){ $('div.switch_time', dialog).bind('click', function (event) {
var newclass, boxes; var newclass, boxes;
boxes = $(this).closest('form').find('input.datepicker'); boxes = $(this).closest('form').find('input.datepicker');
if(($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) if (($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) {
{
newclass = 'checked'; newclass = 'checked';
boxes.removeAttr('readonly'); boxes.removeAttr('readonly');
} }
else else {
{
newclass = 'unchecked'; newclass = 'unchecked';
boxes.attr('readonly','readonly'); boxes.attr('readonly', 'readonly');
} }
$(this).removeClass('mixed checked unchecked').addClass(newclass); $(this).removeClass('mixed checked unchecked').addClass(newclass);
@@ -196,29 +190,27 @@ function ini_edit_usrs(){
type: 'POST', type: 'POST',
url: '../admin/users/rights/time/sbas/', url: '../admin/users/rights/time/sbas/',
data: { data: {
users:$('#users_rights_form input[name="users"]').val(), users: $('#users_rights_form input[name="users"]').val(),
sbas_id:sbas_id sbas_id: sbas_id
}, },
success: function(data){ success: function (data) {
var dialog = $('#time_dialog'); var dialog = $('#time_dialog');
dialog.html(data); dialog.html(data);
dialog.dialog('open'); dialog.dialog('open');
$('div.switch_time', dialog).bind('click', function(event){ $('div.switch_time', dialog).bind('click', function (event) {
var newclass, boxes; var newclass, boxes;
boxes = $(this).closest('form').find('input.datepicker'); boxes = $(this).closest('form').find('input.datepicker');
if(($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) if (($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) {
{
newclass = 'checked'; newclass = 'checked';
boxes.removeAttr('readonly'); boxes.removeAttr('readonly');
} }
else else {
{
newclass = 'unchecked'; newclass = 'unchecked';
boxes.attr('readonly','readonly'); boxes.attr('readonly', 'readonly');
} }
$(this).removeClass('mixed checked unchecked').addClass(newclass); $(this).removeClass('mixed checked unchecked').addClass(newclass);
@@ -227,36 +219,34 @@ function ini_edit_usrs(){
}); });
} }
}); });
$('#users_rights_form .quota_trigger').bind('click', function(){ $('#users_rights_form .quota_trigger').bind('click', function () {
var base_id = $(this).find('input[name="quota_base_id"]').val(); var base_id = $(this).find('input[name="quota_base_id"]').val();
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/rights/quotas/', url: '../admin/users/rights/quotas/',
data: { data: {
users:$('#users_rights_form input[name="users"]').val(), users: $('#users_rights_form input[name="users"]').val(),
base_id:base_id base_id: base_id
}, },
success: function(data){ success: function (data) {
var dialog = $('#quotas_dialog'); var dialog = $('#quotas_dialog');
if (dialog.data("ui-dialog")) { if (dialog.data("ui-dialog")) {
dialog.html(data).dialog('open'); dialog.html(data).dialog('open');
} }
$('div.switch_quota', dialog).bind('click', function(event){ $('div.switch_quota', dialog).bind('click', function (event) {
var newclass, boxes; var newclass, boxes;
boxes = $(this).closest('form').find('input:text'); boxes = $(this).closest('form').find('input:text');
if(($(this).hasClass('mixed')===true) || ($(this).hasClass('unchecked') === true)) if (($(this).hasClass('mixed') === true) || ($(this).hasClass('unchecked') === true)) {
{
newclass = 'checked'; newclass = 'checked';
boxes.removeAttr('readonly'); boxes.removeAttr('readonly');
} }
else else {
{
newclass = 'unchecked'; newclass = 'unchecked';
boxes.attr('readonly','readonly'); boxes.attr('readonly', 'readonly');
} }
$(this).removeClass('mixed checked unchecked').addClass(newclass); $(this).removeClass('mixed checked unchecked').addClass(newclass);
@@ -265,55 +255,50 @@ function ini_edit_usrs(){
}); });
}); });
$('#users_rights_form .masks_trigger').bind('click', function(){ $('#users_rights_form .masks_trigger').bind('click', function () {
var base_id = $(this).find('input[name="masks_base_id"]').val(); var base_id = $(this).find('input[name="masks_base_id"]').val();
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/rights/masks/', url: '../admin/users/rights/masks/',
data: { data: {
users:$('#users_rights_form input[name="users"]').val(), users: $('#users_rights_form input[name="users"]').val(),
base_id:base_id base_id: base_id
}, },
success: function(data){ success: function (data) {
$('#masks_dialog').html(data).dialog('open'); $('#masks_dialog').html(data).dialog('open');
$('.switch_masks').bind('click', function(){ $('.switch_masks').bind('click', function () {
var currentclass, newclass; var currentclass, newclass;
var bit = $(this).find('input[name="bit"]').val(); var bit = $(this).find('input[name="bit"]').val();
currentclass = 'unchecked'; currentclass = 'unchecked';
if($(this).hasClass('mixed')) if ($(this).hasClass('mixed')) {
{
currentclass = 'mixed'; currentclass = 'mixed';
} }
if($(this).hasClass('checked')) if ($(this).hasClass('checked')) {
{
currentclass = 'checked'; currentclass = 'checked';
} }
switch(currentclass) switch (currentclass) {
{
case 'mixed': case 'mixed':
default: default:
$('.bitnum_'+bit).removeClass('mixed checked unchecked').addClass('checked') $('.bitnum_' + bit).removeClass('mixed checked unchecked').addClass('checked')
break; break;
case 'unchecked': case 'unchecked':
$(this).removeClass('mixed checked unchecked').addClass('checked') $(this).removeClass('mixed checked unchecked').addClass('checked')
break; break;
case 'checked': case 'checked':
if($('.checked.bitnum_'+bit).length == 2) if ($('.checked.bitnum_' + bit).length == 2) {
{
$(this).removeClass('mixed checked unchecked').addClass('unchecked') $(this).removeClass('mixed checked unchecked').addClass('unchecked')
} }
else else {
{
alert("admin::user:mask: vous devez cocher au moins une case pour chaque status"); alert("admin::user:mask: vous devez cocher au moins une case pour chaque status");
return; return;
} }
break; break;
} }
var left = $('.bitnum_'+bit+'.bit_left'); var left = $('.bitnum_' + bit + '.bit_left');
var right = $('.bitnum_'+bit+'.bit_right'); var right = $('.bitnum_' + bit + '.bit_right');
var maskform = $('#masks_dialog form'); var maskform = $('#masks_dialog form');
var vand_and = $('input[name="vand_and"]', maskform); var vand_and = $('input[name="vand_and"]', maskform);
@@ -323,24 +308,21 @@ function ini_edit_usrs(){
var newbit_vand_and = newbit_vand_or = newbit_vxor_and = newbit_vxor_or = 0; var newbit_vand_and = newbit_vand_or = newbit_vxor_and = newbit_vxor_or = 0;
if( left.length === 1 && right.length === 1 ) if (left.length === 1 && right.length === 1) {
{ if (left.hasClass('checked') && right.hasClass('unchecked')) {
if(left.hasClass('checked') && right.hasClass('unchecked') )
{
newbit_vand_and = "1"; newbit_vand_and = "1";
newbit_vand_or = "1"; newbit_vand_or = "1";
} }
else if( left.hasClass('unchecked') && right.hasClass('checked') ) else if (left.hasClass('unchecked') && right.hasClass('checked')) {
{
newbit_vand_and = "1"; newbit_vand_and = "1";
newbit_vand_or = "1"; newbit_vand_or = "1";
newbit_vxor_and = "1"; newbit_vxor_and = "1";
newbit_vxor_or = "1"; newbit_vxor_or = "1";
} }
vand_and.val( vand_and.val().substr(0, 31 - bit) + newbit_vand_and + vand_and.val().substr(31 + 1 - bit) ); vand_and.val(vand_and.val().substr(0, 31 - bit) + newbit_vand_and + vand_and.val().substr(31 + 1 - bit));
vand_or.val ( vand_or.val().substr( 0, 31 - bit) + newbit_vand_or + vand_or.val().substr( 31 + 1 - bit) ); vand_or.val(vand_or.val().substr(0, 31 - bit) + newbit_vand_or + vand_or.val().substr(31 + 1 - bit));
vxor_and.val( vxor_and.val().substr(0, 31 - bit) + newbit_vxor_and + vxor_and.val().substr(31 + 1 - bit) ); vxor_and.val(vxor_and.val().substr(0, 31 - bit) + newbit_vxor_and + vxor_and.val().substr(31 + 1 - bit));
vxor_or.val ( vxor_or.val().substr( 0, 31 - bit) + newbit_vxor_or + vxor_and.val().substr(31 + 1 - bit) ); vxor_or.val(vxor_or.val().substr(0, 31 - bit) + newbit_vxor_or + vxor_and.val().substr(31 + 1 - bit));
} }
}); });
} }
@@ -348,8 +330,7 @@ function ini_edit_usrs(){
}); });
function save_masks() function save_masks() {
{
var cont = $('#masks_dialog'); var cont = $('#masks_dialog');
var maskform = $('#masks_dialog form'); var maskform = $('#masks_dialog form');
@@ -365,22 +346,21 @@ function ini_edit_usrs(){
type: 'POST', type: 'POST',
url: '../admin/users/rights/masks/apply/', url: '../admin/users/rights/masks/apply/',
data: { data: {
users:users, users: users,
base_id:base_id, base_id: base_id,
vand_and:vand_and, vand_and: vand_and,
vand_or:vand_or, vand_or: vand_or,
vxor_and:vxor_and, vxor_and: vxor_and,
vxor_or:vxor_or vxor_or: vxor_or
}, },
success: function(data){ success: function (data) {
$('#masks_dialog').dialog('close'); $('#masks_dialog').dialog('close');
} }
}); });
} }
function save_quotas() function save_quotas() {
{
var cont = $('#quotas_dialog'); var cont = $('#quotas_dialog');
var base_id = $('input[name="base_id"]', cont).val(); var base_id = $('input[name="base_id"]', cont).val();
var users = $('input[name="users"]', cont).val(); var users = $('input[name="users"]', cont).val();
@@ -389,33 +369,32 @@ function ini_edit_usrs(){
var switch_quota = $('.switch_quota', cont); var switch_quota = $('.switch_quota', cont);
if(switch_quota.hasClass('mixed')) if (switch_quota.hasClass('mixed'))
return; return;
var quota = 0; var quota = 0;
if(switch_quota.hasClass('checked')) if (switch_quota.hasClass('checked'))
quota = 1; quota = 1;
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/rights/quotas/apply/', url: '../admin/users/rights/quotas/apply/',
data: { data: {
act:"APPLYQUOTAS", act: "APPLYQUOTAS",
users:users, users: users,
base_id:base_id, base_id: base_id,
quota:quota, quota: quota,
droits:droits, droits: droits,
restes:restes restes: restes
}, },
success: function(data){ success: function (data) {
$('#quotas_dialog').dialog('close'); $('#quotas_dialog').dialog('close');
} }
}); });
} }
function save_time() function save_time() {
{
var cont = $('#time_dialog'); var cont = $('#time_dialog');
var dmin = $('input[name="dmin"]', cont).val(); var dmin = $('input[name="dmin"]', cont).val();
var dmax = $('input[name="dmax"]', cont).val(); var dmax = $('input[name="dmax"]', cont).val();
@@ -425,83 +404,79 @@ function ini_edit_usrs(){
var switch_time = $('.switch_time', cont); var switch_time = $('.switch_time', cont);
if(switch_time.hasClass('mixed')) if (switch_time.hasClass('mixed'))
return; return;
var limit = 0; var limit = 0;
if(switch_time.hasClass('checked')) if (switch_time.hasClass('checked'))
limit = 1; limit = 1;
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/rights/time/apply/', url: '../admin/users/rights/time/apply/',
data: { data: {
users:users, users: users,
base_id:base_id, base_id: base_id,
sbas_id:sbas_id, sbas_id: sbas_id,
limit:limit, limit: limit,
dmin:dmin, dmin: dmin,
dmax:dmax dmax: dmax
}, },
success: function(data){ success: function (data) {
$('#time_dialog').dialog('close'); $('#time_dialog').dialog('close');
} }
}); });
} }
function check_uncheck_menu(right, sbas_id, el) function check_uncheck_menu(right, sbas_id, el) {
{ var top = el.offset().top;
var top = el.offset().top ;
var left = el.offset().left + 16; var left = el.offset().left + 16;
$('body').append('<div id="users_check_uncheck" style="position:absolute;top:'+top+'px;left:'+left+'px;">'+ $('body').append('<div id="users_check_uncheck" style="position:absolute;top:' + top + 'px;left:' + left + 'px;">' +
'<div class="checker" >'+ '<div class="checker" >' +
language.check_all+ language.check_all +
'<input type="hidden" name="sbas_id" value="'+sbas_id+'"/>'+ '<input type="hidden" name="sbas_id" value="' + sbas_id + '"/>' +
'<input type="hidden" name="right" value="'+right+'"/>'+ '<input type="hidden" name="right" value="' + right + '"/>' +
'</div>'+ '</div>' +
'<div class="unchecker">'+ '<div class="unchecker">' +
language.uncheck_all+ language.uncheck_all +
'<input type="hidden" name="sbas_id" value="'+sbas_id+'"/>'+ '<input type="hidden" name="sbas_id" value="' + sbas_id + '"/>' +
'<input type="hidden" name="right" value="'+right+'"/>'+ '<input type="hidden" name="right" value="' + right + '"/>' +
'</div></div>'); '</div></div>');
$('#users_check_uncheck div').hover( $('#users_check_uncheck div').hover(
function(){ function () {
$(this).addClass('hovered'); $(this).addClass('hovered');
}, },
function(){ function () {
$(this).removeClass('hovered'); $(this).removeClass('hovered');
} }
); );
$('#users_check_uncheck div.checker').bind('click',function(event){ $('#users_check_uncheck div.checker').bind('click', function (event) {
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();
users_check(true, $('input[name="sbas_id"]',$(this)).val(), $('input[name="right"]',$(this)).val()); users_check(true, $('input[name="sbas_id"]', $(this)).val(), $('input[name="right"]', $(this)).val());
$('#users_check_uncheck').remove(); $('#users_check_uncheck').remove();
}); });
$('#users_check_uncheck div.unchecker').bind('click',function(event){ $('#users_check_uncheck div.unchecker').bind('click', function (event) {
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();
users_check(false, $('input[name="sbas_id"]',$(this)).val(), $('input[name="right"]',$(this)).val()); users_check(false, $('input[name="sbas_id"]', $(this)).val(), $('input[name="right"]', $(this)).val());
$('#users_check_uncheck').remove(); $('#users_check_uncheck').remove();
}); });
} }
function users_check(bool, sbas_id, right)
{ function users_check(bool, sbas_id, right) {
var newclass; var newclass;
if(bool) if (bool) {
{ newclass = "checked";
newclass="checked";
} }
else else {
{ newclass = "unchecked";
newclass="unchecked";
} }
$('.inside_sbas_'+sbas_id+'.'+right+':visible').each(function(i,n){ $('.inside_sbas_' + sbas_id + '.' + right + ':visible').each(function (i, n) {
user_click_box(null, $(n), newclass); user_click_box(null, $(n), newclass);
}); });
} }
} }

View File

@@ -4,13 +4,11 @@
*/ */
$(document).ready(function(){ $(document).ready(function () {
function users_select_this(n,k) function users_select_this(n, k) {
{
if(p4.users.sel.length >= 800) if (p4.users.sel.length >= 800) {
{
alert(language.max_record_selected); alert(language.max_record_selected);
return false; return false;
} }
@@ -19,19 +17,17 @@ $(document).ready(function(){
return true; return true;
} }
$('#users th.sortable').live('click', function(){ $('#users th.sortable').live('click',function () {
var $this = $(this); var $this = $(this);
var sort = $('input', $this).val(); var sort = $('input', $this).val();
if((sort == $('#users_page_form input[name="srt"]').val()) if ((sort == $('#users_page_form input[name="srt"]').val())
&& ($('#users_page_form input[name="ord"]').val() == 'asc')) && ($('#users_page_form input[name="ord"]').val() == 'asc')) {
{
var ord = 'desc'; var ord = 'desc';
} }
else else {
{
var ord = 'asc'; var ord = 'asc';
} }
@@ -39,63 +35,65 @@ $(document).ready(function(){
$('#users_page_form input[name="ord"]').val(ord); $('#users_page_form input[name="ord"]').val(ord);
$('#users_page_form').trigger('submit'); $('#users_page_form').trigger('submit');
}).live('mouseover', function(){$(this).addClass('hover');}) }).live('mouseover', function () {
.live('mouseout', function(){$(this).removeClass('hover');}); $(this).addClass('hover');
})
.live('mouseout', function () {
$(this).removeClass('hover');
});
var buttons = {}; var buttons = {};
buttons[language.create_user] = function(){ buttons[language.create_user] = function () {
check_new_user(false); check_new_user(false);
}; };
buttons[language.annuler] = function(){ buttons[language.annuler] = function () {
$('#user_add_dialog').dialog('close') $('#user_add_dialog').dialog('close')
}; };
$('#user_add_dialog').dialog({ $('#user_add_dialog').dialog({
buttons:buttons, buttons: buttons,
modal:true, modal: true,
resizable:false, resizable: false,
draggable:false, draggable: false,
width:500 width: 500
}).dialog('close'); }).dialog('close');
var buttons = {}; var buttons = {};
buttons[language.create_template] = function(){ buttons[language.create_template] = function () {
check_new_user(true); check_new_user(true);
}; };
buttons[language.annuler] = function(){ buttons[language.annuler] = function () {
$('#template_add_dialog').dialog('close'); $('#template_add_dialog').dialog('close');
}; };
$('#template_add_dialog').dialog({ $('#template_add_dialog').dialog({
buttons:buttons, buttons: buttons,
modal:true, modal: true,
resizable:false, resizable: false,
draggable:false, draggable: false,
width:500 width: 500
}).dialog('close'); }).dialog('close');
function check_new_user(is_template) function check_new_user(is_template) {
{
var container = is_template ? $('#template_add_dialog') : $('#user_add_dialog'); var container = is_template ? $('#template_add_dialog') : $('#user_add_dialog');
$('#new_user_loader').show(); $('#new_user_loader').show();
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/create/', url: '../admin/users/create/',
dataType : 'json', dataType: 'json',
data: { data: {
act:'CREATENEWUSER', act: 'CREATENEWUSER',
value:$('input[name="value"]', container).val(), value: $('input[name="value"]', container).val(),
send_credentials: $('input[name="send_credentials"]', container).is(':checked') ? 1 : 0, send_credentials: $('input[name="send_credentials"]', container).is(':checked') ? 1 : 0,
validate_mail: $('input[name="validate_mail"]', container).is(':checked') ? 1 : 0, validate_mail: $('input[name="validate_mail"]', container).is(':checked') ? 1 : 0,
template:is_template ? '1':'0' template: is_template ? '1' : '0'
}, },
success: function(data){ success: function (data) {
$('.new_user_loader', container).hide(); $('.new_user_loader', container).hide();
if(!data.error) if (!data.error) {
{
if (container.data("ui-dialog")) { if (container.data("ui-dialog")) {
container.dialog('close'); container.dialog('close');
} }
@@ -106,51 +104,48 @@ $(document).ready(function(){
type: 'POST', type: 'POST',
url: '../admin/users/rights/', url: '../admin/users/rights/',
data: { data: {
users : data.data users: data.data
}, },
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').html(data); $('#right-ajax').removeClass('loading').html(data);
} }
}); });
} }
else else {
{
alert(data.message); alert(data.message);
} }
}, },
error:function() error: function () {
{
alert(language.serverError); alert(language.serverError);
}, },
timeout:function() timeout: function () {
{
alert(language.serverTimeout); alert(language.serverTimeout);
} }
}); });
} }
$('#users_page .user_adder').live('click', function(){ $('#users_page .user_adder').live('click', function () {
if ($('#user_add_dialog').data("ui-dialog")) { if ($('#user_add_dialog').data("ui-dialog")) {
$('#user_add_dialog').dialog('open'); $('#user_add_dialog').dialog('open');
} }
}); });
$('#users_page .template_adder').live('click', function(){ $('#users_page .template_adder').live('click', function () {
if ($('#template_add_dialog').data("ui-dialog")) { if ($('#template_add_dialog').data("ui-dialog")) {
$('#template_add_dialog').dialog('open'); $('#template_add_dialog').dialog('open');
} }
}); });
$('#users_page_form').live('submit', function(){ $('#users_page_form').live('submit', function () {
var datas = $('#users_page_form').serializeArray(); var datas = $('#users_page_form').serializeArray();
$('#right-ajax').empty().addClass('loading'); $('#right-ajax').empty().addClass('loading');
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/search/', url: '../admin/users/search/',
data: datas, data: datas,
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').empty().html(data); $('#right-ajax').removeClass('loading').empty().html(data);
} }
}); });
@@ -158,14 +153,14 @@ $(document).ready(function(){
return false; return false;
}); });
$('#users_page_search').live('submit', function(){ $('#users_page_search').live('submit', function () {
var datas = $('#users_page_search').serializeArray(); var datas = $('#users_page_search').serializeArray();
$('#right-ajax').empty().addClass('loading'); $('#right-ajax').empty().addClass('loading');
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '../admin/users/search/', url: '../admin/users/search/',
data: datas, data: datas,
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').empty().html(data); $('#right-ajax').removeClass('loading').empty().html(data);
} }
}); });
@@ -173,7 +168,7 @@ $(document).ready(function(){
return false; return false;
}); });
$('#users_page_form .pager').live('click', function(){ $('#users_page_form .pager').live('click', function () {
var form = $('#users_page_form'); var form = $('#users_page_form');
var current_page = parseInt($('input[name="page"]', form).val()); var current_page = parseInt($('input[name="page"]', form).val());
@@ -182,32 +177,28 @@ $(document).ready(function(){
var offset_start = 0; var offset_start = 0;
if($(this).hasClass('prev')) if ($(this).hasClass('prev')) {
{ offset_start = (current_page - 2) * perPage;
offset_start = (current_page-2) * perPage;
} }
if($(this).hasClass('first')) if ($(this).hasClass('first')) {
{
offset_start = 0; offset_start = 0;
} }
if($(this).hasClass('next')) if ($(this).hasClass('next')) {
{
offset_start = current_page * perPage; offset_start = current_page * perPage;
} }
if($(this).hasClass('last')) if ($(this).hasClass('last')) {
{ offset_start = (Math.floor(parseInt($('input[name=total_results]').val()) / perPage)) * perPage;
offset_start = (Math.floor(parseInt($('input[name=total_results]').val()) / perPage))* perPage;
} }
$('input[name="offset_start"]', form).val(offset_start); $('input[name="offset_start"]', form).val(offset_start);
}); });
$('#users tbody tr, #users tbody td').live('dblclick', function(evt){ $('#users tbody tr, #users tbody td').live('dblclick', function (evt) {
$('#users_page_form .user_modifier').trigger('click'); $('#users_page_form .user_modifier').trigger('click');
}); });
$('#users tbody tr, #users tbody td').live('click', function(evt){ $('#users tbody tr, #users tbody td').live('click',function (evt) {
if(evt.stopPropagation) if (evt.stopPropagation)
evt.stopPropagation(); evt.stopPropagation();
evt.cancelBubble = true; evt.cancelBubble = true;
evt.preventDefault(); evt.preventDefault();
@@ -216,29 +207,24 @@ $(document).ready(function(){
var k = el.attr('id').split('_').pop(); var k = el.attr('id').split('_').pop();
if(is_shift_key(evt) && $('tr.last_selected', cont).length!=0) if (is_shift_key(evt) && $('tr.last_selected', cont).length != 0) {
{
var lst = $('tr', cont); var lst = $('tr', cont);
var index1 = $.inArray($('tr.last_selected', cont)[0],lst); var index1 = $.inArray($('tr.last_selected', cont)[0], lst);
var index2 = $.inArray($(el)[0],lst); var index2 = $.inArray($(el)[0], lst);
if(index2<index1) if (index2 < index1) {
{
var tmp = index1; var tmp = index1;
index1=(index2-1)<0?index2:(index2-1); index1 = (index2 - 1) < 0 ? index2 : (index2 - 1);
index2=tmp; index2 = tmp;
} }
var stopped = false; var stopped = false;
if(index2 != -1 && index1 != -1) if (index2 != -1 && index1 != -1) {
{ var exp = 'tr:gt(' + index1 + '):lt(' + (index2 - index1) + ')';
var exp = 'tr:gt('+index1+'):lt('+(index2-index1)+')'; $.each($(exp, cont), function (i, n) {
$.each($(exp, cont),function(i,n){
if(!$(n).hasClass('selected')) if (!$(n).hasClass('selected')) {
{
if(!users_select_this(n,$(n).attr('id').split('_').pop())) if (!users_select_this(n, $(n).attr('id').split('_').pop())) {
{
stopped = true; stopped = true;
return false; return false;
} }
@@ -246,63 +232,54 @@ $(document).ready(function(){
}); });
} }
if(!stopped && $.inArray(k,p4.users.sel)<0) if (!stopped && $.inArray(k, p4.users.sel) < 0) {
{ if (!users_select_this(el, k))
if(!users_select_this(el,k))
return false; return false;
} }
} }
else else {
{ if (!is_ctrl_key(evt)) {
if(!is_ctrl_key(evt)) if ($.inArray(k, p4.users.sel) < 0) {
{
if($.inArray(k,p4.users.sel)<0)
{
p4.users.sel = new Array(); p4.users.sel = new Array();
$('tr', cont).removeClass('selected'); $('tr', cont).removeClass('selected');
if(!users_select_this(el,k)) if (!users_select_this(el, k))
return false; return false;
} }
} }
else else {
{ if ($.inArray(k, p4.users.sel) >= 0) {
if($.inArray(k,p4.users.sel)>=0) p4.users.sel = $.grep(p4.users.sel, function (n) {
{ return(n != k);
p4.users.sel = $.grep(p4.users.sel,function(n){
return(n!=k);
}); });
$(el).removeClass('selected'); $(el).removeClass('selected');
} }
else else {
{ if (!users_select_this(el, k))
if(!users_select_this(el,k))
return false; return false;
} }
} }
} }
$('.last_selected', cont).removeClass('last_selected'); $('.last_selected', cont).removeClass('last_selected');
$(el).addClass('last_selected'); $(el).addClass('last_selected');
}).live('mousedown', function(evt){ }).live('mousedown', function (evt) {
if(evt.stopPropagation) if (evt.stopPropagation)
evt.stopPropagation(); evt.stopPropagation();
evt.cancelBubble = true; evt.cancelBubble = true;
evt.preventDefault(); evt.preventDefault();
}); });
$('#users_apply_template').live('submit', function(){ $('#users_apply_template').live('submit', function () {
var users = p4.users.sel.join(';'); var users = p4.users.sel.join(';');
if(users === '') if (users === '') {
{
return false; return false;
} }
var $this = $(this); var $this = $(this);
var template = $('select[name="template_chooser"]', $this).val(); var template = $('select[name="template_chooser"]', $this).val();
if(template === '') if (template === '') {
{
return false; return false;
} }
@@ -313,20 +290,19 @@ $(document).ready(function(){
type: $this.attr('method'), type: $this.attr('method'),
url: $this.attr('action'), url: $this.attr('action'),
data: { data: {
users : users, users: users,
template : template template: template
}, },
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').html(data); $('#right-ajax').removeClass('loading').html(data);
} }
}); });
return false; return false;
}); });
$('#users_page_form .user_modifier').live('click', function(){ $('#users_page_form .user_modifier').live('click', function () {
var users = p4.users.sel.join(';'); var users = p4.users.sel.join(';');
if(users === '') if (users === '') {
{
return false; return false;
} }
@@ -336,9 +312,9 @@ $(document).ready(function(){
type: 'POST', type: 'POST',
url: '../admin/users/rights/', url: '../admin/users/rights/',
data: { data: {
users : users users: users
}, },
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').html(data); $('#right-ajax').removeClass('loading').html(data);
} }
}); });
@@ -346,10 +322,9 @@ $(document).ready(function(){
}); });
$('#users_page_form .user_deleter').live('click', function(){ $('#users_page_form .user_deleter').live('click', function () {
var users = p4.users.sel.join(';'); var users = p4.users.sel.join(';');
if(users === '') if (users === '') {
{
return false; return false;
} }
@@ -359,19 +334,18 @@ $(document).ready(function(){
type: 'POST', type: 'POST',
url: '../admin/users/delete/', url: '../admin/users/delete/',
data: { data: {
users : users users: users
}, },
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').html(data); $('#right-ajax').removeClass('loading').html(data);
} }
}); });
return false; return false;
}); });
$('#users_page .invite_modifier, #users_page .autoregister_modifier').live('click', function(){ $('#users_page .invite_modifier, #users_page .autoregister_modifier').live('click', function () {
var users = $(this).next('input').val(); var users = $(this).next('input').val();
if($.trim(users) === '') if ($.trim(users) === '') {
{
return false; return false;
} }
@@ -381,9 +355,9 @@ $(document).ready(function(){
type: 'POST', type: 'POST',
url: '../admin/users/rights/', url: '../admin/users/rights/',
data: { data: {
users : users users: users
}, },
success: function(data){ success: function (data) {
$('#right-ajax').removeClass('loading').html(data); $('#right-ajax').removeClass('loading').html(data);
} }
}); });

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,30 @@
$(document).ready(function(){ $(document).ready(function () {
if(typeof validator_loaded === 'boolean') if (typeof validator_loaded === 'boolean')
return; return;
$('.confirm_report').live('click', function () {
$('.confirm_report').live('click',function(){
var $this = $(this); var $this = $(this);
$('.loader', $this).css({ $('.loader', $this).css({
visibility:'visible' visibility: 'visible'
}); });
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/lightbox/ajax/SET_RELEASE/" + $('#basket_validation_id').val() + "/", url: "/lightbox/ajax/SET_RELEASE/" + $('#basket_validation_id').val() + "/",
dataType: 'json', dataType: 'json',
error: function(data) { error: function (data) {
$('.loader', $this).css({ $('.loader', $this).css({
visibility: 'hidden' visibility: 'hidden'
}); });
}, },
timeout: function(data) { timeout: function (data) {
$('.loader', $this).css({ $('.loader', $this).css({
visibility: 'hidden' visibility: 'hidden'
}); });
}, },
success: function(data) { success: function (data) {
$('.loader', $this).css({ $('.loader', $this).css({
visibility: 'hidden' visibility: 'hidden'
}); });
@@ -41,7 +40,7 @@ $(document).ready(function(){
}); });
}); });
$('.agreement_radio').live('vmousedown', function(){ $('.agreement_radio').live('vmousedown', function () {
var sselcont_id = $(this).attr('for').split('_').pop(); var sselcont_id = $(this).attr('for').split('_').pop();
var agreement = $('#' + $(this).attr('for')).val() == 'yes' ? '1' : '-1'; var agreement = $('#' + $(this).attr('for')).val() == 'yes' ? '1' : '-1';
@@ -49,37 +48,34 @@ $(document).ready(function(){
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/lightbox/ajax/SET_ELEMENT_AGREEMENT/"+sselcont_id+"/", url: "/lightbox/ajax/SET_ELEMENT_AGREEMENT/" + sselcont_id + "/",
dataType: 'json', dataType: 'json',
data: { data: {
agreement : agreement agreement: agreement
}, },
error: function(datas){ error: function (datas) {
alert('error'); alert('error');
$.mobile.loading(); $.mobile.loading();
}, },
timeout: function(datas){ timeout: function (datas) {
alert('error'); alert('error');
$.mobile.loading(); $.mobile.loading();
}, },
success: function(datas){ success: function (datas) {
if(!datas.error) if (!datas.error) {
{ if (agreement == '1')
if(agreement == '1') $('.valid_choice_' + sselcont_id).removeClass('disagree').addClass('agree');
$('.valid_choice_'+sselcont_id).removeClass('disagree').addClass('agree');
else else
$('.valid_choice_'+sselcont_id).removeClass('agree').addClass('disagree'); $('.valid_choice_' + sselcont_id).removeClass('agree').addClass('disagree');
$.mobile.loading(); $.mobile.loading();
if(datas.error) if (datas.error) {
{
alert(datas.datas); alert(datas.datas);
return; return;
} }
releasable = datas.release; releasable = datas.release;
} }
else else {
{
alert(datas.datas); alert(datas.datas);
} }
return; return;
@@ -88,34 +84,33 @@ $(document).ready(function(){
return false; return false;
}); });
$('.note_area_validate').live('click', function(){ $('.note_area_validate').live('click', function () {
var sselcont_id = $(this).closest('form').find('input[name="sselcont_id"]').val(); var sselcont_id = $(this).closest('form').find('input[name="sselcont_id"]').val();
$.mobile.loading(); $.mobile.loading();
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/lightbox/ajax/SET_NOTE/"+sselcont_id+"/", url: "/lightbox/ajax/SET_NOTE/" + sselcont_id + "/",
dataType: 'json', dataType: 'json',
data: { data: {
note : $('#note_form_'+sselcont_id).find('textarea').val() note: $('#note_form_' + sselcont_id).find('textarea').val()
}, },
error: function(datas){ error: function (datas) {
alert('error'); alert('error');
$.mobile.loading(); $.mobile.loading();
}, },
timeout: function(datas){ timeout: function (datas) {
alert('error'); alert('error');
$.mobile.loading(); $.mobile.loading();
}, },
success: function(datas){ success: function (datas) {
$.mobile.loading(); $.mobile.loading();
if(datas.error) if (datas.error) {
{
alert(datas.datas); alert(datas.datas);
return; return;
} }
$('#notes_'+sselcont_id).empty().append(datas.datas); $('#notes_' + sselcont_id).empty().append(datas.datas);
window.history.back(); window.history.back();
return; return;
} }

View File

@@ -1,15 +1,15 @@
; ;
(function(document){ (function (document) {
/***************** /*****************
* Canva Object * Canva Object
*****************/ *****************/
var Canva = function(domCanva){ var Canva = function (domCanva) {
this.domCanva = domCanva; this.domCanva = domCanva;
}; };
Canva.prototype = { Canva.prototype = {
resize : function(elementDomNode){ resize: function (elementDomNode) {
var w = elementDomNode.getWidth(); var w = elementDomNode.getWidth();
var maxH = elementDomNode.getHeight(); var maxH = elementDomNode.getHeight();
@@ -31,10 +31,9 @@
return this; return this;
}, },
getContext2d : function(){ getContext2d: function () {
if (undefined === this.domCanva.getContext) if (undefined === this.domCanva.getContext) {
{
return G_vmlCanvasManager return G_vmlCanvasManager
.initElement(this.domCanva) .initElement(this.domCanva)
.getContext("2d"); .getContext("2d");
@@ -42,10 +41,10 @@
return this.domCanva.getContext('2d'); return this.domCanva.getContext('2d');
}, },
extractImage : function(){ extractImage: function () {
return this.domCanva.toDataURL("image/png"); return this.domCanva.toDataURL("image/png");
}, },
reset : function(){ reset: function () {
var context = this.getContext2d(); var context = this.getContext2d();
var w = this.getWidth(); var w = this.getWidth();
var h = this.getHeight(); var h = this.getHeight();
@@ -57,7 +56,7 @@
return this; return this;
}, },
copy : function(elementDomNode){ copy: function (elementDomNode) {
var context = this.getContext2d(); var context = this.getContext2d();
context.drawImage( context.drawImage(
@@ -70,13 +69,13 @@
return this; return this;
}, },
getDomElement : function(){ getDomElement: function () {
return this.domCanva; return this.domCanva;
}, },
getHeight : function(){ getHeight: function () {
return this.domCanva.offsetHeight; return this.domCanva.offsetHeight;
}, },
getWidth : function(){ getWidth: function () {
return this.domCanva.offsetWidth; return this.domCanva.offsetWidth;
} }
}; };
@@ -85,18 +84,18 @@
/****************** /******************
* Image Object * Image Object
******************/ ******************/
var Image = function(domElement){ var Image = function (domElement) {
this.domElement = domElement; this.domElement = domElement;
}; };
Image.prototype = { Image.prototype = {
getDomElement : function(){ getDomElement: function () {
return this.domElement; return this.domElement;
}, },
getHeight : function(){ getHeight: function () {
return this.domElement.offsetHeight; return this.domElement.offsetHeight;
}, },
getWidth : function(){ getWidth: function () {
return this.domElement.offsetWidth; return this.domElement.offsetWidth;
} }
}; };
@@ -105,45 +104,45 @@
* Video Object inherits from Image object * Video Object inherits from Image object
******************/ ******************/
var Video = function(domElement){ var Video = function (domElement) {
Image.call(this, domElement); Image.call(this, domElement);
this.aspectRatio = domElement.getAttribute('data-ratio'); this.aspectRatio = domElement.getAttribute('data-ratio');
}; };
Video.prototype = new Image(); Video.prototype = new Image();
Video.prototype.constructor = Video; Video.prototype.constructor = Video;
Video.prototype.getCurrentTime = function(){ Video.prototype.getCurrentTime = function () {
return Math.floor(this.domElement.currentTime); return Math.floor(this.domElement.currentTime);
}; };
Video.prototype.getAspectRatio = function(){ Video.prototype.getAspectRatio = function () {
return this.aspectRatio; return this.aspectRatio;
}; };
/****************** /******************
* Cache Object * Cache Object
******************/ ******************/
var Store = function(){ var Store = function () {
this.datas = {}; this.datas = {};
}; };
Store.prototype = { Store.prototype = {
set : function(id, item){ set: function (id, item) {
this.datas[id] = item; this.datas[id] = item;
return this; return this;
}, },
get : function(id){ get: function (id) {
if(!this.datas[id]){ if (!this.datas[id]) {
throw 'Unknown ID'; throw 'Unknown ID';
} }
return this.datas[id]; return this.datas[id];
}, },
remove : function(id) { remove: function (id) {
delete this.datas[id]; delete this.datas[id];
}, },
getLength : function(){ getLength: function () {
var count = 0; var count = 0;
for (var k in this.datas){ for (var k in this.datas) {
if (this.datas.hasOwnProperty(k)){ if (this.datas.hasOwnProperty(k)) {
++count; ++count;
} }
} }
@@ -154,7 +153,7 @@
/****************** /******************
* Screenshot Object * Screenshot Object
******************/ ******************/
var ScreenShot = function(id, canva, video){ var ScreenShot = function (id, canva, video) {
var date = new Date(); var date = new Date();
@@ -168,16 +167,16 @@
}; };
ScreenShot.prototype = { ScreenShot.prototype = {
getId:function(){ getId: function () {
return this.id; return this.id;
}, },
getDataURI: function(){ getDataURI: function () {
return this.dataURI; return this.dataURI;
}, },
getTimeStamp: function(){ getTimeStamp: function () {
return this.timestamp; return this.timestamp;
}, },
getVideoTime : function(){ getVideoTime: function () {
return this.videoTime; return this.videoTime;
} }
}; };
@@ -185,7 +184,7 @@
/** /**
* THUMB EDITOR * THUMB EDITOR
*/ */
var ThumbEditor = function(videoId, canvaId){ var ThumbEditor = function (videoId, canvaId) {
var domElement = document.getElementById(videoId); var domElement = document.getElementById(videoId);
@@ -194,18 +193,18 @@
} }
var store = new Store(); var store = new Store();
function getCanva(){ function getCanva() {
return document.getElementById(canvaId); return document.getElementById(canvaId);
} }
return { return {
isSupported : function () { isSupported: function () {
var elem = document.createElement('canvas'); var elem = document.createElement('canvas');
return !! document.getElementById(videoId) && document.getElementById(canvaId) return !!document.getElementById(videoId) && document.getElementById(canvaId)
&& !! elem.getContext && !! elem.getContext('2d'); && !!elem.getContext && !!elem.getContext('2d');
}, },
screenshot : function(){ screenshot: function () {
var screenshot = new ScreenShot( var screenshot = new ScreenShot(
store.getLength() + 1, store.getLength() + 1,
new Canva(getCanva()), new Canva(getCanva()),
@@ -216,8 +215,8 @@
return screenshot; return screenshot;
}, },
store : store, store: store,
copy: function(elementDomNode){ copy: function (elementDomNode) {
var element = new Image(elementDomNode); var element = new Image(elementDomNode);
var editorCanva = new Canva(getCanva()); var editorCanva = new Canva(getCanva());
editorCanva editorCanva
@@ -225,15 +224,15 @@
.resize(editorVideo) .resize(editorVideo)
.copy(element); .copy(element);
}, },
getCanvaImage : function(){ getCanvaImage: function () {
var canva = new Canva(getCanva()); var canva = new Canva(getCanva());
return canva.extractImage(); return canva.extractImage();
}, },
resetCanva : function(){ resetCanva: function () {
var editorCanva = new Canva(getCanva()); var editorCanva = new Canva(getCanva());
editorCanva.reset(); editorCanva.reset();
}, },
getNbScreenshot : function(){ getNbScreenshot: function () {
return store.getLength(); return store.getLength();
} }
}; };

View File

@@ -1,25 +1,22 @@
var p4 = p4 || {}; var p4 = p4 || {};
(function(p4){ (function (p4) {
function create_dialog() function create_dialog() {
{ if ($('#p4_alerts').length === 0) {
if($('#p4_alerts').length === 0)
{
$('body').append('<div id="p4_alerts"></div>'); $('body').append('<div id="p4_alerts"></div>');
} }
return $('#p4_alerts'); return $('#p4_alerts');
} }
function alert(title, message, callback) function alert(title, message, callback) {
{
var dialog = create_dialog(); var dialog = create_dialog();
var button = new Object(); var button = new Object();
button['Ok'] = function(){ button['Ok'] = function () {
if(typeof callback === 'function') if (typeof callback === 'function')
callback(); callback();
else else
dialog.dialog('close'); dialog.dialog('close');
@@ -29,28 +26,28 @@ var p4 = p4 || {};
dialog.dialog('destroy'); dialog.dialog('destroy');
} }
dialog.attr('title',title) dialog.attr('title', title)
.empty() .empty()
.append(message) .append(message)
.dialog({ .dialog({
autoOpen:false, autoOpen: false,
closeOnEscape:true, closeOnEscape: true,
resizable:false, resizable: false,
draggable:false, draggable: false,
modal:true, modal: true,
buttons : button, buttons: button,
overlay: { overlay: {
backgroundColor: '#000', backgroundColor: '#000',
opacity: 0.7 opacity: 0.7
} }
}).dialog('open'); }).dialog('open');
if(typeof callback === 'function') if (typeof callback === 'function') {
{ dialog.bind("dialogclose", function (event, ui) {
dialog.bind( "dialogclose", function(event, ui) {callback();}); callback();
});
} }
else else {
{
} }

View File

@@ -2,36 +2,31 @@
var p4 = p4 || {}; var p4 = p4 || {};
; ;
(function(p4, $){ (function (p4, $) {
function getLevel (level) { function getLevel(level) {
level = parseInt(level); level = parseInt(level);
if(isNaN(level) || level < 1) if (isNaN(level) || level < 1) {
{
return 1; return 1;
} }
return level; return level;
}; };
function getId (level) function getId(level) {
{
return 'DIALOG' + getLevel(level); return 'DIALOG' + getLevel(level);
}; };
function addButtons(buttons, dialog) function addButtons(buttons, dialog) {
{ if (dialog.options.closeButton === true) {
if(dialog.options.closeButton === true) buttons[language.fermer] = function () {
{
buttons[language.fermer] = function() {
dialog.Close(); dialog.Close();
}; };
} }
if(dialog.options.cancelButton === true) if (dialog.options.cancelButton === true) {
{ buttons[language.annuler] = function () {
buttons[language.annuler] = function() {
dialog.Close(); dialog.Close();
}; };
} }
@@ -41,12 +36,11 @@ var p4 = p4 || {};
var phraseaDialog = function (options, level) { var phraseaDialog = function (options, level) {
var createDialog = function(level) { var createDialog = function (level) {
var $dialog = $('#' + getId(level)); var $dialog = $('#' + getId(level));
if($dialog.length > 0) if ($dialog.length > 0) {
{
throw 'Dialog already exists at this level'; throw 'Dialog already exists at this level';
} }
@@ -57,15 +51,15 @@ var p4 = p4 || {};
}; };
var defaults = { var defaults = {
size : 'Medium', size: 'Medium',
buttons : {}, buttons: {},
loading : true, loading: true,
title : '', title: '',
closeOnEscape : true, closeOnEscape: true,
confirmExit:false, confirmExit: false,
closeCallback:false, closeCallback: false,
closeButton:false, closeButton: false,
cancelButton:false cancelButton: false
}, },
options = typeof options === 'object' ? options : {}, options = typeof options === 'object' ? options : {},
width, width,
@@ -81,11 +75,10 @@ var p4 = p4 || {};
this.options.buttons = addButtons(this.options.buttons, this); this.options.buttons = addButtons(this.options.buttons, this);
switch(this.options.size) switch (this.options.size) {
{
case 'Full': case 'Full':
height = bodySize.y - 30; height = bodySize.y - 30;
width = bodySize.x - 30 ; width = bodySize.x - 30;
break; break;
case 'Medium': case 'Medium':
width = Math.min(bodySize.x - 30, 730); width = Math.min(bodySize.x - 30, 730);
@@ -113,14 +106,12 @@ var p4 = p4 || {};
this.$dialog = createDialog(this.level), this.$dialog = createDialog(this.level),
zIndex = Math.min(this.level * 5000 + 5000, 32767); zIndex = Math.min(this.level * 5000 + 5000, 32767);
var CloseCallback = function() { var CloseCallback = function () {
if(typeof $this.options.closeCallback === 'function') if (typeof $this.options.closeCallback === 'function') {
{
$this.options.closeCallback($this.$dialog); $this.options.closeCallback($this.$dialog);
} }
if($this.closing === false) if ($this.closing === false) {
{
$this.closing = true; $this.closing = true;
$this.Close(); $this.Close();
} }
@@ -133,34 +124,32 @@ var p4 = p4 || {};
this.$dialog.attr('title', this.options.title) this.$dialog.attr('title', this.options.title)
.empty() .empty()
.dialog({ .dialog({
buttons:this.options.buttons, buttons: this.options.buttons,
draggable:false, draggable: false,
resizable:false, resizable: false,
closeOnEscape:this.options.closeOnEscape, closeOnEscape: this.options.closeOnEscape,
modal:true, modal: true,
width:width, width: width,
height:height, height: height,
open: function() { open: function () {
$(this).dialog("widget").css("z-index", zIndex); $(this).dialog("widget").css("z-index", zIndex);
}, },
close:CloseCallback close: CloseCallback
}) })
.dialog('open').addClass('dialog-' + this.options.size); .dialog('open').addClass('dialog-' + this.options.size);
if(this.options.loading === true) if (this.options.loading === true) {
{
this.$dialog.addClass('loading'); this.$dialog.addClass('loading');
} }
if(this.options.size === 'Full') if (this.options.size === 'Full') {
{
var $this = this; var $this = this;
$(window).unbind('resize.DIALOG' + getLevel(level)) $(window).unbind('resize.DIALOG' + getLevel(level))
.bind('resize.DIALOG' + getLevel(level), function(){ .bind('resize.DIALOG' + getLevel(level), function () {
if ($this.$dialog.data("ui-dialog")) { if ($this.$dialog.data("ui-dialog")) {
$this.$dialog.dialog('option', { $this.$dialog.dialog('option', {
width : bodySize.x - 30, width: bodySize.x - 30,
height : bodySize.y - 30 height: bodySize.y - 30
}); });
} }
}); });
@@ -170,61 +159,59 @@ var p4 = p4 || {};
}; };
phraseaDialog.prototype = { phraseaDialog.prototype = {
Close : function() { Close: function () {
p4.Dialog.Close(this.level); p4.Dialog.Close(this.level);
}, },
setContent : function (content) { setContent: function (content) {
this.$dialog.removeClass('loading').empty().append(content); this.$dialog.removeClass('loading').empty().append(content);
}, },
getId : function () { getId: function () {
return this.$dialog.attr('id'); return this.$dialog.attr('id');
}, },
load : function(url, method, params) { load: function (url, method, params) {
var $this = this; var $this = this;
this.loader = { this.loader = {
url : url, url: url,
method : typeof method === 'undefined' ? 'GET' : method, method: typeof method === 'undefined' ? 'GET' : method,
params : typeof params === 'undefined' ? {} : params params: typeof params === 'undefined' ? {} : params
}; };
$.ajax({ $.ajax({
type: this.loader.method, type: this.loader.method,
url: this.loader.url, url: this.loader.url,
dataType: 'html', dataType: 'html',
data : this.loader.params, data: this.loader.params,
beforeSend:function(){ beforeSend: function () {
}, },
success: function(data){ success: function (data) {
$this.setContent(data); $this.setContent(data);
return; return;
}, },
error: function(){ error: function () {
return; return;
}, },
timeout: function(){ timeout: function () {
return; return;
} }
}); });
}, },
refresh : function() { refresh: function () {
if(typeof this.loader === 'undefined') if (typeof this.loader === 'undefined') {
{
throw 'Nothing to refresh'; throw 'Nothing to refresh';
} }
this.load(this.loader.url, this.loader.method, this.loader.params); this.load(this.loader.url, this.loader.method, this.loader.params);
}, },
getDomElement : function () { getDomElement: function () {
return this.$dialog; return this.$dialog;
}, },
getOption : function (optionName) { getOption: function (optionName) {
if (this.$dialog.data("ui-dialog")) { if (this.$dialog.data("ui-dialog")) {
return this.$dialog.dialog('option', optionName); return this.$dialog.dialog('option', optionName);
} }
return null; return null;
}, },
setOption : function (optionName, optionValue) { setOption: function (optionName, optionValue) {
if(optionName === 'buttons') if (optionName === 'buttons') {
{
optionValue = addButtons(optionValue, this); optionValue = addButtons(optionValue, this);
} }
if (this.$dialog.data("ui-dialog")) { if (this.$dialog.data("ui-dialog")) {
@@ -238,10 +225,9 @@ var p4 = p4 || {};
}; };
Dialog.prototype = { Dialog.prototype = {
Create : function(options, level) { Create: function (options, level) {
if(this.get(level) instanceof phraseaDialog) if (this.get(level) instanceof phraseaDialog) {
{
this.get(level).Close(); this.get(level).Close();
} }
@@ -251,18 +237,17 @@ var p4 = p4 || {};
return $dialog; return $dialog;
}, },
get : function (level) { get: function (level) {
var id = getId(level); var id = getId(level);
if(id in this.currentStack) if (id in this.currentStack) {
{
return this.currentStack[id]; return this.currentStack[id];
} }
return null; return null;
}, },
Close : function (level) { Close: function (level) {
$(window).unbind('resize.DIALOG' + getLevel(level)); $(window).unbind('resize.DIALOG' + getLevel(level));
@@ -275,8 +260,7 @@ var p4 = p4 || {};
var id = this.get(level).getId(); var id = this.get(level).getId();
if(id in this.currentStack) if (id in this.currentStack) {
{
delete this.currentStack.id; delete this.currentStack.id;
} }
} }

View File

@@ -1,8 +1,7 @@
; ;
(function(window){ (function (window) {
var Feedback = function($container, context){ var Feedback = function ($container, context) {
this.container = $($container); this.container = $($container);
this.Context = context; this.Context = context;
@@ -10,23 +9,23 @@
this.selection = new Selectable( this.selection = new Selectable(
$('.user_content .badges', this.container), $('.user_content .badges', this.container),
{ {
selector:'.badge' selector: '.badge'
} }
); );
var $this = this; var $this = this;
$('.content .options .select-all', this.container).bind('click', function(){ $('.content .options .select-all', this.container).bind('click', function () {
$this.selection.selectAll(); $this.selection.selectAll();
}); });
$('.content .options .unselect-all', this.container).bind('click', function(){ $('.content .options .unselect-all', this.container).bind('click', function () {
$this.selection.empty(); $this.selection.empty();
}); });
$('.UserTips', this.container).tooltip(); $('.UserTips', this.container).tooltip();
$('a.user_adder', this.container).bind('click', function(){ $('a.user_adder', this.container).bind('click', function () {
var $this = $(this); var $this = $(this);
@@ -34,22 +33,22 @@
type: "GET", type: "GET",
url: $this.attr('href'), url: $this.attr('href'),
dataType: 'html', dataType: 'html',
beforeSend:function(){ beforeSend: function () {
var options = { var options = {
size : 'Medium', size: 'Medium',
title : $this.html() title: $this.html()
}; };
p4.Dialog.Create(options, 2).getDomElement().addClass('loading'); p4.Dialog.Create(options, 2).getDomElement().addClass('loading');
}, },
success: function(data){ success: function (data) {
p4.Dialog.get(2).getDomElement().removeClass('loading').empty().append(data); p4.Dialog.get(2).getDomElement().removeClass('loading').empty().append(data);
return; return;
}, },
error: function(){ error: function () {
p4.Dialog.get(2).Close(); p4.Dialog.get(2).Close();
return; return;
}, },
timeout: function(){ timeout: function () {
p4.Dialog.get(2).Close(); p4.Dialog.get(2).Close();
return; return;
} }
@@ -58,7 +57,7 @@
return false; return false;
}); });
$('.recommended_users', this.container).bind('click', function(){ $('.recommended_users', this.container).bind('click', function () {
var usr_id = $('input[name="usr_id"]', $(this)).val(); var usr_id = $('input[name="usr_id"]', $(this)).val();
@@ -67,19 +66,19 @@
return false; return false;
}); });
$('.recommended_users_list', this.container).bind('click', function(){ $('.recommended_users_list', this.container).bind('click', function () {
var content = $('#push_user_recommendations').html(); var content = $('#push_user_recommendations').html();
var options = { var options = {
size : 'Small', size: 'Small',
title : $(this).attr('title') title: $(this).attr('title')
}; };
$dialog = p4.Dialog.Create(options, 2); $dialog = p4.Dialog.Create(options, 2);
$dialog.setContent(content); $dialog.setContent(content);
$dialog.getDomElement().find('a.adder').bind('click', function(){ $dialog.getDomElement().find('a.adder').bind('click', function () {
$(this).addClass('added'); $(this).addClass('added');
@@ -90,24 +89,21 @@
return false; return false;
}); });
$dialog.getDomElement().find('a.adder').each(function(i, el){ $dialog.getDomElement().find('a.adder').each(function (i, el) {
var usr_id = $(this).closest('tr').find('input[name="usr_id"]').val(); var usr_id = $(this).closest('tr').find('input[name="usr_id"]').val();
if($('.badge_' + usr_id, $this.container).length > 0) if ($('.badge_' + usr_id, $this.container).length > 0) {
{
$(this).addClass('added'); $(this).addClass('added');
} }
}); });
return false; return false;
}); });
$('#PushBox form[name="FeedBackForm"]').bind('submit', function(){ $('#PushBox form[name="FeedBackForm"]').bind('submit', function () {
var $this = $(this); var $this = $(this);
@@ -116,27 +112,25 @@
url: $this.attr('action'), url: $this.attr('action'),
dataType: 'json', dataType: 'json',
data: $this.serializeArray(), data: $this.serializeArray(),
beforeSend:function(){ beforeSend: function () {
}, },
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
p4.Dialog.Close(1); p4.Dialog.Close(1);
p4.WorkZone.refresh(); p4.WorkZone.refresh();
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
return; return;
}, },
error: function(){ error: function () {
return; return;
}, },
timeout: function(){ timeout: function () {
return; return;
} }
@@ -145,21 +139,20 @@
return false; return false;
}); });
$('.FeedbackSend', this.container).bind('click', function(){ $('.FeedbackSend', this.container).bind('click', function () {
if($('.badges .badge', $container).length === 0) if ($('.badges .badge', $container).length === 0) {
{
alert(language.FeedBackNoUsersSelected); alert(language.FeedBackNoUsersSelected);
return; return;
} }
var buttons = {}; var buttons = {};
buttons[language.send] = function(){ buttons[language.send] = function () {
if ($.trim($('input[name="name"]', $dialog.getDomElement()).val()) === '') { if ($.trim($('input[name="name"]', $dialog.getDomElement()).val()) === '') {
options = { options = {
size : 'Alert', size: 'Alert',
closeButton : true, closeButton: true,
title : language.warning title: language.warning
}, },
$dialog = p4.Dialog.Create(options, 3); $dialog = p4.Dialog.Create(options, 3);
$dialog.setContent(language.FeedBackNameMandatory); $dialog.setContent(language.FeedBackNameMandatory);
@@ -178,12 +171,12 @@
}; };
var options = { var options = {
size : 'Small', size: 'Small',
buttons : buttons, buttons: buttons,
loading : true, loading: true,
title : language.send, title: language.send,
closeOnEscape : true, closeOnEscape: true,
cancelButton : true cancelButton: true
}; };
var $dialog = p4.Dialog.Create(options, 2); var $dialog = p4.Dialog.Create(options, 2);
@@ -198,14 +191,14 @@
$('textarea[name="message"]', $dialog.getDomElement()).val($('textarea[name="message"]', $FeedBackForm).val()); $('textarea[name="message"]', $dialog.getDomElement()).val($('textarea[name="message"]', $FeedBackForm).val());
$('.' + $this.Context, $dialog.getDomElement()).show(); $('.' + $this.Context, $dialog.getDomElement()).show();
$('form', $dialog.getDomElement()).submit(function() { $('form', $dialog.getDomElement()).submit(function () {
return false; return false;
}); });
}); });
$('.user_content .badges', this.container).disableSelection(); $('.user_content .badges', this.container).disableSelection();
$('.user_content .badges .badge .toggle', this.container).die('click').live('click', function(event){ $('.user_content .badges .badge .toggle', this.container).die('click').live('click', function (event) {
var $this = $(this); var $this = $(this);
@@ -216,19 +209,17 @@
return false; return false;
}); });
$('.general_togglers .general_toggler', this.container).bind('click', function(){ $('.general_togglers .general_toggler', this.container).bind('click', function () {
var feature = $(this).attr('feature'); var feature = $(this).attr('feature');
var $badges = $('.user_content .badge.selected', this.container); var $badges = $('.user_content .badge.selected', this.container);
var toggles = $('.status_off.toggle_' + feature, $badges); var toggles = $('.status_off.toggle_' + feature, $badges);
if(toggles.length === 0) if (toggles.length === 0) {
{
var toggles = $('.status_on.toggle_' + feature, $badges); var toggles = $('.status_on.toggle_' + feature, $badges);
} }
if(toggles.length === 0) if (toggles.length === 0) {
{
humane.info('No user selected'); humane.info('No user selected');
} }
@@ -236,26 +227,25 @@
return false; return false;
}); });
$('.user_content .badges .badge .deleter', this.container).live('click', function(event){ $('.user_content .badges .badge .deleter', this.container).live('click', function (event) {
var $elem = $(this).closest('.badge'); var $elem = $(this).closest('.badge');
$elem.fadeOut(function(){ $elem.fadeOut(function () {
$elem.remove(); $elem.remove();
}); });
return; return;
}); });
$('.list_manager', this.container).bind('click', function(){ $('.list_manager', this.container).bind('click', function () {
$('#PushBox').hide(); $('#PushBox').hide();
$('#ListManager').show(); $('#ListManager').show();
return false; return false;
}); });
$('a.list_loader', this.container).bind('click', function(){ $('a.list_loader', this.container).bind('click', function () {
var url = $(this).attr('href'); var url = $(this).attr('href');
var callbackList = function(list){ var callbackList = function (list) {
for(var i in list.entries) for (var i in list.entries) {
{
this.selectUser(list.entries[i].User); this.selectUser(list.entries[i].User);
} }
}; };
@@ -267,19 +257,18 @@
$('.options button', this.container); $('.options button', this.container);
$('form.list_saver', this.container).bind('submit', function(){ $('form.list_saver', this.container).bind('submit', function () {
var $form = $(this); var $form = $(this);
var $input = $('input[name="name"]', $form); var $input = $('input[name="name"]', $form);
var users = p4.Feedback.getUsers(); var users = p4.Feedback.getUsers();
if(users.length === 0) if (users.length === 0) {
{
humane.error('No users'); humane.error('No users');
return false; return false;
} }
p4.Lists.create($input.val(), function(list){ p4.Lists.create($input.val(), function (list) {
$input.val(''); $input.val('');
list.addUsers(users); list.addUsers(users);
}); });
@@ -289,68 +278,64 @@
$('input[name="users-search"]', this.container).autocomplete({ $('input[name="users-search"]', this.container).autocomplete({
minLength: 2, minLength: 2,
source: function( request, response ) { source: function (request, response) {
$.ajax({ $.ajax({
url: '/prod/push/search-user/', url: '/prod/push/search-user/',
dataType: "json", dataType: "json",
data: { data: {
query: request.term query: request.term
}, },
success: function( data ) { success: function (data) {
response(data); response(data);
} }
}); });
}, },
focus: function( event, ui ) { focus: function (event, ui) {
$( 'input[name="users-search"]' ).val( ui.item.label ); $('input[name="users-search"]').val(ui.item.label);
}, },
select: function( event, ui ) { select: function (event, ui) {
if(ui.item.type === 'USER') { if (ui.item.type === 'USER') {
$this.selectUser(ui.item); $this.selectUser(ui.item);
} else if(ui.item.type === 'LIST') { } else if (ui.item.type === 'LIST') {
for(var e in ui.item.entries) { for (var e in ui.item.entries) {
$this.selectUser(ui.item.entries[e].User); $this.selectUser(ui.item.entries[e].User);
} }
} }
return false; return false;
} }
}) })
.data( "ui-autocomplete" )._renderItem = function( ul, item ) { .data("ui-autocomplete")._renderItem = function (ul, item) {
var html = ""; var html = "";
if(item.type === 'USER') { if (item.type === 'USER') {
html = _.template($("#list_user_tpl").html(), { html = _.template($("#list_user_tpl").html(), {
item: item item: item
}); });
} else if(item.type === 'LIST') { } else if (item.type === 'LIST') {
html = _.template($("#list_list_tpl").html(), { html = _.template($("#list_list_tpl").html(), {
item: item item: item
}); });
} }
return $(html).data( "ui-autocomplete-item", item ).appendTo(ul); return $(html).data("ui-autocomplete-item", item).appendTo(ul);
}; };
return this; return this;
}; };
Feedback.prototype = { Feedback.prototype = {
selectUser : function(user){ selectUser: function (user) {
if(typeof user !== 'object') if (typeof user !== 'object') {
{ if (window.console) {
if(window.console)
{
console.log('trying to select a user with wrong datas'); console.log('trying to select a user with wrong datas');
} }
} }
if($('.badge_' + user.usr_id, this.container).length > 0) if ($('.badge_' + user.usr_id, this.container).length > 0) {
{
humane.info('User already selected'); humane.info('User already selected');
return; return;
} }
if(window.console) if (window.console) {
{
console.log('Selecting', user); console.log('Selecting', user);
} }
@@ -360,7 +345,7 @@
p4.Feedback.appendBadge(html); p4.Feedback.appendBadge(html);
}, },
loadUser : function(usr_id, callback) { loadUser: function (usr_id, callback) {
var $this = this; var $this = this;
$.ajax({ $.ajax({
@@ -368,35 +353,33 @@
url: '/prod/push/user/' + usr_id + '/', url: '/prod/push/user/' + usr_id + '/',
dataType: 'json', dataType: 'json',
data: { data: {
usr_id : usr_id usr_id: usr_id
}, },
success: function(data){ success: function (data) {
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback.call($this, data); callback.call($this, data);
} }
} }
}); });
}, },
loadList : function(url, callback) { loadList: function (url, callback) {
var $this = this; var $this = this;
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
url: url, url: url,
dataType: 'json', dataType: 'json',
success: function(data){ success: function (data) {
if(typeof callback === 'function') if (typeof callback === 'function') {
{
callback.call($this, data); callback.call($this, data);
} }
} }
}); });
}, },
appendBadge : function(badge){ appendBadge: function (badge) {
$('.user_content .badges', this.container).append(badge); $('.user_content .badges', this.container).append(badge);
}, },
addUser : function($form, callback){ addUser: function ($form, callback) {
var $this = this; var $this = this;
@@ -405,50 +388,47 @@
url: '/prod/push/add-user/', url: '/prod/push/add-user/',
dataType: 'json', dataType: 'json',
data: $form.serializeArray(), data: $form.serializeArray(),
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
$this.selectUser(data.user); $this.selectUser(data.user);
callback(); callback();
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
} }
}); });
}, },
getSelection : function() { getSelection: function () {
return this.selection; return this.selection;
}, },
getUsers : function() { getUsers: function () {
return $('.user_content .badge', this.container).map(function(){ return $('.user_content .badge', this.container).map(function () {
return $('input[name="id"]', $(this)).val(); return $('input[name="id"]', $(this)).val();
}); });
} }
}; };
var ListManager = function ($container) {
var ListManager = function($container) {
this.list = null; this.list = null;
this.container = $container; this.container = $container;
$('.back_link', this.container).bind('click', function(){ $('.back_link', this.container).bind('click', function () {
$('#PushBox').show(); $('#PushBox').show();
$('#ListManager').hide(); $('#ListManager').hide();
return false; return false;
}); });
$('a.list_sharer', this.container).die('click').live('click', function(){ $('a.list_sharer', this.container).die('click').live('click', function () {
var $this = $(this), var $this = $(this),
options = { options = {
size : 'Small', size: 'Small',
closeButton : true, closeButton: true,
title : $this.attr('title') title: $this.attr('title')
}, },
$dialog = p4.Dialog.Create(options, 2); $dialog = p4.Dialog.Create(options, 2);
@@ -458,7 +438,7 @@
}); });
$('a.user_adder', this.container).bind('click', function(){ $('a.user_adder', this.container).bind('click', function () {
var $this = $(this); var $this = $(this);
@@ -466,21 +446,22 @@
type: "GET", type: "GET",
url: $this.attr('href'), url: $this.attr('href'),
dataType: 'html', dataType: 'html',
beforeSend:function(){ beforeSend: function () {
var options = { var options = {
size : 'Medium', size: 'Medium',
title : $this.html() title: $this.html()
}; };
p4.Dialog.Create(options, 2).getDomElement().addClass('loading'); }, p4.Dialog.Create(options, 2).getDomElement().addClass('loading');
success: function(data){ },
success: function (data) {
p4.Dialog.get(2).getDomElement().removeClass('loading').empty().append(data); p4.Dialog.get(2).getDomElement().removeClass('loading').empty().append(data);
return; return;
}, },
error: function(){ error: function () {
p4.Dialog.get(2).Close(); p4.Dialog.get(2).Close();
return; return;
}, },
timeout: function(){ timeout: function () {
p4.Dialog.get(2).Close(); p4.Dialog.get(2).Close();
return; return;
} }
@@ -490,11 +471,10 @@
}); });
var initLeft = function () {
$('a.list_refresh', $container).bind('click', function (event) {
var initLeft = function() { var callback = function (datas) {
$('a.list_refresh', $container).bind('click', function(event){
var callback = function(datas){
$('.all-lists', $container).removeClass('loading').append(datas); $('.all-lists', $container).removeClass('loading').append(datas);
initLeft(); initLeft();
}; };
@@ -506,13 +486,13 @@
return false; return false;
}); });
$('a.list_adder', $container).bind('click', function(event){ $('a.list_adder', $container).bind('click', function (event) {
var makeDialog = function (box) { var makeDialog = function (box) {
var buttons = {}; var buttons = {};
buttons[language.valider] = function() { buttons[language.valider] = function () {
var callbackOK = function () { var callbackOK = function () {
$('a.list_refresh', $container).trigger('click'); $('a.list_refresh', $container).trigger('click');
@@ -521,8 +501,7 @@
var name = $('input[name="name"]', p4.Dialog.get(2).getDomElement()).val(); var name = $('input[name="name"]', p4.Dialog.get(2).getDomElement()).val();
if($.trim(name) === '') if ($.trim(name) === '') {
{
alert(language.listNameCannotBeEmpty); alert(language.listNameCannotBeEmpty);
return; return;
} }
@@ -531,9 +510,9 @@
}; };
var options = { var options = {
cancelButton : true, cancelButton: true,
buttons : buttons, buttons: buttons,
size:'Alert' size: 'Alert'
}; };
p4.Dialog.Create(options, 2).setContent(box); p4.Dialog.Create(options, 2).setContent(box);
@@ -546,7 +525,7 @@
return false; return false;
}); });
$('li.list a.list_link', $container).bind('click', function(event){ $('li.list a.list_link', $container).bind('click', function (event) {
var $this = $(this); var $this = $(this);
@@ -557,11 +536,11 @@
type: 'GET', type: 'GET',
url: $this.attr('href'), url: $this.attr('href'),
dataType: 'html', dataType: 'html',
success: function(data){ success: function (data) {
$('.editor', $container).removeClass('loading').append(data); $('.editor', $container).removeClass('loading').append(data);
initRight(); initRight();
}, },
beforeSend: function(){ beforeSend: function () {
$('.editor', $container).empty().addClass('loading'); $('.editor', $container).empty().addClass('loading');
} }
}); });
@@ -570,11 +549,11 @@
}); });
}; };
var initRight = function(){ var initRight = function () {
var $container = $('#ListManager .editor'); var $container = $('#ListManager .editor');
$('form[name="list-editor-search"]', $container).bind('submit', function(){ $('form[name="list-editor-search"]', $container).bind('submit', function () {
var $this = $(this); var $this = $(this);
var dest = $('.list-editor-results', $container); var dest = $('.list-editor-results', $container);
@@ -584,10 +563,10 @@
type: $this.attr('method'), type: $this.attr('method'),
dataType: "html", dataType: "html",
data: $this.serializeArray(), data: $this.serializeArray(),
beforeSend : function () { beforeSend: function () {
dest.empty().addClass('loading'); dest.empty().addClass('loading');
}, },
success: function( datas ) { success: function (datas) {
dest.empty().removeClass('loading').append(datas); dest.empty().removeClass('loading').append(datas);
} }
@@ -595,20 +574,20 @@
return false; return false;
}); });
$('form[name="list-editor-search"] select, form[name="list-editor-search"] input[name="ListUser"]', $container).bind('change', function(){ $('form[name="list-editor-search"] select, form[name="list-editor-search"] input[name="ListUser"]', $container).bind('change', function () {
$(this).closest('form').trigger('submit'); $(this).closest('form').trigger('submit');
}); });
$('.EditToggle', $container).bind('click', function(){ $('.EditToggle', $container).bind('click', function () {
$('.content.readonly, .content.readwrite', $('#ListManager')).toggle(); $('.content.readonly, .content.readwrite', $('#ListManager')).toggle();
return false; return false;
}); });
$('.Refresher', $container).bind('click', function(){ $('.Refresher', $container).bind('click', function () {
$('#ListManager ul.lists .list.selected a').trigger('click'); $('#ListManager ul.lists .list.selected a').trigger('click');
return false; return false;
}); });
$('form[name="SaveName"]', $container).bind('submit', function(){ $('form[name="SaveName"]', $container).bind('submit', function () {
var $this = $(this); var $this = $(this);
$.ajax({ $.ajax({
@@ -616,26 +595,24 @@
url: $this.attr('action'), url: $this.attr('action'),
dataType: 'json', dataType: 'json',
data: $this.serializeArray(), data: $this.serializeArray(),
beforeSend:function(){ beforeSend: function () {
}, },
success: function(data){ success: function (data) {
if(data.success) if (data.success) {
{
humane.info(data.message); humane.info(data.message);
$('#ListManager .lists .list_refresh').trigger('click'); $('#ListManager .lists .list_refresh').trigger('click');
} }
else else {
{
humane.error(data.message); humane.error(data.message);
} }
return; return;
}, },
error: function(){ error: function () {
return; return;
}, },
timeout: function(){ timeout: function () {
return; return;
} }
@@ -645,7 +622,7 @@
}); });
$('button.deleter', $container).bind('click', function(event){ $('button.deleter', $container).bind('click', function (event) {
var list_id = $(this).find('input[name=list_id]').val(); var list_id = $(this).find('input[name=list_id]').val();
@@ -653,7 +630,7 @@
var buttons = {}; var buttons = {};
buttons[language.valider] = function() { buttons[language.valider] = function () {
var callbackOK = function () { var callbackOK = function () {
$('#ListManager .all-lists a.list_refresh').trigger('click'); $('#ListManager .all-lists a.list_refresh').trigger('click');
@@ -665,9 +642,9 @@
}; };
var options = { var options = {
cancelButton : true, cancelButton: true,
buttons : buttons, buttons: buttons,
size:'Alert' size: 'Alert'
}; };
p4.Dialog.Create(options, 2).setContent(box); p4.Dialog.Create(options, 2).setContent(box);
@@ -683,15 +660,15 @@
initLeft(); initLeft();
$('.badges a.deleter', this.container).live('click', function(){ $('.badges a.deleter', this.container).live('click', function () {
var badge = $(this).closest('.badge'); var badge = $(this).closest('.badge');
var usr_id = badge.find('input[name="id"]').val(); var usr_id = badge.find('input[name="id"]').val();
var callback = function(list, datas){ var callback = function (list, datas) {
$('.counter.current, .list.selected .counter', $('#ListManager')).each(function(){ $('.counter.current, .list.selected .counter', $('#ListManager')).each(function () {
$(this).text(parseInt($(this).text()) - 1); $(this).text(parseInt($(this).text()) - 1);
}); });
@@ -706,19 +683,18 @@
}; };
ListManager.prototype = { ListManager.prototype = {
workOn : function(list_id) { workOn: function (list_id) {
this.list = new document.List(list_id); this.list = new document.List(list_id);
}, },
getList : function(){ getList: function () {
return this.list; return this.list;
}, },
appendBadge : function(datas) { appendBadge: function (datas) {
$('#ListManager .badges').append(datas); $('#ListManager .badges').append(datas);
} }
}; };
window.Feedback = Feedback; window.Feedback = Feedback;
window.ListManager = ListManager; window.ListManager = ListManager;

View File

@@ -1,9 +1,9 @@
(function() { (function () {
$(document).ready(function() { $(document).ready(function () {
humane.info = humane.spawn({addnCls: 'humane-libnotify-info', timeout: 1000}); humane.info = humane.spawn({addnCls: 'humane-libnotify-info', timeout: 1000});
humane.error = humane.spawn({addnCls: 'humane-libnotify-error', timeout: 1000}); humane.error = humane.spawn({addnCls: 'humane-libnotify-error', timeout: 1000});
$('a.dialog').live('click', function(event) { $('a.dialog').live('click', function (event) {
var $this = $(this), size = 'Medium'; var $this = $(this), size = 'Medium';
if ($this.hasClass('small-dialog')) { if ($this.hasClass('small-dialog')) {
@@ -25,7 +25,7 @@
type: "GET", type: "GET",
url: $this.attr('href'), url: $this.attr('href'),
dataType: 'html', dataType: 'html',
success: function(data) { success: function (data) {
$dialog.setContent(data); $dialog.setContent(data);
return; return;
} }

View File

@@ -1,21 +1,21 @@
var p4 = p4 || {}; var p4 = p4 || {};
(function(p4, window){ (function (p4, window) {
p4.Results = { p4.Results = {
'Selection':new Selectable($('#answers'), { 'Selection': new Selectable($('#answers'), {
selector : '.IMGT', selector: '.IMGT',
limit:800, limit: 800,
selectStart:function(event, selection){ selectStart: function (event, selection) {
$('#answercontextwrap table:visible').hide(); $('#answercontextwrap table:visible').hide();
}, },
selectStop:function(event, selection){ selectStop: function (event, selection) {
viewNbSelect(); viewNbSelect();
}, },
callbackSelection:function(element){ callbackSelection: function (element) {
var elements = $(element).attr('id').split('_'); var elements = $(element).attr('id').split('_');
return elements.slice(elements.length - 2 ,elements.length).join('_'); return elements.slice(elements.length - 2, elements.length).join('_');
} }
}) })
}; };

View File

@@ -2,40 +2,40 @@
var p4 = p4 || {}; var p4 = p4 || {};
; ;
(function(p4, $){ (function (p4, $) {
/** /**
* UPLOADER MANAGER * UPLOADER MANAGER
*/ */
var UploaderManager = function(options){ var UploaderManager = function (options) {
var options = options || {}; var options = options || {};
if(false === ("container" in options)){ if (false === ("container" in options)) {
throw "missing container parameter"; throw "missing container parameter";
} }
else if(! options.container.jquery){ else if (!options.container.jquery) {
throw "container parameter must be a jquery dom element"; throw "container parameter must be a jquery dom element";
} }
if(false === ("settingsBox" in options)){ if (false === ("settingsBox" in options)) {
throw "missing settingBox parameter"; throw "missing settingBox parameter";
} }
else if(! options.settingsBox.jquery){ else if (!options.settingsBox.jquery) {
throw "container parameter must be a jquery dom element"; throw "container parameter must be a jquery dom element";
} }
if(false === ("uploadBox" in options)){ if (false === ("uploadBox" in options)) {
throw "missing uploadBox parameter"; throw "missing uploadBox parameter";
} }
else if(! options.uploadBox.jquery){ else if (!options.uploadBox.jquery) {
throw "container parameter must be a jquery dom element"; throw "container parameter must be a jquery dom element";
} }
if(false === ("downloadBox" in options)){ if (false === ("downloadBox" in options)) {
throw "missing downloadBox parameter"; throw "missing downloadBox parameter";
} }
else if(! options.downloadBox.jquery){ else if (!options.downloadBox.jquery) {
throw "container parameter must be a jquery dom element"; throw "container parameter must be a jquery dom element";
} }
@@ -51,7 +51,7 @@ var p4 = p4 || {};
this.options.downloadBox = this.options.downloadBox.find('ul:first'); this.options.downloadBox = this.options.downloadBox.find('ul:first');
if($.isFunction($.fn.sortable)){ if ($.isFunction($.fn.sortable)) {
this.options.uploadBox.sortable(); this.options.uploadBox.sortable();
} }
@@ -63,54 +63,54 @@ var p4 = p4 || {};
}; };
UploaderManager.prototype = { UploaderManager.prototype = {
setOptions : function(options){ setOptions: function (options) {
return $.extend(this.options, options); return $.extend(this.options, options);
}, },
getContainer : function(){ getContainer: function () {
return this.options.container; return this.options.container;
}, },
getUploadBox : function(){ getUploadBox: function () {
return this.options.uploadBox; return this.options.uploadBox;
}, },
getSettingsBox : function(){ getSettingsBox: function () {
return this.options.settingsBox; return this.options.settingsBox;
}, },
getDownloadBox : function(){ getDownloadBox: function () {
return this.options.downloadBox; return this.options.downloadBox;
}, },
clearUploadBox: function(){ clearUploadBox: function () {
this.getUploadBox().empty(); this.getUploadBox().empty();
this.uploadIndex = 0; this.uploadIndex = 0;
this.Queue.clear(); this.Queue.clear();
}, },
getDatas : function(){ getDatas: function () {
return this.Queue.all(); return this.Queue.all();
}, },
getData : function(index){ getData: function (index) {
return this.Queue.get(index); return this.Queue.get(index);
}, },
addData: function(data){ addData: function (data) {
this.uploadIndex++; this.uploadIndex++;
data.uploadIndex = this.uploadIndex; data.uploadIndex = this.uploadIndex;
this.Queue.set(this.uploadIndex, data); this.Queue.set(this.uploadIndex, data);
}, },
removeData : function(index){ removeData: function (index) {
this.Queue.remove(index); this.Queue.remove(index);
}, },
addAttributeToData : function(indexOfData, attribute, value){ addAttributeToData: function (indexOfData, attribute, value) {
var data = this.getData(indexOfData); var data = this.getData(indexOfData);
if($.type(attribute) === "string"){ if ($.type(attribute) === "string") {
data[attribute] = value; data[attribute] = value;
this.Queue.set(indexOfData, data); this.Queue.set(indexOfData, data);
} }
}, },
getUploadIndex : function(){ getUploadIndex: function () {
return this.uploadIndex; return this.uploadIndex;
}, },
hasData : function(){ hasData: function () {
return !this.Queue.isEmpty(); return !this.Queue.isEmpty();
}, },
countData: function (){ countData: function () {
return this.Queue.getLength(); return this.Queue.getLength();
} }
}; };
@@ -130,29 +130,29 @@ var p4 = p4 || {};
* canva: (boolean) render preview as canva if supported by the navigator * canva: (boolean) render preview as canva if supported by the navigator
*/ */
var Preview = function(){ var Preview = function () {
this.options = { this.options = {
fileType: /^image\/(gif|jpeg|png|jpg)$/, fileType: /^image\/(gif|jpeg|png|jpg)$/,
maxSize : 5242880 // 5MB maxSize: 5242880 // 5MB
}; };
}; };
Preview.prototype = { Preview.prototype = {
setOptions: function(options){ setOptions: function (options) {
this.options = $.extend(this.options, options); this.options = $.extend(this.options, options);
}, },
getOptions: function(){ getOptions: function () {
return this.options; return this.options;
}, },
render: function(file, callback){ render: function (file, callback) {
if(typeof loadImage === 'function' && this.options.fileType.test(file.type)){ if (typeof loadImage === 'function' && this.options.fileType.test(file.type)) {
if($.type(this.options.maxSize) !== 'number' || file.size < this.options.maxSize){ if ($.type(this.options.maxSize) !== 'number' || file.size < this.options.maxSize) {
var options = { var options = {
maxWidth: this.options.maxWidth || 150, maxWidth: this.options.maxWidth || 150,
maxHeight: this.options.maxHeight || 75, maxHeight: this.options.maxHeight || 75,
minWidth: this.options.minWidth || 80, minWidth: this.options.minWidth || 80,
minHeight: this.options.minHeight || 40, minHeight: this.options.minHeight || 40,
canvas : this.options.canva || true canvas: this.options.canva || true
}; };
loadImage(file, callback, options); loadImage(file, callback, options);
} }
@@ -165,7 +165,7 @@ var p4 = p4 || {};
* FORMATER * FORMATER
*/ */
var Formater = function(){ var Formater = function () {
}; };
@@ -200,50 +200,50 @@ var p4 = p4 || {};
} }
return bytes + ' o/s'; return bytes + ' o/s';
}, },
pourcent: function(current, total){ pourcent: function (current, total) {
return (current/ total * 100).toFixed(2); return (current / total * 100).toFixed(2);
} }
}; };
/** /**
* QUEUE * QUEUE
*/ */
var Queue = function(){ var Queue = function () {
this.list = {}; this.list = {};
}; };
Queue.prototype = { Queue.prototype = {
all : function(){ all: function () {
return this.list; return this.list;
}, },
set : function(id, item){ set: function (id, item) {
this.list[id] = item; this.list[id] = item;
return this; return this;
}, },
get : function(id){ get: function (id) {
if(!this.list[id]){ if (!this.list[id]) {
throw 'Unknown ID' + id; throw 'Unknown ID' + id;
} }
return this.list[id]; return this.list[id];
}, },
remove : function(id) { remove: function (id) {
delete this.list[id]; delete this.list[id];
}, },
getLength : function(){ getLength: function () {
var count = 0; var count = 0;
for (var k in this.list){ for (var k in this.list) {
if (this.list.hasOwnProperty(k)){ if (this.list.hasOwnProperty(k)) {
++count; ++count;
} }
} }
return count; return count;
}, },
isEmpty: function(){ isEmpty: function () {
return this.getLength() === 0; return this.getLength() === 0;
}, },
clear: function(){ clear: function () {
var $this = this; var $this = this;
$.each(this.list, function(k){ $.each(this.list, function (k) {
$this.remove(k); $this.remove(k);
}); });
} }

View File

@@ -1,8 +1,7 @@
var p4 = p4 || {}; var p4 = p4 || {};
(function(p4) { (function (p4) {
function refreshBaskets(baskId, sort, scrolltobottom, type) function refreshBaskets(baskId, sort, scrolltobottom, type) {
{
type = typeof type === 'undefined' ? 'basket' : type; type = typeof type === 'undefined' ? 'basket' : type;
var active = $('#baskets .SSTT.ui-state-active'); var active = $('#baskets .SSTT.ui-state-active');
@@ -19,12 +18,12 @@ var p4 = p4 || {};
data: { data: {
id: baskId, id: baskId,
sort: sort, sort: sort,
type:type type: type
}, },
beforeSend: function() { beforeSend: function () {
$('#basketcontextwrap').remove(); $('#basketcontextwrap').remove();
}, },
success: function(data) { success: function (data) {
var cache = $("#idFrameC #baskets"); var cache = $("#idFrameC #baskets");
if ($(".SSTT", cache).data("ui-droppable")) { if ($(".SSTT", cache).data("ui-droppable")) {
@@ -53,8 +52,7 @@ var p4 = p4 || {};
}); });
} }
function setTemporaryPref(name, value) function setTemporaryPref(name, value) {
{
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "/user/preferences/temporary/", url: "/user/preferences/temporary/",
@@ -62,13 +60,13 @@ var p4 = p4 || {};
prop: name, prop: name,
value: value value: value
}, },
success: function(data) { success: function (data) {
return; return;
} }
}); });
} }
$("#baskets div.content select[name=valid_ord]").live('change', function() { $("#baskets div.content select[name=valid_ord]").live('change', function () {
var active = $('#baskets .SSTT.ui-state-active'); var active = $('#baskets .SSTT.ui-state-active');
if (active.length === 0) { if (active.length === 0) {
return; return;
@@ -79,19 +77,18 @@ var p4 = p4 || {};
getContent(active, order); getContent(active, order);
}); });
function WorkZoneElementRemover(el, confirm) function WorkZoneElementRemover(el, confirm) {
{
var context = el.data('context'); var context = el.data('context');
if (confirm !== true && $(el).hasClass('groupings') && p4.reg_delete) { if (confirm !== true && $(el).hasClass('groupings') && p4.reg_delete) {
var buttons = {}; var buttons = {};
buttons[language.valider] = function() { buttons[language.valider] = function () {
$("#DIALOG-baskets").dialog('close').remove(); $("#DIALOG-baskets").dialog('close').remove();
WorkZoneElementRemover(el, true); WorkZoneElementRemover(el, true);
}; };
buttons[language.annuler] = function() { buttons[language.annuler] = function () {
$("#DIALOG-baskets").dialog('close').remove(); $("#DIALOG-baskets").dialog('close').remove();
}; };
@@ -121,10 +118,10 @@ var p4 = p4 || {};
type: "POST", type: "POST",
url: $(el).attr('href'), url: $(el).attr('href'),
dataType: 'json', dataType: 'json',
beforeSend: function() { beforeSend: function () {
$('.wrapCHIM_' + id).find('.CHIM').fadeOut(); $('.wrapCHIM_' + id).find('.CHIM').fadeOut();
}, },
success: function(data) { success: function (data) {
if (data.success) { if (data.success) {
humane.info(data.message); humane.info(data.message);
p4.WorkZone.Selection.remove(id); p4.WorkZone.Selection.remove(id);
@@ -170,8 +167,7 @@ var p4 = p4 || {};
} }
function activeBaskets() function activeBaskets() {
{
var cache = $("#idFrameC #baskets"); var cache = $("#idFrameC #baskets");
cache.accordion({ cache.accordion({
@@ -179,7 +175,7 @@ var p4 = p4 || {};
heightStyle: "content", heightStyle: "content",
collapsible: true, collapsible: true,
header: 'div.header', header: 'div.header',
activate: function(event, ui) { activate: function (event, ui) {
var b_active = $('#baskets .SSTT.active'); var b_active = $('#baskets .SSTT.active');
if (p4.next_bask_scroll) { if (p4.next_bask_scroll) {
p4.next_bask_scroll = false; p4.next_bask_scroll = false;
@@ -200,7 +196,8 @@ var p4 = p4 || {};
b_active.not('.ui-state-active').removeClass('active'); b_active.not('.ui-state-active').removeClass('active');
if (uiactive.length === 0) { if (uiactive.length === 0) {
return; /* everything is closed */ return;
/* everything is closed */
} }
uiactive.addClass('ui-state-focus active'); uiactive.addClass('ui-state-focus active');
@@ -210,14 +207,14 @@ var p4 = p4 || {};
getContent(uiactive); getContent(uiactive);
}, },
beforeActivate: function(event, ui) { beforeActivate: function (event, ui) {
ui.newHeader.addClass('active'); ui.newHeader.addClass('active');
$('#basketcontextwrap .basketcontextmenu').hide(); $('#basketcontextwrap .basketcontextmenu').hide();
} }
}); });
$('.bloc', cache).droppable({ $('.bloc', cache).droppable({
accept: function(elem) { accept: function (elem) {
if ($(elem).hasClass('grouping') && !$(elem).hasClass('SSTT')) if ($(elem).hasClass('grouping') && !$(elem).hasClass('SSTT'))
return true; return true;
return false; return false;
@@ -225,7 +222,7 @@ var p4 = p4 || {};
scope: 'objects', scope: 'objects',
hoverClass: 'groupDrop', hoverClass: 'groupDrop',
tolerance: 'pointer', tolerance: 'pointer',
drop: function() { drop: function () {
fix(); fix();
} }
}); });
@@ -240,7 +237,7 @@ var p4 = p4 || {};
scope: 'objects', scope: 'objects',
hoverClass: 'baskDrop', hoverClass: 'baskDrop',
tolerance: 'pointer', tolerance: 'pointer',
accept: function(elem) { accept: function (elem) {
if ($(elem).hasClass('CHIM')) { if ($(elem).hasClass('CHIM')) {
if ($(elem).closest('.content').prev()[0] === $(this)[0]) { if ($(elem).closest('.content').prev()[0] === $(this)[0]) {
return false; return false;
@@ -250,7 +247,7 @@ var p4 = p4 || {};
return false; return false;
return true; return true;
}, },
drop: function(event, ui) { drop: function (event, ui) {
dropOnBask(event, ui.draggable, $(this)); dropOnBask(event, ui.draggable, $(this));
} }
}); });
@@ -258,12 +255,12 @@ var p4 = p4 || {};
if ($('#basketcontextwrap').length === 0) if ($('#basketcontextwrap').length === 0)
$('body').append('<div id="basketcontextwrap"></div>'); $('body').append('<div id="basketcontextwrap"></div>');
$('.context-menu-item', cache).hover(function() { $('.context-menu-item', cache).hover(function () {
$(this).addClass('context-menu-item-hover'); $(this).addClass('context-menu-item-hover');
}, function() { }, function () {
$(this).removeClass('context-menu-item-hover'); $(this).removeClass('context-menu-item-hover');
}); });
$.each($(".SSTT", cache), function() { $.each($(".SSTT", cache), function () {
var el = $(this); var el = $(this);
$(this).find('.contextMenuTrigger').contextMenu('#' + $(this).attr('id') + ' .contextMenu', { $(this).find('.contextMenuTrigger').contextMenu('#' + $(this).attr('id') + ' .contextMenu', {
'appendTo': '#basketcontextwrap', 'appendTo': '#basketcontextwrap',
@@ -278,8 +275,7 @@ var p4 = p4 || {};
} }
function getContent(header, order) function getContent(header, order) {
{
if (window.console) { if (window.console) {
console.log('Reload content for ', header); console.log('Reload content for ', header);
} }
@@ -294,11 +290,11 @@ var p4 = p4 || {};
type: "GET", type: "GET",
url: url, url: url,
dataType: 'html', dataType: 'html',
beforeSend: function() { beforeSend: function () {
$('#tooltip').hide(); $('#tooltip').hide();
header.next().addClass('loading'); header.next().addClass('loading');
}, },
success: function(data) { success: function (data) {
header.removeClass('unread'); header.removeClass('unread');
var dest = header.next(); var dest = header.next();
@@ -309,14 +305,14 @@ var p4 = p4 || {};
dest.append(data); dest.append(data);
$('a.WorkZoneElementRemover', dest).bind('mousedown', function(event) { $('a.WorkZoneElementRemover', dest).bind('mousedown',function (event) {
return false; return false;
}).bind('click', function(event) { }).bind('click', function (event) {
return WorkZoneElementRemover($(this), false); return WorkZoneElementRemover($(this), false);
}); });
dest.droppable({ dest.droppable({
accept: function(elem) { accept: function (elem) {
if ($(elem).hasClass('CHIM')) { if ($(elem).hasClass('CHIM')) {
if ($(elem).closest('.content')[0] === $(this)[0]) { if ($(elem).closest('.content')[0] === $(this)[0]) {
return false; return false;
@@ -328,7 +324,7 @@ var p4 = p4 || {};
}, },
hoverClass: 'baskDrop', hoverClass: 'baskDrop',
scope: 'objects', scope: 'objects',
drop: function(event, ui) { drop: function (event, ui) {
dropOnBask(event, ui.draggable, $(this).prev()); dropOnBask(event, ui.draggable, $(this).prev());
}, },
tolerance: 'pointer' tolerance: 'pointer'
@@ -337,7 +333,7 @@ var p4 = p4 || {};
$('.noteTips, .captionRolloverTips', dest).tooltip(); $('.noteTips, .captionRolloverTips', dest).tooltip();
dest.find('.CHIM').draggable({ dest.find('.CHIM').draggable({
helper: function() { helper: function () {
$('body').append('<div id="dragDropCursor" ' + $('body').append('<div id="dragDropCursor" ' +
'style="position:absolute;z-index:9999;background:red;' + 'style="position:absolute;z-index:9999;background:red;' +
'-moz-border-radius:8px;-webkit-border-radius:8px;">' + '-moz-border-radius:8px;-webkit-border-radius:8px;">' +
@@ -353,23 +349,23 @@ var p4 = p4 || {};
top: 10, top: 10,
left: -20 left: -20
}, },
start: function(event, ui) { start: function (event, ui) {
var baskets = $('#baskets'); var baskets = $('#baskets');
baskets.append('<div class="top-scroller"></div>' + baskets.append('<div class="top-scroller"></div>' +
'<div class="bottom-scroller"></div>'); '<div class="bottom-scroller"></div>');
$('.bottom-scroller', baskets).bind('mousemove', function() { $('.bottom-scroller', baskets).bind('mousemove', function () {
$('#baskets .bloc').scrollTop($('#baskets .bloc').scrollTop() + 30); $('#baskets .bloc').scrollTop($('#baskets .bloc').scrollTop() + 30);
}); });
$('.top-scroller', baskets).bind('mousemove', function() { $('.top-scroller', baskets).bind('mousemove', function () {
$('#baskets .bloc').scrollTop($('#baskets .bloc').scrollTop() - 30); $('#baskets .bloc').scrollTop($('#baskets .bloc').scrollTop() - 30);
}); });
}, },
stop: function() { stop: function () {
$('#baskets').find('.top-scroller, .bottom-scroller') $('#baskets').find('.top-scroller, .bottom-scroller')
.unbind() .unbind()
.remove(); .remove();
}, },
drag: function(event, ui) { drag: function (event, ui) {
if (is_ctrl_key(event) || $(this).closest('.content').hasClass('grouping')) if (is_ctrl_key(event) || $(this).closest('.content').hasClass('grouping'))
$('#dragDropCursor div').empty().append('+ ' + p4.WorkZone.Selection.length()); $('#dragDropCursor div').empty().append('+ ' + p4.WorkZone.Selection.length());
else else
@@ -383,8 +379,7 @@ var p4 = p4 || {};
}); });
} }
function dropOnBask(event, from, destKey, singleSelection) function dropOnBask(event, from, destKey, singleSelection) {
{
var action = "", from = $(from), dest_uri = '', lstbr = [], sselcont = [], act = "ADD"; var action = "", from = $(from), dest_uri = '', lstbr = [], sselcont = [], act = "ADD";
if (from.hasClass("CHIM")) { if (from.hasClass("CHIM")) {
@@ -422,7 +417,7 @@ var p4 = p4 || {};
lstbr = p4.Results.Selection.get(); lstbr = p4.Results.Selection.get();
} }
} else { } else {
sselcont = $.map(p4.WorkZone.Selection.get(), function(n, i) { sselcont = $.map(p4.WorkZone.Selection.get(), function (n, i) {
return $('.CHIM_' + n, $('#baskets .content:visible')).attr('id').split('_').slice(1, 2).pop(); return $('.CHIM_' + n, $('#baskets .content:visible')).attr('id').split('_').slice(1, 2).pop();
}); });
lstbr = p4.WorkZone.Selection.get(); lstbr = p4.WorkZone.Selection.get();
@@ -486,10 +481,10 @@ var p4 = p4 || {};
url: url, url: url,
data: data, data: data,
dataType: 'json', dataType: 'json',
beforeSend: function() { beforeSend: function () {
}, },
success: function(data) { success: function (data) {
if (!data.success) { if (!data.success) {
humane.error(data.message); humane.error(data.message);
} else { } else {
@@ -506,37 +501,35 @@ var p4 = p4 || {};
}); });
} }
function fix() function fix() {
{
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "../prod/WorkZone/attachStories/", url: "../prod/WorkZone/attachStories/",
data: {stories: p4.Results.Selection.get()}, data: {stories: p4.Results.Selection.get()},
dataType: "json", dataType: "json",
success: function(data) { success: function (data) {
humane.info(data.message); humane.info(data.message);
p4.WorkZone.refresh(); p4.WorkZone.refresh();
} }
}); });
} }
function unfix(link) function unfix(link) {
{
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: link, url: link,
dataType: "json", dataType: "json",
success: function(data) { success: function (data) {
humane.info(data.message); humane.info(data.message);
p4.WorkZone.refresh(); p4.WorkZone.refresh();
} }
}); });
} }
$(document).ready(function() { $(document).ready(function () {
activeBaskets(); activeBaskets();
$('a.story_unfix').live('click', function() { $('a.story_unfix').live('click', function () {
unfix($(this).attr('href')); unfix($(this).attr('href'));
return false; return false;
@@ -545,7 +538,7 @@ var p4 = p4 || {};
p4.WorkZone = { p4.WorkZone = {
'Selection': new Selectable($('#baskets'), {selector: '.CHIM'}), 'Selection': new Selectable($('#baskets'), {selector: '.CHIM'}),
'refresh': refreshBaskets, 'refresh': refreshBaskets,
'addElementToBasket': function(sbas_id, record_id, event, singleSelection) { 'addElementToBasket': function (sbas_id, record_id, event, singleSelection) {
singleSelection = !!singleSelection || false; singleSelection = !!singleSelection || false;
if ($('#baskets .SSTT.active').length === 1) { if ($('#baskets .SSTT.active').length === 1) {
@@ -555,26 +548,25 @@ var p4 = p4 || {};
} }
}, },
"removeElementFromBasket": WorkZoneElementRemover, "removeElementFromBasket": WorkZoneElementRemover,
'reloadCurrent': function() { 'reloadCurrent': function () {
var sstt = $('#baskets .content:visible'); var sstt = $('#baskets .content:visible');
if (sstt.length === 0) if (sstt.length === 0)
return; return;
getContent(sstt.prev()); getContent(sstt.prev());
}, },
'close': function() { 'close': function () {
var frame = $('#idFrameC'), that = this; var frame = $('#idFrameC'), that = this;
if (!frame.hasClass('closed')) if (!frame.hasClass('closed')) {
{
// hide tabs content // hide tabs content
var activeTabIdx = $('#idFrameC .tabs').tabs("option", "active"); var activeTabIdx = $('#idFrameC .tabs').tabs("option", "active");
$('#idFrameC .tabs > div:eq('+activeTabIdx+')').hide(); $('#idFrameC .tabs > div:eq(' + activeTabIdx + ')').hide();
frame.data('openwidth', frame.width()); frame.data('openwidth', frame.width());
frame.animate({width: 100}, frame.animate({width: 100},
300, 300,
'linear', 'linear',
function() { function () {
answerSizer(); answerSizer();
linearize(); linearize();
$('#answers').trigger('resize'); $('#answers').trigger('resize');
@@ -582,16 +574,15 @@ var p4 = p4 || {};
frame.addClass('closed'); frame.addClass('closed');
$('.escamote', frame).hide(); $('.escamote', frame).hide();
$('li.ui-tabs-selected', frame).removeClass('ui-tabs-selected'); $('li.ui-tabs-selected', frame).removeClass('ui-tabs-selected');
frame.unbind('click.escamote').bind('click.escamote', function() { frame.unbind('click.escamote').bind('click.escamote', function () {
that.open(); that.open();
}); });
} }
}, },
'open': function() { 'open': function () {
var frame = $('#idFrameC'); var frame = $('#idFrameC');
if (frame.hasClass('closed')) if (frame.hasClass('closed')) {
{
var width = frame.data('openwidth') ? frame.data('openwidth') : 300; var width = frame.data('openwidth') ? frame.data('openwidth') : 300;
frame.css({width: width}); frame.css({width: width});
answerSizer(); answerSizer();
@@ -601,7 +592,7 @@ var p4 = p4 || {};
frame.unbind('click.escamote'); frame.unbind('click.escamote');
// show tabs content // show tabs content
var activeTabIdx = $('#idFrameC .tabs').tabs("option", "active"); var activeTabIdx = $('#idFrameC .tabs').tabs("option", "active");
$('#idFrameC .tabs > div:eq('+activeTabIdx+')').show(); $('#idFrameC .tabs > div:eq(' + activeTabIdx + ')').show();
} }
} }
}; };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,13 @@
function publicator_reload_publicator() {
function publicator_reload_publicator()
{
var options = $('#dialog_publicator form[name="current_datas"]').serializeArray(); var options = $('#dialog_publicator form[name="current_datas"]').serializeArray();
var dialog = p4.Dialog.get(1); var dialog = p4.Dialog.get(1);
dialog.load('/prod/bridge/manager/', 'POST', options); dialog.load('/prod/bridge/manager/', 'POST', options);
} }
function init_publicator(datas) function init_publicator(datas) {
{
var dialog = p4.Dialog.Create({ var dialog = p4.Dialog.Create({
size:'Full', size: 'Full',
title:'Bridge', title: 'Bridge',
loading: false loading: false
}); });

View File

@@ -38,19 +38,19 @@ $(document).ready(function () {
configure_dash(); configure_dash();
bindEvents(); bindEvents();
$("a.select-all").bind("click", function(e) { $("a.select-all").bind("click", function (e) {
$("ul.multiselect .coll-checkbox", $(this).closest('.form2')).attr("checked", true); $("ul.multiselect .coll-checkbox", $(this).closest('.form2')).attr("checked", true);
}); });
$("a.deselect-all").bind("click", function(e) { $("a.deselect-all").bind("click", function (e) {
$("ul.multiselect .coll-checkbox", $(this).closest('.form2')).attr("checked", false); $("ul.multiselect .coll-checkbox", $(this).closest('.form2')).attr("checked", false);
}); });
$(".multiselect-group").toggle(function() { $(".multiselect-group").toggle(function () {
var $this = $(this); var $this = $(this);
var groupId = $this.data('group-id'); var groupId = $this.data('group-id');
$(".checkbox-" + groupId, $this.closest('.form2')).attr("checked", true); $(".checkbox-" + groupId, $this.closest('.form2')).attr("checked", true);
}, function() { }, function () {
var $this = $(this); var $this = $(this);
var groupId = $this.data('group-id'); var groupId = $this.data('group-id');
$(".checkbox-" + groupId, $this.closest('.form2')).attr("checked", false); $(".checkbox-" + groupId, $this.closest('.form2')).attr("checked", false);

View File

@@ -1,46 +1,39 @@
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// sprintf function for javascript // sprintf function for javascript
function sprintf() function sprintf() {
{ if (!arguments || arguments.length < 1 || !RegExp) {
if (!arguments || arguments.length < 1 || !RegExp)
{
return ''; return '';
} }
str = arguments[0]; str = arguments[0];
while((newstr = str.replace("\n", "\x01")) != str) while ((newstr = str.replace("\n", "\x01")) != str)
str = newstr; str = newstr;
// var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/; // var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
var re = new RegExp("^([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)$", "m"); var re = new RegExp("^([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)$", "m");
re["$*"] = true; re["$*"] = true;
var a = b = [], numSubstitutions = 0, numMatches = 0; var a = b = [], numSubstitutions = 0, numMatches = 0;
a = re.exec(str); a = re.exec(str);
while (a) while (a) {
{
var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4]; var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
var pPrecision = a[5], pType = a[6], rightPart = a[7]; numMatches++; var pPrecision = a[5], pType = a[6], rightPart = a[7];
numMatches++;
// alert("str:"+str + "\nl:"+leftpart + "\nr:"+rightPart); // alert("str:"+str + "\nl:"+leftpart + "\nr:"+rightPart);
if (pType == '%') if (pType == '%') {
{
subst = '%'; subst = '%';
} }
else else {
{
numSubstitutions++; numSubstitutions++;
if (numSubstitutions >= arguments.length) if (numSubstitutions >= arguments.length) {
{
alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\n' + 'for the number of substitution parameters in string (' + numSubstitutions + ' so far).'); alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\n' + 'for the number of substitution parameters in string (' + numSubstitutions + ' so far).');
} }
var param = arguments[numSubstitutions]; var param = arguments[numSubstitutions];
var pad = ''; var pad = '';
if (pPad && pPad.substr(0,1) == "'") if (pPad && pPad.substr(0, 1) == "'") {
{ pad = leftpart.substr(1, 1);
pad = leftpart.substr(1,1);
} }
else if (pPad) else if (pPad) {
{
pad = pPad; pad = pPad;
} }
var justifyRight = true; var justifyRight = true;
@@ -50,13 +43,11 @@ function sprintf()
if (pMinLength) if (pMinLength)
minLength = parseInt(pMinLength); minLength = parseInt(pMinLength);
var precision = -1; var precision = -1;
if (pPrecision && pType == 'f') if (pPrecision && pType == 'f') {
{
precision = parseInt(pPrecision.substring(1)); precision = parseInt(pPrecision.substring(1));
} }
var subst = param; var subst = param;
switch (pType) switch (pType) {
{
case 'b': case 'b':
subst = parseInt(param).toString(2); subst = parseInt(param).toString(2);
break; break;
@@ -64,7 +55,7 @@ function sprintf()
subst = String.fromCharCode(parseInt(param)); subst = String.fromCharCode(parseInt(param));
break; break;
case 'd': case 'd':
subst = parseInt(param)? parseInt(param) : 0; subst = parseInt(param) ? parseInt(param) : 0;
break; break;
case 'u': case 'u':
subst = Math.abs(param); subst = Math.abs(param);
@@ -89,20 +80,18 @@ function sprintf()
} }
var padLeft = minLength - subst.toString().length; var padLeft = minLength - subst.toString().length;
var padding; var padding;
if (padLeft > 0) if (padLeft > 0) {
{ var arrTmp = new Array(padLeft + 1);
var arrTmp = new Array(padLeft+1); padding = arrTmp.join(pad ? pad : " ");
padding = arrTmp.join(pad?pad:" ");
} }
else else {
{
padding = ""; padding = "";
} }
} }
str = leftpart + padding + subst + rightPart; str = leftpart + padding + subst + rightPart;
a = re.exec(str); a = re.exec(str);
} }
while((newstr = str.replace("\x01", "\n")) != str) while ((newstr = str.replace("\x01", "\n")) != str)
str = newstr; str = newstr;
return(str); return(str);
} }

View File

@@ -1,26 +1,21 @@
function loadXMLDoc(url, post_parms, asxml) {
function loadXMLDoc(url, post_parms, asxml) if (typeof(asxml) == "undefined")
{
if(typeof(asxml)=="undefined")
asxml = false; asxml = false;
out = null; out = null;
xmlhttp = null; xmlhttp = null;
// code for Mozilla, etc. // code for Mozilla, etc.
if (window.XMLHttpRequest) if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest(); xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject) else if (window.ActiveXObject)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) if (xmlhttp) {
{
// xmlhttp.onreadystatechange=state_Change // xmlhttp.onreadystatechange=state_Change
if(post_parms) if (post_parms) {
{
xmlhttp.open("POST", url, false); xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(post_parms); xmlhttp.send(post_parms);
} }
else else {
{
xmlhttp.open("GET", url, false); xmlhttp.open("GET", url, false);
xmlhttp.send(null); xmlhttp.send(null);
} }
@@ -30,25 +25,22 @@ function loadXMLDoc(url, post_parms, asxml)
} }
function showFound2(term, lterm, branch, depth) function showFound2(term, lterm, branch, depth) {
{
var c; var c;
var ret = 0; var ret = 0;
var thb = branch.firstChild.nextSibling.nextSibling; var thb = branch.firstChild.nextSibling.nextSibling;
// branch est un <DIV ID="THE_xxx"> // branch est un <DIV ID="THE_xxx">
if(thb) if (thb) {
for (c = thb.firstChild; c; c = c.nextSibling) // THE, les SY ou les TA
{ {
for(c=thb.firstChild; c; c=c.nextSibling) // THE, les SY ou les TA if (c.nodeName == "DIV")
{ ret += showFound2(term, lterm, c, depth + 1); // on descend uniquement les THE_yyy
if(c.nodeName=="DIV")
ret += showFound2(term, lterm, c, depth+1); // on descend uniquement les THE_yyy
} }
} }
if(branch.firstChild.nextSibling.nodeValue.substr(0, lterm)==term) if (branch.firstChild.nextSibling.nodeValue.substr(0, lterm) == term) {
{
ret = 1; ret = 1;
// alert(branch.firstChild.nextSibling.nodeValue + " : " + thb.id); // alert(branch.firstChild.nextSibling.nodeValue + " : " + thb.id);
} }
@@ -56,13 +48,11 @@ function showFound2(term, lterm, branch, depth)
// if(ret > 0) // if(ret > 0)
// if(depth > 0) // if(depth > 0)
// { // {
if(ret > 0) if (ret > 0) {
{
//eventObj.Src0.innerHTML = "+"; //eventObj.Src0.innerHTML = "+";
thb.className = "OB"; thb.className = "OB";
} }
else else {
{
//eventObj.Src0.innerHTML = "+"; //eventObj.Src0.innerHTML = "+";
thb.className = "ob"; thb.className = "ob";
} }
@@ -81,24 +71,20 @@ function showFound2(term, lterm, branch, depth)
return(ret); return(ret);
} }
function showAll(branch, depth) function showAll(branch, depth) {
{
depth = parseInt(depth); depth = parseInt(depth);
var c; var c;
for(c=branch.firstChild; c; c=c.nextSibling) for (c = branch.firstChild; c; c = c.nextSibling) {
{ if (c.nodeType == 1 && c.nodeName == "DIV") // 1=XML_ELEMENT_NODE
if(c.nodeType==1 && c.nodeName=="DIV") // 1=XML_ELEMENT_NODE showAll(c, depth + 1);
showAll(c, depth+1);
} }
if(depth > 0) if (depth > 0)
branch.style.display = ""; branch.style.display = "";
if(depth===0) if (depth === 0) {
{ document.getElementById("WT1").style.visibility = "hidden";
document.getElementById("WT1").style.visibility="hidden"; if (document.forms["fTh"].textT1.value !== "") {
if(document.forms["fTh"].textT1.value!=="")
{
// oups! le mot a changé durant le traitement, on recommence // oups! le mot a changé durant le traitement, on recommence
evt_kup_T1(); evt_kup_T1();
} }
@@ -106,33 +92,28 @@ function showAll(branch, depth)
} }
function scanTerms(inputName, zTerm, showhide) {
function scanTerms(inputName, zTerm, showhide)
{
showhide = !!showhide; showhide = !!showhide;
var lTerm = zTerm.length; var lTerm = zTerm.length;
var zTable = document.getElementById("L"+inputName); var zTable = document.getElementById("L" + inputName);
var zTr = zTable.childNodes; // TR's var zTr = zTable.childNodes; // TR's
var l = zTr.length; var l = zTr.length;
var found = null; var found = null;
for(var i=0; i<l; i++) for (var i = 0; i < l; i++) {
{
// if(renum) // if(renum)
// zTr[i].id = inputName+"_"+i // zTr[i].id = inputName+"_"+i
var t = zTr[i].firstChild.firstChild.nodeValue; var t = zTr[i].firstChild.firstChild.nodeValue;
// alert(i+" "+t); // alert(i+" "+t);
if(zTerm == t) if (zTerm == t)
found = zTr[i]; found = zTr[i];
if(showhide === true) if (showhide === true) {
{ if (lTerm == 0 || (t.substr(0, lTerm) == zTerm))
if(lTerm==0 || (t.substr(0, lTerm)==zTerm))
zTr[i].style.display = ""; zTr[i].style.display = "";
else else
zTr[i].style.display = "none"; zTr[i].style.display = "none";
} }
else else {
{
zTr[i].style.display = ""; zTr[i].style.display = "";
} }
} }
@@ -141,8 +122,8 @@ function scanTerms(inputName, zTerm, showhide)
function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY" function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
{ {
if(typeof(zTerm)=="undefined") // si pas de terme en argument, prendre dans la zone de saisie if (typeof(zTerm) == "undefined") // si pas de terme en argument, prendre dans la zone de saisie
zTerm = document.forms["fTh"]["text"+inputName].value; zTerm = document.forms["fTh"]["text" + inputName].value;
// alert(zTerm); // alert(zTerm);
// on cherche si le zTerm existe déjà // on cherche si le zTerm existe déjà
// var parent_id = selectedThesaurusItem.getAttribute("id"); // var parent_id = selectedThesaurusItem.getAttribute("id");
@@ -150,17 +131,14 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
// found = scanTerms(inputName, true, false); // renuméroter et tout afficher // found = scanTerms(inputName, true, false); // renuméroter et tout afficher
var found = scanTerms(inputName, zTerm, false); // tout afficher var found = scanTerms(inputName, zTerm, false); // tout afficher
if(!found) if (!found) {
{
// on cherche la div "thb" si elle existe // on cherche la div "thb" si elle existe
var thb, thRef; var thb, thRef;
for(thb=selectedThesaurusItem.firstChild; thb; thb=thb.nextSibling) for (thb = selectedThesaurusItem.firstChild; thb; thb = thb.nextSibling) {
{ if (thb.nodeType == 1 && thb.tagName == "DIV" && thb.id.substr(0, 4) == "THB_")
if(thb.nodeType==1 && thb.tagName=="DIV" && thb.id.substr(0,4)=="THB_")
break; break;
} }
if(!thb) if (!thb) {
{
// on ajoute le premier fils ... // on ajoute le premier fils ...
// ... on crée le +/- en face du terme // ... on crée le +/- en face du terme
selectedThesaurusItem.firstChild.className = "tri"; selectedThesaurusItem.firstChild.className = "tri";
@@ -174,27 +152,25 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
thb.id = "THB_" + selectedThesaurusItem.id.substr(4); thb.id = "THB_" + selectedThesaurusItem.id.substr(4);
} }
if(inputName=="TS") // on ajoute un terme spécifique if (inputName == "TS") // on ajoute un terme spécifique
{ {
// un id pour le nouveau terme // un id pour le nouveau terme
var nextid = parseInt(selectedThesaurusItem.getAttribute("nextid")); var nextid = parseInt(selectedThesaurusItem.getAttribute("nextid"));
// selectedThesaurusItem.nextid = "" + (nextid+1); // selectedThesaurusItem.nextid = "" + (nextid+1);
selectedThesaurusItem.setAttribute("nextid", "" + (nextid+1)); selectedThesaurusItem.setAttribute("nextid", "" + (nextid + 1));
// on ajoute le nouveau terme dans le thb : on crée une nouvelle div // on ajoute le nouveau terme dans le thb : on crée une nouvelle div
var div = document.createElement("DIV"); var div = document.createElement("DIV");
div.className = "s_"; div.className = "s_";
if(selectedThesaurusItem.id == "THE_") if (selectedThesaurusItem.id == "THE_")
div.id = "THE_" + nextid; div.id = "THE_" + nextid;
else else
div.id = selectedThesaurusItem.id + "." + nextid; div.id = selectedThesaurusItem.id + "." + nextid;
if(typeof(oldid)=="undefined") if (typeof(oldid) == "undefined") {
{
// div.oldid = "?"; // permettra de repérer les nouveaux termes // div.oldid = "?"; // permettra de repérer les nouveaux termes
div.setAttribute("oldid", "?"); // permettra de repérer les nouveaux termes div.setAttribute("oldid", "?"); // permettra de repérer les nouveaux termes
} }
else else {
{
// div.oldid = oldid; // le terme a provient des termes candidats // div.oldid = oldid; // le terme a provient des termes candidats
div.setAttribute("oldid", oldid); // le terme a provient des termes candidats div.setAttribute("oldid", oldid); // le terme a provient des termes candidats
} }
@@ -211,7 +187,7 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
p.className = inputName.toLowerCase(); // ta ou sy p.className = inputName.toLowerCase(); // ta ou sy
p.appendChild(document.createTextNode(zTerm)); p.appendChild(document.createTextNode(zTerm));
thRef = thb.appendChild(p); thRef = thb.appendChild(p);
nextid = document.getElementById("L"+inputName).nextid++; nextid = document.getElementById("L" + inputName).nextid++;
} }
// on ajoute aussi à la liste des termes // on ajoute aussi à la liste des termes
@@ -222,7 +198,7 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
tr.thRef = thRef; // lien du nouveau terme de la liste vers le thesaurus tr.thRef = thRef; // lien du nouveau terme de la liste vers le thesaurus
document.forms["fTh"]["text"+inputName].value = ""; document.forms["fTh"]["text" + inputName].value = "";
termChanged = true; termChanged = true;
@@ -235,8 +211,7 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
evt_kup(inputName); evt_kup(inputName);
} }
function dirty() function dirty() {
{
thesaurusChanged = true; thesaurusChanged = true;
document.getElementById("saveButton").style.display = ""; document.getElementById("saveButton").style.display = "";
} }
@@ -363,60 +338,50 @@ function dirty()
} }
*/ */
// supprime un terme et tous ses fils (deplace 'e plat') dans '(deleted)' // supprime un terme et tous ses fils (deplace 'e plat') dans '(deleted)'
function deleteBranch(the, thb_deleted) function deleteBranch(the, thb_deleted) {
{ if (the.id.substr(0, 4) == "THE_") {
if(the.id.substr(0,4)=="THE_") var d = thb_deleted.appendChild(document.createElement("DIV"));
{
var d = thb_deleted.appendChild(document.createElement("DIV") );
d.className = "s_ R_"; d.className = "s_ R_";
d.id = "TCE_R" + (thb_deleted.parentNode.id.substr(1)) + "." + (thb_deleted.parentNode.getAttribute("nextid")); d.id = "TCE_R" + (thb_deleted.parentNode.id.substr(1)) + "." + (thb_deleted.parentNode.getAttribute("nextid"));
thb_deleted.parentNode.setAttribute("nextid", parseInt(thb_deleted.parentNode.getAttribute("nextid")+1) ); thb_deleted.parentNode.setAttribute("nextid", parseInt(thb_deleted.parentNode.getAttribute("nextid") + 1));
d.appendChild(the.firstChild.nextSibling.cloneNode(false) ); d.appendChild(the.firstChild.nextSibling.cloneNode(false));
d.setAttribute("oldid", the.oldid ? the.oldid : the.id.substr(4) ); d.setAttribute("oldid", the.oldid ? the.oldid : the.id.substr(4));
if(the.firstChild.nextSibling.nextSibling) if (the.firstChild.nextSibling.nextSibling) {
{ for (var the = the.firstChild.nextSibling.nextSibling.firstChild; the; the = the.nextSibling) {
for(var the=the.firstChild.nextSibling.nextSibling.firstChild; the; the=the.nextSibling)
{
deleteBranch(the, thb_deleted); deleteBranch(the, thb_deleted);
} }
} }
} }
} }
function alertNode(n, msg) function alertNode(n, msg) {
{ if (typeof(msg) == "undefined")
if(typeof(msg)=="undefined")
msg = ""; msg = "";
if(n) if (n) {
{ if (n.nodeType == 1) {
if(n.nodeType==1) alert(msg + " : <" + n.nodeName + " id='" + n.id + "'>");
{
alert(msg + " : <"+n.nodeName+" id='"+n.id+"'>");
} }
else else {
{ alert(msg + " : nodeType=" + n.nodeType);
alert(msg + " : nodeType="+n.nodeType);
} }
} }
else else {
{
alert(msg + " : NULL"); alert(msg + " : NULL");
} }
} }
function appendTerm(inputName, new_term, id) function appendTerm(inputName, new_term, id) {
{
var tr = document.createElement("TR"); var tr = document.createElement("TR");
tr.id = inputName + "_"+id; tr.id = inputName + "_" + id;
tr.className = "s_"; tr.className = "s_";
var td = tr.appendChild(document.createElement("TD")); var td = tr.appendChild(document.createElement("TD"));
td.appendChild(document.createTextNode(new_term)); td.appendChild(document.createTextNode(new_term));
td = tr.appendChild(document.createElement("TD")); td = tr.appendChild(document.createElement("TD"));
td.innerHTML = "<img id='"+inputName+"f_"+id+"' src='./images/noflag.gif' />"; td.innerHTML = "<img id='" + inputName + "f_" + id + "' src='./images/noflag.gif' />";
td = tr.appendChild(document.createElement("TD")); td = tr.appendChild(document.createElement("TD"));
td.appendChild(document.createTextNode(" ")); td.appendChild(document.createTextNode(" "));
var zTable = document.getElementById("L"+inputName); var zTable = document.getElementById("L" + inputName);
return(zTable.appendChild(tr)); return(zTable.appendChild(tr));
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,27 +1,22 @@
function loadXMLDoc(url, post_parms, asxml) {
function loadXMLDoc(url, post_parms, asxml) if (typeof(asxml) == "undefined")
{
if(typeof(asxml)=="undefined")
asxml = false; asxml = false;
out = null; out = null;
xmlhttp = null; xmlhttp = null;
// code for Mozilla, etc. // code for Mozilla, etc.
if (window.XMLHttpRequest) if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest(); xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject) else if (window.ActiveXObject)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) if (xmlhttp) {
{
// xmlhttp.onreadystatechange=state_Change // xmlhttp.onreadystatechange=state_Change
if(post_parms) if (post_parms) {
{
xmlhttp.open("POST", url, false); xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(post_parms); xmlhttp.send(post_parms);
} }
else else {
{
xmlhttp.open("GET", url, false); xmlhttp.open("GET", url, false);
xmlhttp.send(null); xmlhttp.send(null);
} }