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

View File

@@ -1,145 +1,136 @@
(function( $ ){
(function ($) {
var methods = {
init : function( options ) {
init: function (options) {
var settings = {
'zoomable' : false,
'display_full_screen' : false
'zoomable': false,
'display_full_screen': false
};
return this.each(function() {
return this.each(function () {
var $this = $(this), data = $(this).data('image_enhance');
if ( ! data )
{
if ( options ) {
$.extend( settings, options );
if (!data) {
if (options) {
$.extend(settings, options);
}
var wrapper = $('.thumb_wrapper', $(this));
var $image =$('img', $this);
var $image = $('img', $this);
wrapper.css('position','relative');
wrapper.css('position', 'relative');
reset_position($this);
if(settings.display_full_screen)
{
if (settings.display_full_screen) {
$image.parent()
.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_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()
.bind('mouseover.image_enhance', function(){
.bind('mouseover.image_enhance', function () {
$titlebar.stop().show().animate({
'height':28
'height': 28
}, 150);
})
.bind('mouseout.image_enhance', function(){
.bind('mouseout.image_enhance', function () {
$titlebar.stop().animate({
'height':0
}, 150, function(){
'height': 0
}, 150, function () {
$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\
\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>');
var $theatre = $('.image_enhance_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');
}
else
{
if($theatre_img.hasClass('zoomed'))
else {
if ($theatre_img.hasClass('zoomed'))
return;
}
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');
$('.closer', $theatre).bind('click.image_enhance', function(){
$('.closer', $theatre).bind('click.image_enhance', function () {
$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');
$('img', $theatre).disableSelection();
});
}
if(settings.zoomable)
{
if(typeof $image.draggable !== 'function' && window.console)
if (settings.zoomable) {
if (typeof $image.draggable !== 'function' && window.console)
console.error('zoomable require jquery UI\'s draggable');
if($image.attr('ondragstart'))
{
if ($image.attr('ondragstart')) {
$image.removeAttr('ondragstart');
}
$image.draggable();
$image.css({
'max-width':'none',
'max-height':'none'
'max-width': 'none',
'max-height': 'none'
});
var image_width = parseInt($('input[name="width"]', $this).val());
var image_height = parseInt($('input[name="height"]', $this).val());
var ratio = image_width / image_height;
$this.bind('mousewheel',function(event, delta){
$this.bind('mousewheel',function (event, delta) {
$image.addClass('zoomed');
if(delta > 0)
{
if (delta > 0) {
event.stopPropagation();
zoomPreview(true, ratio, $image, $(this));
}
else
{
else {
event.stopPropagation();
zoomPreview(false, ratio, $image, $(this));
}
return false;
}).bind('dblclick', function(event){
}).bind('dblclick', function (event) {
reset_position($this);
});
}
$(this).data('image_enhance', {
width:image_width,
height:image_height
width: image_width,
height: image_height
});
}
});
},
destroy : function( ) {
return this.each(function() {
destroy: function () {
return this.each(function () {
$(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)
{
if($img.length === 0)
function zoomPreview(bool, ratio, $img, $container) {
if ($img.length === 0)
return;
var t1 = parseInt($img.css('top'));
@@ -147,19 +138,17 @@
var w1 = $img.width();
var h1 = $img.height();
var w2,t2;
var w2, t2;
if(bool)
{
if((w1 * 1.08) < 32767) {
if (bool) {
if ((w1 * 1.08) < 32767) {
w2 = w1 * 1.08;
} else {
w2 = w1;
}
}
else
{
if((w1 / 1.08) > 20) {
else {
if ((w1 / 1.08) > 20) {
w2 = w1 / 1.08;
} else {
w2 = w1;
@@ -171,11 +160,11 @@
h2 = Math.round(w2 / ratio);
w2 = Math.round(w2);
t2 = Math.round(t1 - (h2 - h1) / 2)+'px';
var l2 = Math.round(l1 - (w2 - w1) / 2)+'px';
t2 = Math.round(t1 - (h2 - h1) / 2) + 'px';
var l2 = Math.round(l1 - (w2 - w1) / 2) + 'px';
var wPreview = $container.width()/2;
var hPreview = $container.height()/2;
var wPreview = $container.width() / 2;
var hPreview = $container.height() / 2;
var nt = Math.round((h2 / h1) * (t1 - hPreview) + hPreview);
var nl = Math.round(((w2 / w1) * (l1 - wPreview)) + wPreview);
@@ -186,64 +175,60 @@
}).width(w2).height(h2);
}
function calculate_sizes(window_width, window_height,image_width, image_height, border)
{
if(typeof border !== 'number')
function calculate_sizes(window_width, window_height, image_width, image_height, border) {
if (typeof border !== 'number')
border = 0;
var width, height;
var ratio_display = window_width / window_height;
var ratio_image = image_width / image_height;
if(ratio_image > ratio_display)
{
if (ratio_image > ratio_display) {
width = window_width - border;
height = Math.round(width / ratio_image);
}
else
{
else {
height = window_height - border;
width = Math.round(height * ratio_image);
}
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 {
top:top,
left:left,
width:width,
height:height
top: top,
left: left,
width: width,
height: height
};
}
function reset_position($this)
{
function reset_position($this) {
var display_width = $this.width();
var display_height = $this.height();
var image_width = parseInt($('input[name="width"]', $this).val());
var image_height = parseInt($('input[name="height"]', $this).val());
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 left = Math.round((display_width - datas.width) / 2)+'px';
var top = Math.round((display_height - datas.height) / 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;
}
$.fn.image_enhance = function(method) {
$.fn.image_enhance = function (method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} 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;
if(event.ctrlKey)
if (event.ctrlKey)
return true;
if(event.metaKey) // apple key opera
if (event.metaKey) // apple key opera
return true;
if(event.keyCode == '17') // apple key opera
if (event.keyCode == '17') // apple key opera
return true;
if(event.keyCode == '224') // apple key mozilla
if (event.keyCode == '224') // apple key mozilla
return true;
if(event.keyCode == '91') // apple key safari
if (event.keyCode == '91') // apple key safari
return true;
return false;
}
function is_shift_key(event)
{
if(event.shiftKey)
function is_shift_key(event) {
if (event.shiftKey)
return true;
return false;
}

View File

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

View File

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

View File

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

View File

@@ -13,7 +13,7 @@
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
(function ($) {
// the tooltip element
var helper = {},
@@ -28,15 +28,15 @@
$.tooltip = {
blocked: false,
ajaxTimeout : false,
ajaxRequest : false,
ajaxEvent : false,
ajaxTimeout: false,
ajaxRequest: false,
ajaxEvent: false,
current: null,
visible: false,
defaults: {
delay: 700,
fixable:false,
fixableIndex:100,
fixable: false,
fixableIndex: 100,
fade: true,
showURL: true,
outside: true,
@@ -45,27 +45,26 @@
left: 15,
id: "tooltip"
},
block: function() {
block: function () {
$.tooltip.blocked = !$.tooltip.blocked;
},
delayAjax : function(a,b,c)
{
delayAjax: function (a, b, c) {
var options_serial = p4.tot_options;
var query = p4.tot_query;
var datas = {
options_serial:options_serial,
query:query
options_serial: options_serial,
query: query
};
$.tooltip.ajaxRequest = $.ajax({
url: $.tooltip.current.tooltipSrc,
type:'post',
data:datas,
success: function(data) {
type: 'post',
data: datas,
success: function (data) {
title = data;
positioning($.tooltip.ajaxEvent);
},
"error":function(){
"error": function () {
return;
}
});
@@ -73,10 +72,10 @@
};
$.fn.extend({
tooltip: function(settings) {
tooltip: function (settings) {
settings = $.extend({}, $.tooltip.defaults, settings);
createHelper(settings);
return this.each(function() {
return this.each(function () {
$.data(this, "tooltip", settings);
// copy tooltip into its own expando and remove the title
this.tooltipText = $(this).attr('title');
@@ -94,7 +93,7 @@
.mouseout(hide)
.mousedown(fix);
},
fixPNG: IE ? function() {
fixPNG: IE ? function () {
return this.each(function () {
var image = $(this).css('backgroundImage');
if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
@@ -109,32 +108,32 @@
});
}
});
} : function() {
} : function () {
return this;
},
unfixPNG: IE ? function() {
unfixPNG: IE ? function () {
return this.each(function () {
$(this).css({
'filter': '',
backgroundImage: ''
});
});
} : function() {
} : function () {
return this;
},
hideWhenEmpty: function() {
return this.each(function() {
hideWhenEmpty: function () {
return this.each(function () {
$(this)[ $(this).html() ? "show" : "hide" ]();
});
},
url: function() {
url: function () {
return this.attr('href') || this.attr('src');
}
});
function createHelper(settings) {
// there can be only one tooltip helper
if( helper.parent )
if (helper.parent)
return;
// create the helper, h3 for title, div for url
helper.parent = $('<div id="' + settings.id + '"><div class="body"></div></div>')
@@ -144,7 +143,7 @@
.hide();
// apply bgiframe if available
if ( $.fn.bgiframe )
if ($.fn.bgiframe)
helper.parent.bgiframe();
// save references to title and url elements
@@ -160,11 +159,11 @@
// main event handler to start showing tooltips
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;
// show helper, either with timeout or on instant
if( settings(this).delay )
if (settings(this).delay)
tID = setTimeout(visible, settings(this).delay);
else
visible();
@@ -181,12 +180,12 @@
// save elements title before the tooltip is displayed
function save(event) {
// 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.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;
// save current
@@ -194,28 +193,26 @@
title = this.tooltipText;
// if element has href or src, add and show it, otherwise hide it
if( settings(this).showURL && $(this).url() )
helper.url.html( $(this).url().replace('http://', '') ).show();
if (settings(this).showURL && $(this).url())
helper.url.html($(this).url().replace('http://', '')).show();
else
helper.url.hide();
// add an optional class for this tip
// helper.parent.addClass(settings(this).extraClass);
if(this.ajaxLoad)
{
if (this.ajaxLoad) {
clearTimeout($.tooltip.ajaxTimeout);
$.tooltip.ajaxTimeout = setTimeout("$.tooltip.delayAjax()", 300);
$.tooltip.ajaxEvent = event;
}
else
{
title = '<div class="popover" style="display:block;position:relative;">'+
'<div class="arrow"></div>'+
'<div class="popover-inner" style="width:auto;">'+
'<div class="popover-content">'+
title+
'</div>'+
'</div>'+
else {
title = '<div class="popover" style="display:block;position:relative;">' +
'<div class="arrow"></div>' +
'<div class="popover-inner" style="width:auto;">' +
'<div class="popover-content">' +
title +
'</div>' +
'</div>' +
'</div>';
positioning.apply(this, arguments);
@@ -224,16 +221,14 @@
}
function positioning(event)
{
function positioning(event) {
helper.body.html(title);
helper.body.show();
$this = $.tooltip.current;
// fix PNG background for IE
if (settings($this).fixPNG )
if (settings($this).fixPNG)
helper.parent.fixPNG();
if(settings($this).outside)
{
if (settings($this).outside) {
var width = 'auto';
var height = 'auto';
var ratio = 1;
@@ -245,53 +240,52 @@
resizeImgTips = true;
width = parseInt($imgTips[0].style.width);
height = parseInt($imgTips[0].style.height);
ratio = width/height;
$imgTips.css({top:'0px',left:'0px'});
ratio = width / height;
$imgTips.css({top: '0px', left: '0px'});
}
if ($videoTips[0] && $('#' + settings($.tooltip.current).id + ' .noToolTipResize').length === 0) {
resizeVideoTips = true;
width = parseInt($videoTips.attr('width'));
height = parseInt($videoTips.attr('height'));
ratio = width/height;
$videoTips.css({top:'0px',left:'0px'});
ratio = width / height;
$videoTips.css({top: '0px', left: '0px'});
}
var v = viewport(),
h = helper.parent;
helper.parent.css({
width:width,
top:0,
left:0,
visibility:'hidden',
width: width,
top: 0,
left: 0,
visibility: 'hidden',
// visibility:'visible',
display:'block',
height:height
display: 'block',
height: height
});
$(h).width($(h).width());
width = ($(h).width()>(v.x-40))?(v.x-40):$(h).width();
height = ($(h).height()>(v.y-40))?(v.y-40):$(h).height();
width = ($(h).width() > (v.x - 40)) ? (v.x - 40) : $(h).width();
height = ($(h).height() > (v.y - 40)) ? (v.y - 40) : $(h).height();
// $('#' + 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;
}
$(h).css({
width:width,
height:height
width: width,
height: height
});
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();
var ratioSurfaceH;
var ratioSurfaceV, wiH,wiV,heH,heV;
var ratioImage = $(h).width()/$(h).height();
var ratioSurfaceV, wiH, wiV, heH, heV;
var ratioImage = $(h).width() / $(h).height();
//position de l'image
if ($(event.target).offset().left > (v.x - $(event.target).offset().left - $(event.target).width())) {
@@ -325,66 +319,58 @@
//correction par ratio
if (resizeImgTips && $('#' + settings($.tooltip.current).id + ' .imgTips')[0]) {
if(ratioSurfaceH > ratioImage)
{
horS = v.y * ratioImage*v.y;
if (ratioSurfaceH > ratioImage) {
horS = v.y * ratioImage * v.y;
}
else
{
horS = wiH * wiH/ratioImage;
else {
horS = wiH * wiH / ratioImage;
}
if(ratioSurfaceV > ratioImage)
{
vertS = heV * ratioImage*heV;
if (ratioSurfaceV > ratioImage) {
vertS = heV * ratioImage * heV;
}
else
{
vertS = v.x * v.x/ratioImage;
else {
vertS = v.x * v.x / ratioImage;
}
}
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 zW = $(h).width();
zH = $(h).height();
var ETOT = $(event.target).offset().top;
var ETH = $(event.target).height();
left = (zL - zW/2)<20?20:(((zL + zW/2+20)>v.x)?(v.x-zW-20):(zL -zW/2));
switch(vert)
{
left = (zL - zW / 2) < 20 ? 20 : (((zL + zW / 2 + 20) > v.x) ? (v.x - zW - 20) : (zL - zW / 2));
switch (vert) {
case 'haut':
height = (zH>(ETOT-40))?(ETOT-40):zH;
top = ETOT - height-20;
height = (zH > (ETOT - 40)) ? (ETOT - 40) : zH;
top = ETOT - height - 20;
break;
case 'bas':
height = ((v.y-ETH-ETOT-40)>zH)?zH:(v.y-ETH-ETOT-40);
top = ETOT +ETH+20;
height = ((v.y - ETH - ETOT - 40) > zH) ? zH : (v.y - ETH - ETOT - 40);
top = ETOT + ETH + 20;
break;
default:
break;
}
}
else
{
else {
// height = ($(h).height()>(v.y-40))?(v.y-40):$(h).height();
zH = $(h).height();
var zT = event.pageY;
var EOTL = $(event.target).offset().left;
var ETW = $(event.target).width();
var zw = $(h).width();
top = (zT - zH/2)<20?20:(((zT + zH/2+20)>v.y)?(v.y-zH-20):(zT - zH/2));
switch(hor)
{
top = (zT - zH / 2) < 20 ? 20 : (((zT + zH / 2 + 20) > v.y) ? (v.y - zH - 20) : (zT - zH / 2));
switch (hor) {
case 'gauche':
width = (zw>(EOTL-40))?(EOTL-40):zw;
left = EOTL - width-20;
width = (zw > (EOTL - 40)) ? (EOTL - 40) : zw;
left = EOTL - width - 20;
break;
case 'droite':
width = ((v.x-ETW-EOTL-40)>zw)?zw:(v.x-ETW-EOTL-40);
left = EOTL +ETW+20;
width = ((v.x - ETW - EOTL - 40) > zw) ? zw : (v.x - ETW - EOTL - 40);
left = EOTL + ETW + 20;
break;
default:
break;
@@ -401,9 +387,9 @@
//si ya une image on re-ajuste au ratio
if (resizeImgTips && $('#' + settings($.tooltip.current).id + ' .imgTips')[0]) {
if(width == 'auto')
if (width == 'auto')
width = $('#' + settings($.tooltip.current).id).width();
if(height == 'auto')
if (height == 'auto')
height = $('#' + settings($.tooltip.current).id).height();
if (ratio > 1) {
var nh = width / ratio;
@@ -421,16 +407,13 @@
}
width = nw;
}
}else
{
if(vertS < horS)
{
} else {
if (vertS < horS) {
height = 'auto';
}
}
if(resizeImgTips)
{
if (resizeImgTips) {
var factor = Math.min((width - 45) / width, (height - 75) / height);
var imgWidth = Math.round(width * 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 imgWidth = Math.round(width * factor);
var imgHeight = Math.round(height * factor);
@@ -488,25 +470,23 @@
update();
}
function fix(event)
{
if(!settings(this).fixable)
{
function fix(event) {
if (!settings(this).fixable) {
hide(event);
return;
}
event.cancelBubble = true;
if(event.stopPropagation)
if (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.blocked = true;
}
function visible(){
function visible() {
$.tooltip.visible = true;
helper.parent.css({
visibility:'visible'
visibility: 'visible'
});
}
@@ -517,7 +497,7 @@
*/
function update(event) {
if($.tooltip.blocked)
if ($.tooltip.blocked)
return;
if (event && event.target.tagName == "OPTION") {
@@ -525,12 +505,12 @@
}
// 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);
}
// if no current element is available, remove this listener
if( $.tooltip.current === null ) {
if ($.tooltip.current === null) {
$(document.body).unbind('mousemove', update);
return;
}
@@ -538,8 +518,7 @@
// remove position helper classes
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 top = helper.parent[0].offsetTop;
helper.parent.width('auto');
@@ -548,7 +527,7 @@
// position the helper 15 pixel to bottom right, starting from mouse position
left = event.pageX + settings($.tooltip.current).left;
top = event.pageY + settings($.tooltip.current).top;
var right='auto';
var right = 'auto';
if (settings($.tooltip.current).positionLeft) {
right = $(window).width() - left;
left = 'auto';
@@ -590,27 +569,26 @@
}
// hide helper and restore added classes and the title
function hide(event)
{
if($.tooltip.blocked || !$.tooltip.current)
function hide(event) {
if ($.tooltip.blocked || !$.tooltip.current)
return;
// clear timeout if possible
if(tID)
if (tID)
clearTimeout(tID);
// no more current element
$.tooltip.visible = false;
var tsettings = settings($.tooltip.current);
clearTimeout($.tooltip.ajaxTimeout);
if($.tooltip.ajaxRequest && $.tooltip.ajaxRequest.abort)
{
if ($.tooltip.ajaxRequest && $.tooltip.ajaxRequest.abort) {
$.tooltip.ajaxRequest.abort();
}
helper.body.empty();
$.tooltip.current = null;
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 (helper.parent.is(':animated'))
helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
@@ -619,14 +597,13 @@
} else
complete();
if( tsettings.fixPNG )
if (tsettings.fixPNG)
helper.parent.unfixPNG();
}
})(jQuery);
function unfix_tooltip()
{
function unfix_tooltip() {
$.tooltip.blocked = false;
$.tooltip.visible = false;
$.tooltip.current = null;
@@ -636,9 +613,8 @@ function unfix_tooltip()
}
$(document).bind('keydown', function(event){
if(event.keyCode == 27 && $.tooltip.blocked === true)
{
$(document).bind('keydown', function (event) {
if (event.keyCode == 27 && $.tooltip.blocked === true) {
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;
if(VocabularyId === '')
if (VocabularyId === '')
VocabularyId = null;
return VocabularyId;
}
var recordFieldValue = function(meta_id, value, VocabularyId) {
var recordFieldValue = function (meta_id, value, VocabularyId) {
VocabularyId = checkVocabId(VocabularyId);
this.datas = {
meta_id:meta_id,
value:value,
VocabularyId:VocabularyId
meta_id: meta_id,
value: value,
VocabularyId: VocabularyId
};
var $this = this;
};
recordFieldValue.prototype = {
getValue : function() {
getValue: function () {
return this.datas.value;
},
getMetaId : function() {
getMetaId: function () {
return this.datas.meta_id;
},
getVocabularyId : function() {
getVocabularyId: function () {
return this.datas.VocabularyId;
},
setValue : function(value, VocabularyId) {
setValue: function (value, VocabularyId) {
this.datas.value = value;
this.datas.VocabularyId = checkVocabId(VocabularyId);
return this;
},
remove : function() {
remove: function () {
this.datas.value = '';
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 = {
multi : false,
required : false,
readonly : false,
maxLength : null,
minLength : null,
type : 'string',
separator : null,
vocabularyControl : null,
vocabularyRestricted : false
multi: false,
required: false,
readonly: false,
maxLength: null,
minLength: null,
type: 'string',
separator: null,
vocabularyControl: null,
vocabularyRestricted: false
},
options = (typeof options == 'object') ? options : {};
if(isNaN(meta_struct_id))
{
if (isNaN(meta_struct_id)) {
throw 'meta_struct_id should be a number';
}
@@ -74,93 +71,83 @@
this.meta_struct_id = meta_struct_id;
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 = ';';
}
};
databoxField.prototype = {
getMetaStructId : function() {
getMetaStructId: function () {
return this.meta_struct_id;
},
getName : function() {
getName: function () {
return this.name;
},
getLabel : function() {
getLabel: function () {
return this.label;
},
isMulti : function() {
isMulti: function () {
return this.options.multi;
},
isRequired : function() {
isRequired: function () {
return this.options.required;
},
isReadonly : function() {
isReadonly: function () {
return this.options.readonly;
},
getMaxLength : function() {
getMaxLength: function () {
return this.options.maxLength;
},
getMinLength : function() {
getMinLength: function () {
return this.options.minLength;
},
getType : function() {
getType: function () {
return this.options.type;
},
getSeparator : function() {
getSeparator: function () {
return this.options.separator;
}
};
var recordField = function(databoxField, arrayValues) {
var recordField = function (databoxField, arrayValues) {
this.databoxField = databoxField;
this.options = {
dirty : false
dirty: false
};
this.datas = new Array();
if(arrayValues instanceof Array)
{
if(arrayValues.length > 1 && !databoxField.isMulti())
if (arrayValues instanceof Array) {
if (arrayValues.length > 1 && !databoxField.isMulti())
throw 'You can not add multiple values to a non multi field ' + databoxField.getName();
var first = true;
for(v in arrayValues)
{
if(typeof arrayValues[v] !== 'object')
{
if(window.console)
{
for (v in arrayValues) {
if (typeof arrayValues[v] !== 'object') {
if (window.console) {
console.error('Trying to add a non-recordFieldValue to the field...');
}
continue;
}
if(isNaN(arrayValues[v].getMetaId()))
{
if(window.console)
{
if (isNaN(arrayValues[v].getMetaId())) {
if (window.console) {
console.error('Trying to add a recordFieldValue without metaId...');
}
continue;
}
if(!first && this.options.multi === false)
{
if(window.console)
{
if (!first && this.options.multi === false) {
if (window.console) {
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]);
}
@@ -172,101 +159,81 @@
var $this = this;
}
recordField.prototype = {
getName : function() {
getName: function () {
return this.databoxField.getName();
},
getMetaStructId : function() {
getMetaStructId: function () {
return this.databoxField.getMetaStructId();
},
isMulti : function() {
isMulti: function () {
return this.databoxField.isMulti();
},
isRequired : function() {
isRequired: function () {
return this.databoxField.isRequired();
},
isDirty : function() {
isDirty: function () {
return this.options.dirty;
},
addValue : function(value, merge, VocabularyId) {
addValue: function (value, merge, VocabularyId) {
VocabularyId = checkVocabId(VocabularyId);
merge = !!merge;
if(this.databoxField.isReadonly())
{
if(window.console)
{
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
return;
}
if(window.console)
{
console.log('adding value ',value,' vocId : ', VocabularyId , ' ; merge is ',merge);
if (window.console) {
console.log('adding value ', value, ' vocId : ', VocabularyId, ' ; merge is ', merge);
}
if(this.isMulti())
{
if(!this.hasValue(value, VocabularyId))
{
if(window.console)
{
console.log('adding new multi value ',value);
if (this.isMulti()) {
if (!this.hasValue(value, VocabularyId)) {
if (window.console) {
console.log('adding new multi value ', value);
}
this.datas.push(new recordFieldValue(null, value, VocabularyId));
this.options.dirty = true;
}
else
{
if(window.console)
{
console.log('already have ',value);
else {
if (window.console) {
console.log('already have ', value);
}
}
}
else
{
if(merge === true && this.isEmpty() === false && VocabularyId === null)
{
if(window.console)
{
console.log('Merging value ',value);
else {
if (merge === true && this.isEmpty() === false && VocabularyId === null) {
if (window.console) {
console.log('Merging value ', value);
}
this.datas[0].setValue(this.datas[0].getValue() + ' ' + value, VocabularyId);
this.options.dirty = true;
}
else
{
if(merge === true && this.isEmpty() === false && VocabularyId !== null)
{
if(window.console)
{
else {
if (merge === true && this.isEmpty() === false && VocabularyId !== null) {
if (window.console) {
console.error('Cannot merge vocabularies');
}
this.datas[0].setValue(value, VocabularyId);
}
else
{
else {
if(!this.hasValue(value, VocabularyId))
{
if(this.datas.length === 0)
{
if(window.console)
{
console.log('Adding new value ',value);
if (!this.hasValue(value, VocabularyId)) {
if (this.datas.length === 0) {
if (window.console) {
console.log('Adding new value ', value);
}
this.datas.push(new recordFieldValue(null, value, VocabularyId));
}
else
{
if(window.console)
{
console.log('Updating value ',value);
else {
if (window.console) {
console.log('Updating value ', value);
}
this.datas[0].setValue(value, VocabularyId);
}
@@ -278,35 +245,27 @@
return this;
},
hasValue : function(value, VocabularyId) {
hasValue: function (value, VocabularyId) {
if(typeof value === 'undefined')
{
if(window.console)
{
if (typeof value === 'undefined') {
if (window.console) {
console.error('Trying to check the presence of an undefined value');
}
}
VocabularyId = checkVocabId(VocabularyId);
for(d in this.datas)
{
if(VocabularyId !== null)
{
if(this.datas[d].getVocabularyId() === VocabularyId)
{
if(window.console)
{
for (d in this.datas) {
if (VocabularyId !== null) {
if (this.datas[d].getVocabularyId() === VocabularyId) {
if (window.console) {
console.log('already got the vocab ID');
}
return true;
}
}
else if(this.datas[d].getVocabularyId() === null && this.datas[d].getValue() == value)
{
if(window.console)
{
else if (this.datas[d].getVocabularyId() === null && this.datas[d].getValue() == value) {
if (window.console) {
console.log('already got this value');
}
return true;
@@ -314,12 +273,10 @@
}
return false;
},
removeValue : function(value, vocabularyId) {
removeValue: function (value, vocabularyId) {
if(this.databoxField.isReadonly())
{
if(window.console)
{
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
@@ -328,33 +285,25 @@
vocabularyId = checkVocabId(vocabularyId);
if(window.console)
{
if (window.console) {
console.log('Try to remove value ', value, vocabularyId, this.datas);
}
for(d in this.datas)
{
if(window.console)
{
for (d in this.datas) {
if (window.console) {
console.log('loopin... ', this.datas[d].getValue());
}
if(this.datas[d].getVocabularyId() !== null)
{
if(this.datas[d].getVocabularyId() == vocabularyId)
{
if(window.console)
{
if (this.datas[d].getVocabularyId() !== null) {
if (this.datas[d].getVocabularyId() == vocabularyId) {
if (window.console) {
console.log('Found within the vocab ! removing... ');
}
this.datas[d].remove();
this.options.dirty = true;
}
}
else if(this.datas[d].getValue() == value)
{
if(window.console)
{
else if (this.datas[d].getValue() == value) {
if (window.console) {
console.log('Found ! removing... ');
}
this.datas[d].remove();
@@ -363,60 +312,54 @@
}
return this;
},
isEmpty : function() {
isEmpty: function () {
var empty = true;
for(d in this.datas)
{
if(this.datas[d].getValue() !== '')
for (d in this.datas) {
if (this.datas[d].getValue() !== '')
empty = false;
}
return empty;
},
empty : function() {
empty: function () {
if(this.databoxField.isReadonly())
{
if(window.console)
{
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
return;
}
for(d in this.datas)
{
for (d in this.datas) {
this.datas[d].remove();
this.options.dirty = true;
}
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';
if(this.isEmpty())
if (this.isEmpty())
return null;
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';
}
if(this.isEmpty())
if (this.isEmpty())
return new Array();
var arrayValues = [];
for(d in this.datas)
{
if(this.datas[d].getValue() === '')
for (d in this.datas) {
if (this.datas[d].getValue() === '')
continue;
arrayValues.push(this.datas[d]);
@@ -424,29 +367,26 @@
return arrayValues;
},
sort : function(algo) {
sort: function (algo) {
this.datas.sort(algo);
return this;
},
getSerializedValues : function() {
getSerializedValues: function () {
var arrayValues = [];
var values = this.getValues();
for(v in values)
{
for (v in values) {
arrayValues.push(values[v].getValue());
}
return arrayValues.join(' ' + this.databoxField.getSeparator() + ' ');
},
replaceValue : function(search, replace) {
replaceValue: function (search, replace) {
if(this.databoxField.isReadonly())
{
if(window.console)
{
if (this.databoxField.isReadonly()) {
if (window.console) {
console.error('Unable to set a value to a readonly field');
}
@@ -455,18 +395,15 @@
var n = 0;
for(d in this.datas)
{
if(this.datas[d].getVocabularyId() !== null)
{
for (d in this.datas) {
if (this.datas[d].getVocabularyId() !== null) {
continue;
}
var value = this.datas[d].getValue();
var replacedValue = value.replace(search, replace);
if(value === replacedValue)
{
if (value === replacedValue) {
continue;
}
@@ -474,8 +411,7 @@
this.removeValue(value);
if(!this.hasValue(replacedValue))
{
if (!this.hasValue(replacedValue)) {
this.addValue(replacedValue);
}
@@ -484,20 +420,18 @@
return n;
},
exportDatas : function() {
exportDatas: function () {
var returnValue = new Array();
for(d in this.datas)
{
for (d in this.datas) {
var temp = {
meta_id : this.datas[d].getMetaId() ? this.datas[d].getMetaId() : '',
meta_struct_id : this.getMetaStructId(),
value : this.datas[d].getValue()
meta_id: this.datas[d].getMetaId() ? this.datas[d].getMetaId() : '',
meta_struct_id: this.getMetaStructId(),
value: this.datas[d].getValue()
};
if(this.datas[d].getVocabularyId())
{
if (this.datas[d].getVocabularyId()) {
temp.vocabularyId = this.datas[d].getVocabularyId();
}
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 = {
allow_multiple : false,
selector : '',
callbackSelection : null,
selectStart : null,
selectStop : null,
limit : null
allow_multiple: false,
selector: '',
callbackSelection: null,
selectStart: null,
selectStop: null,
limit: null
},
options = (typeof options == 'object') ? options : {};
var $this = this;
if($container.data('selectionnable'))
{
if ($container.data('selectionnable')) {
/* this container is already selectionnable */
if(window.console)
{
if (window.console) {
console.error('Trying to apply new selection to existing one');
}
@@ -39,10 +37,9 @@
this.$container.addClass('selectionnable');
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);
}
@@ -50,15 +47,13 @@
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 index1 = jQuery.inArray( jQuery('.last_selected', this.$container).filter($this.options.selector)[0], lst );
var index2 = jQuery.inArray( $that[0], lst );
var index1 = jQuery.inArray(jQuery('.last_selected', this.$container).filter($this.options.selector)[0], lst);
var index2 = jQuery.inArray($that[0], lst);
if(index2<index1)
{
if (index2 < index1) {
var tmp = index1;
index1 = (index2 - 1) < 0 ? index2 : (index2 - 1);
index2 = tmp;
@@ -66,21 +61,17 @@
var stopped = false;
if(index2 != -1 && index1 != -1)
{
var exp = $this.options.selector + ':gt(' + index1 + '):lt(' + (index2-index1) + ')';
if (index2 != -1 && index1 != -1) {
var exp = $this.options.selector + ':gt(' + index1 + '):lt(' + (index2 - index1) + ')';
$.each(jQuery(exp, this.$container),function(i,n){
if(!jQuery(n).hasClass('selected') && stopped === false)
{
if(!$this.hasReachLimit())
{
$.each(jQuery(exp, this.$container), function (i, n) {
if (!jQuery(n).hasClass('selected') && stopped === false) {
if (!$this.hasReachLimit()) {
var k = get_value(jQuery(n), $this);
$this.push(k);
jQuery(n).addClass('selected');
}
else
{
else {
alert(language.max_record_selected);
stopped = true;
}
@@ -88,43 +79,33 @@
});
}
if($this.has(k) === false && stopped === false)
{
if(!$this.hasReachLimit())
{
if ($this.has(k) === false && stopped === false) {
if (!$this.hasReachLimit()) {
$this.push(k);
$that.addClass('selected');
}
else
{
else {
alert(language.max_record_selected);
}
}
}
else
{
if(!is_ctrl_key(event))
{
else {
if (!is_ctrl_key(event)) {
$this.empty().push(k);
jQuery('.selected', this.$container).filter($this.options.selector).removeClass('selected');
$that.addClass('selected');
}
else
{
if($this.has(k) === true)
{
else {
if ($this.has(k) === true) {
$this.remove(k);
$that.removeClass('selected');
}
else
{
if(!$this.hasReachLimit())
{
else {
if (!$this.hasReachLimit()) {
$this.push(k);
$that.addClass('selected');
}
else
{
else {
alert(language.max_record_selected);
}
}
@@ -135,8 +116,7 @@
$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);
}
@@ -147,122 +127,110 @@
return;
};
function get_value(element, Selectable)
{
if(typeof Selectable.options.callbackSelection === 'function')
{
function get_value(element, Selectable) {
if (typeof Selectable.options.callbackSelection === 'function') {
return Selectable.options.callbackSelection(jQuery(element));
}
else
{
else {
return jQuery('input[name="id"]', jQuery(element)).val();
}
}
function is_ctrl_key(event)
{
if(event.altKey)
function is_ctrl_key(event) {
if (event.altKey)
return true;
if(event.ctrlKey)
if (event.ctrlKey)
return true;
if(event.metaKey) // apple key opera
if (event.metaKey) // apple key opera
return true;
if(event.keyCode == '17') // apple key opera
if (event.keyCode == '17') // apple key opera
return true;
if(event.keyCode == '224') // apple key mozilla
if (event.keyCode == '224') // apple key mozilla
return true;
if(event.keyCode == '91') // apple key safari
if (event.keyCode == '91') // apple key safari
return true;
return false;
}
function is_shift_key(event)
{
if(event.shiftKey)
function is_shift_key(event) {
if (event.shiftKey)
return true;
return false;
}
Selectable.prototype = {
push : function(element){
if(this.options.allow_multiple === true || !this.has(element))
{
push: function (element) {
if (this.options.allow_multiple === true || !this.has(element)) {
this.datas.push(element);
}
return this;
},
hasReachLimit : function() {
if(this.options.limit !== null && this.options.limit <= this.datas.length)
{
hasReachLimit: function () {
if (this.options.limit !== null && this.options.limit <= this.datas.length) {
return true;
}
return false;
},
remove : function(element){
this.datas = jQuery.grep(this.datas, function(n){
remove: function (element) {
this.datas = jQuery.grep(this.datas, function (n) {
return(n !== element);
});
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;
},
empty : function(){
empty: function () {
var $this = this;
this.datas = new Array();
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);
}
return this;
},
length : function(){
length: function () {
return this.datas.length;
},
size : function(){
size: function () {
return this.datas.length;
},
serialize : function(separator){
serialize: function (separator) {
separator = separator || ';';
return this.datas.join(separator);
},
selectAll : function(){
selectAll: function () {
this.select('*');
return this;
},
select : function(selector){
select: function (selector) {
var $this = this,
stopped = false;
jQuery(this.options.selector, this.$container).filter(selector).not('.selected').filter(':visible').each(function(){
if(!$this.hasReachLimit())
{
jQuery(this.options.selector, this.$container).filter(selector).not('.selected').filter(':visible').each(function () {
if (!$this.hasReachLimit()) {
$this.push(get_value(this, $this));
$(this).addClass('selected');
}
else
{
if(stopped === false)
{
else {
if (stopped === false) {
alert(language.max_record_selected);
}
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);
}

View File

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

View File

@@ -1,18 +1,17 @@
(function( $ ){
(function ($) {
var methods = {
init : function( options ) {
init: function (options) {
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');
if ( ! data )
{
if ( options ) {
$.extend( settings, options );
if (!data) {
if (options) {
$.extend(settings, options);
}
$this.data('path_file_tests', {});
@@ -21,19 +20,18 @@
$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_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();
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;
if(!$this.hasClass('required') && $.trim($this.val()) === '')
{
if (!$this.hasClass('required') && $.trim($this.val()) === '') {
el_status.css('visibility', 'hidden');
return;
}
@@ -43,43 +41,39 @@
type: "GET",
url: settings.url,
data: {
path : $this.val()
path: $this.val()
},
beforeSend:function(){
beforeSend: function () {
el_loader.css('visibility', 'visible');
},
success: function(data){
success: function (data) {
el_loader.css('visibility', 'hidden');
if($this.hasClass('required'))
{
if ($this.hasClass('required')) {
$this.addClass('field_error');
}
if($this.hasClass('test_executable') && (data.executable === false || data.file !== true))
{
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible');
if ($this.hasClass('test_executable') && (data.executable === false || data.file !== true)) {
el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
return;
}
if($this.hasClass('test_writeable') && data.writeable === false)
{
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible');
if ($this.hasClass('test_writeable') && data.writeable === false) {
el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
return;
}
if($this.hasClass('test_readable') && data.readable === false)
{
el_status.attr('src','/skins/icons/delete.png').css('visibility', 'visible');
if ($this.hasClass('test_readable') && data.readable === false) {
el_status.attr('src', '/skins/icons/delete.png').css('visibility', 'visible');
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');
return;
},
timeout:function(){
timeout: function () {
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_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);
@@ -87,49 +81,46 @@
$this.trigger('keyup');
$this.nextAll('.reload').bind('click', function(){
$this.nextAll('.reload').bind('click', function () {
$this.trigger('keyup');
});
}
});
},
destroy : function( ) {
return this.each(function() {
destroy: function () {
return this.each(function () {
$(this).data('path_file_tests', null);
});
}
};
$.fn.path_file_test = function(method) {
$.fn.path_file_test = function (method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} 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 = {
init : function( options ) {
init: function (options) {
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');
if ( ! data )
{
if ( options ) {
$.extend( settings, options );
if (!data) {
if (options) {
$.extend(settings, options);
}
$this.data('url_tests', {});
@@ -137,7 +128,7 @@
$this.after('<img class="reload" src="/skins/icons/reload.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_status = $(this).nextAll('.status');
@@ -147,91 +138,84 @@
var value = $.trim($this.val());
if(!required && value === '')
{
el_status.attr('src','/skins/icons/ok.png');
if (!required && value === '') {
el_status.attr('src', '/skins/icons/ok.png');
return;
}
if(required && value === '')
{
el_status.attr('src','/skins/icons/delete.png');
if (required && value === '') {
el_status.attr('src', '/skins/icons/delete.png');
return;
}
if(same_domain && value.substring(0,1) != '/')
{
value = '/'+value;
if (same_domain && value.substring(0, 1) != '/') {
value = '/' + value;
}
if(same_domain)
{
value = location.protocol+'//'+location.hostname+value;
if (same_domain) {
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();
var ajax = $.ajax({
type: "GET",
url: settings.url,
dataType:'json',
dataType: 'json',
data: {
url : value
url: value
},
beforeSend:function(){
beforeSend: function () {
el_loader.css('visibility', 'visible');
},
success: function(datas){
success: function (datas) {
el_loader.css('visibility', 'hidden');
if(datas.code === 404)
{
el_status.attr('src','/skins/icons/delete.png');
if (datas.code === 404) {
el_status.attr('src', '/skins/icons/delete.png');
return;
}
if(!listable && datas.code === 403)
{
el_status.attr('src','/skins/icons/ok.png');
if (!listable && datas.code === 403) {
el_status.attr('src', '/skins/icons/ok.png');
}
else
{
el_status.attr('src','/skins/icons/delete.png');
else {
el_status.attr('src', '/skins/icons/delete.png');
}
return;
},
timeout:function(){
timeout: function () {
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_status.attr('src','/skins/icons/delete.png');
el_status.attr('src', '/skins/icons/delete.png');
}
});
$this.data('ajax_url_test', ajax);
});
$this.trigger('keyup');
$this.nextAll('.reload').bind('click', function(){
$this.nextAll('.reload').bind('click', function () {
$this.trigger('keyup');
});
}
});
},
destroy : function( ) {
return this.each(function() {
destroy: function () {
return this.each(function () {
$(this).data('url_tests', null);
});
}
};
$.fn.url_test = function(method) {
$.fn.url_test = function (method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} 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/fieldError",
"apps/admin/fields/errors/errorManager"
], function(
$, _, Backbone, i18n, FieldsCollection, VocabulariesCollection,
DcFieldsCollection, FieldListView, SaveView, FieldErrorView, ErrorManager) {
var initialize = function() {
], function ($, _, Backbone, i18n, FieldsCollection, VocabulariesCollection, DcFieldsCollection, FieldListView, SaveView, FieldErrorView, ErrorManager) {
var initialize = function () {
AdminFieldApp = {
$window : $(window),
$scope : $("#admin-field-app"),
$top : $(".row-top", this.$scope),
$bottom : $(".row-bottom", this.$scope),
$leftBlock : $(".left-block", this.$bottom),
$rightBlock : $(".right-block", this.$bottom),
fieldsToDelete : [],
lng : function() {
$window: $(window),
$scope: $("#admin-field-app"),
$top: $(".row-top", this.$scope),
$bottom: $(".row-bottom", this.$scope),
$leftBlock: $(".left-block", this.$bottom),
$rightBlock: $(".right-block", this.$bottom),
fieldsToDelete: [],
lng: function () {
return typeof p4 === "undefined" ? "en" : (p4.lng || "en");
},
resizeListBlock: function () {
@@ -56,7 +54,7 @@ define([
// initiliaze collections
AdminFieldApp.fieldsCollection = new FieldsCollection(null, {
sbas_id : AdminFieldApp.sbas_id
sbas_id: AdminFieldApp.sbas_id
});
AdminFieldApp.vocabularyCollection = new VocabulariesCollection();
AdminFieldApp.dcFieldsCollection = new DcFieldsCollection();
@@ -71,12 +69,12 @@ define([
AdminFieldApp.dcFieldsCollection.fetch(),
$.ajax({
url: '/available-languages',
success: function(languages) {
success: function (languages) {
AdminFieldApp.languages = languages;
}
})
]).done(
function() {
function () {
// register views
AdminFieldApp.saveView = new SaveView({
el: $(".save-block", AdminFieldApp.scope)
@@ -96,7 +94,7 @@ define([
AdminFieldApp.$window.trigger("resize");
// click on first item list
if (AdminFieldApp.fieldListView.itemViews.length > 0 ) {
if (AdminFieldApp.fieldListView.itemViews.length > 0) {
_.first(AdminFieldApp.fieldListView.itemViews).clickAction().animate();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -13,11 +13,11 @@ define([
"backbone",
"i18n",
"bootstrap"
], function($, _, Backbone, i18n, bootstrap) {
], function ($, _, Backbone, i18n, bootstrap) {
var AlertView = Backbone.View.extend({
tagName: "div",
className: "alert",
initialize: function(options) {
initialize: function (options) {
var self = this;
if (options) {
@@ -30,7 +30,7 @@ define([
self.remove();
});
},
render: function() {
render: function () {
var self = this;
var template = _.template($("#alert_template").html(), {
msg: this.message
@@ -39,7 +39,9 @@ define([
this.$el.addClass("alert-" + this.alert).html(template).alert();
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);

View File

@@ -15,7 +15,7 @@ define([
"bootstrap",
"apps/admin/fields/views/alert",
"models/field"
], function($, _, Backbone, i18n, bootstrap, AlertView, FieldModel) {
], function ($, _, Backbone, i18n, bootstrap, AlertView, FieldModel) {
var CreateView = Backbone.View.extend({
tagName: "div",
events: {
@@ -24,22 +24,22 @@ define([
"click .btn-cancel-field": "toggleCreateFormAction",
"keyup input": "onKeyupInput"
},
render: function() {
render: function () {
var template = _.template($("#create_template").html());
this.$el.html(template);
$("#new-source", this.$el).autocomplete({
minLength: 2,
source: function(request, response) {
source: function (request, response) {
$.ajax({
url: "/admin/fields/tags/search",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
@@ -59,7 +59,7 @@ define([
.find(".help-block")
.empty();
},
createAction: function(event) {
createAction: function (event) {
var self = this;
var formErrors = 0;
@@ -81,7 +81,7 @@ define([
}
// 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();
})) {
fieldName
@@ -118,7 +118,7 @@ define([
formErrors++;
}
if (formErrors > 0 ) {
if (formErrors > 0) {
return;
}
@@ -126,15 +126,15 @@ define([
"sbas-id": AdminFieldApp.sbas_id,
"name": fieldNameValue,
"tag": fieldTagValue,
"label_en" : $("#new-label_en", this.$el).val(),
"label_fr" : $("#new-label_fr", this.$el).val(),
"label_de" : $("#new-label_de", this.$el).val(),
"label_nl" : $("#new-label_nl", this.$el).val(),
"label_en": $("#new-label_en", this.$el).val(),
"label_fr": $("#new-label_fr", this.$el).val(),
"label_de": $("#new-label_de", this.$el).val(),
"label_nl": $("#new-label_nl", this.$el).val(),
"multi": $("#new-multivalued", this.$el).is(":checked")
});
field.save(null, {
success: function(field, response, options) {
success: function (field, response, options) {
AdminFieldApp.fieldsCollection.add(field);
_.last(AdminFieldApp.fieldListView.itemViews).clickAction().animate();
@@ -144,7 +144,7 @@ define([
})
}).render();
},
error: function(xhr, textStatus, errorThrown) {
error: function (xhr, textStatus, errorThrown) {
new AlertView({
alert: "error", message: '' !== xhr.responseText ? xhr.responseText : i18n.t("something_wrong")}
).render();
@@ -155,7 +155,7 @@ define([
return this;
},
toggleCreateFormAction: function(event) {
toggleCreateFormAction: function (event) {
var fieldBlock = $(".add-field-block", 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/dcField",
"apps/admin/fields/errors/error"
], function($, _, Backbone, i18n, MultiViews, AlertView, ModalView, DcFieldView, Error) {
], function ($, _, Backbone, i18n, MultiViews, AlertView, ModalView, DcFieldView, Error) {
// Add multiview methods
var FieldEditView = Backbone.View.extend(_.extend({}, MultiViews, {
tagName: "div",
className: "field-edit",
initialize: function() {
initialize: function () {
this.model.on("change", this._onModelChange, this);
},
updateModel: function(model) {
updateModel: function (model) {
// unbind event to previous model
this.model.off("change");
this.model = model;
return this;
},
render: function() {
render: function () {
var self = this;
var template = _.template($("#edit_template").html(), {
lng: AdminFieldApp.lng(),
@@ -45,7 +45,7 @@ define([
this.$el.empty().html(template);
this._assignView({
".dc-fields-subview" : new DcFieldView({
".dc-fields-subview": new DcFieldView({
collection: AdminFieldApp.dcFieldsCollection,
field: this.model
})
@@ -53,15 +53,15 @@ define([
var completer = $("#tag", this.$el).autocomplete({
minLength: 2,
source: function(request, response) {
source: function (request, response) {
$.ajax({
url: "/admin/fields/tags/search",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
value: item.value
@@ -70,7 +70,7 @@ define([
}
});
},
close: function(e) {
close: function (e) {
self.tagFieldChangedAction(e);
}
});
@@ -95,7 +95,7 @@ define([
"change select": "selectionChangedAction",
"click .lng-label a": "_toggleLabels"
},
triggerControlledVocabulary: function(e) {
triggerControlledVocabulary: function (e) {
if ($(e.target, this.$el).find("option:selected").val() === "") {
this.model.set("vocabulary-type", false);
this.render();
@@ -105,7 +105,7 @@ define([
this.render();
}
},
selectionChangedAction: function(e) {
selectionChangedAction: function (e) {
var field = $(e.target);
var data = {};
data[field.attr("id")] = $("option:selected", field).val();
@@ -113,7 +113,7 @@ define([
return this;
},
fieldChangedAction: function(e) {
fieldChangedAction: function (e) {
var field = $(e.target);
var fieldId = field.attr("id");
var data = {};
@@ -122,7 +122,7 @@ define([
return this;
},
labelChangedAction: function(e) {
labelChangedAction: function (e) {
var field = $(e.target);
var fieldId = field.attr("id");
var data = this.model.get("labels");
@@ -133,13 +133,13 @@ define([
return this;
},
tagFieldChangedAction: function(e) {
tagFieldChangedAction: function (e) {
var $this = this;
var fieldTag = $(e.target);
var fieldTagId = fieldTag.attr("id");
var fieldTagValue = fieldTag.val();
var onFieldValid = function() {
var onFieldValid = function () {
if (fieldTag.closest(".control-group").hasClass("error")) {
// remove error
AdminFieldApp.errorManager.removeModelFieldError(
@@ -157,7 +157,7 @@ define([
}
if ("" !== fieldTagValue) {
var jqxhr = $.get( "/admin/fields/tags/"+fieldTagValue, onFieldValid).fail(function() {
var jqxhr = $.get("/admin/fields/tags/" + fieldTagValue, onFieldValid).fail(function () {
fieldTag
.closest(".control-group")
.addClass("error")
@@ -173,7 +173,7 @@ define([
onFieldValid();
}
},
deleteAction: function() {
deleteAction: function () {
var self = this;
var modalView = new ModalView({
model: this.model,
@@ -191,7 +191,7 @@ define([
var index = previousIndex ? previousIndex : (nextIndex ? nextIndex - 1 : -1);
modalView.render();
modalView.on("modal:confirm", function() {
modalView.on("modal:confirm", function () {
AdminFieldApp.fieldsToDelete.push(self.model);
AdminFieldApp.fieldListView.collection.remove(self.model);
self._selectModelView(index);
@@ -200,19 +200,19 @@ define([
return this;
},
_onModelChange: function() {
_onModelChange: function () {
AdminFieldApp.fieldListView.collection.remove(this.model, {silent: true});
AdminFieldApp.fieldListView.collection.add(this.model, {silent: true});
AdminFieldApp.saveView.updateStateButton();
},
// select temView by index in itemList
_selectModelView: function(index) {
_selectModelView: function (index) {
// select previous or next itemview
if (index >= 0) {
AdminFieldApp.fieldListView.itemViews[index].select().animate().click();
}
},
_toggleLabels: function(event) {
_toggleLabels: function (event) {
event.preventDefault();
var curLabel = $(event.target);
$('.lng-label', this.$el).removeClass("select");

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
;(function (root, factory) {
;
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([''], factory);
} else {
@@ -6,33 +7,33 @@
}
}(this, function () {
return {
init: function($field, options) {
init: function ($field, options) {
var geocompleter = $field.geocompleter(options);
// 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");
$("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
geocompleter.geocompleter("autocompleter", "on", "autocompletesearch", function(event, ui) {
geocompleter.geocompleter("autocompleter", "on", "autocompletesearch", function (event, ui) {
$(this).addClass('input-loading');
$(this).removeClass('input-error');
});
// 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');
});
// 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');
});
// 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).addClass('input-error');
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -15,24 +15,7 @@ define([
'apps/admin/fields/views/modal',
'apps/admin/fields/views/save',
'apps/admin/fields/views/dcField'
], function(
chai,
fixtures,
$,
App,
FieldModel,
FieldCollection,
DcFieldCollection,
VocabularyCollection,
SingleItemView,
ListItemView,
AlertView,
EditView,
FieldErrorView,
ModalView,
SaveView,
DcFieldView
) {
], function (chai, fixtures, $, App, FieldModel, FieldCollection, DcFieldCollection, VocabularyCollection, SingleItemView, ListItemView, AlertView, EditView, FieldErrorView, ModalView, SaveView, DcFieldView) {
var expect = chai.expect;
var assert = chai.assert;
var should = chai.should();
@@ -44,36 +27,36 @@ define([
App.initialize();
describe("Admin field", function() {
describe("Initialization", function() {
it("should create a global variable", function() {
describe("Admin field", function () {
describe("Initialization", function () {
it("should create a global variable", function () {
should.exist(AdminFieldApp);
});
});
describe("Collections", function() {
describe("DcField Collection", function() {
beforeEach(function() {
describe("Collections", function () {
describe("DcField Collection", function () {
beforeEach(function () {
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");
});
});
describe("Vocabulary Collection", function() {
beforeEach(function() {
describe("Vocabulary Collection", function () {
beforeEach(function () {
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");
});
});
describe("Field Collection", function() {
beforeEach(function() {
describe("Field Collection", function () {
beforeEach(function () {
this.collection = new FieldCollection([
{"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"},
{"id": 2, "sbas-id": sbasId, "name": "Object", "tag": "XMP:Object"}
@@ -82,24 +65,24 @@ define([
});
});
describe("Initialization", function() {
it("should throw an exception if 'sbas_id' is missing", function() {
expect(function() {
describe("Initialization", function () {
it("should throw an exception if 'sbas_id' is missing", function () {
expect(function () {
new FieldCollection([]);
}).to.throw("You must set a sbas id");
});
it("should set collection url according to provided 'sbas-id'", function() {
this.collection.url().should.equal("/admin/fields/"+sbasId+"/fields");
it("should set collection url according to provided 'sbas-id'", function () {
this.collection.url().should.equal("/admin/fields/" + sbasId + "/fields");
});
});
describe("Methods", function() {
it("should retrieve categorie item if searching terms begins with 'cat'", function() {
describe("Methods", function () {
it("should retrieve categorie item if searching terms begins with 'cat'", function () {
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;
this.collection.nextIndex(this.collection.first()).should.equal(1);
this.collection.previousIndex(this.collection.last()).should.equal(0);
@@ -109,29 +92,29 @@ define([
});
});
describe("Views", function() {
describe("Single Item Views", function() {
beforeEach(function() {
describe("Views", function () {
describe("Single Item Views", function () {
beforeEach(function () {
this.field = new FieldModel({"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
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);
});
it("should render as a LI element", function() {
it("should render as a LI element", function () {
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-tag').html().should.equal("XMP:Categorie");
});
});
describe("List Item Views", function() {
beforeEach(function() {
describe("List Item Views", function () {
beforeEach(function () {
this.collection = new FieldCollection([
{"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"},
{"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);
});
it("should render as a DIV block", function() {
it("should render as a DIV block", function () {
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.$el.find("li").should.have.length(2);
});
});
describe("Alert Views", function() {
beforeEach(function() {
describe("Alert Views", function () {
beforeEach(function () {
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);
});
it("should render as a DIV element", function() {
it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV");
});
});
describe("DcField Views", function() {
beforeEach(function() {
this.collection = new DcFieldCollection([{
describe("DcField Views", function () {
beforeEach(function () {
this.collection = new DcFieldCollection([
{
"label": "Contributor",
"definition": "An entity responsible for making contributions to the resource.",
"URI": "http://dublincore.org/documents/dces/#contributor"
}, {
},
{
"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.",
"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);
});
it("should render as a DIV element", function() {
it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV");
});
});
describe("Edit Views", function() {
beforeEach(function() {
describe("Edit Views", function () {
beforeEach(function () {
var model = new FieldModel({"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
this.view = new EditView({"model": model});
@@ -227,15 +212,15 @@ define([
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);
});
it("should render as a DIV element", function() {
it("should render as a DIV element", function () {
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();
view.$('input#tag').val("").blur();
@@ -243,7 +228,7 @@ define([
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();
view.$('input#vocabulary-restricted').attr("checked", true);
@@ -253,22 +238,22 @@ define([
});
});
describe("FieldError Views", function() {
beforeEach(function() {
describe("FieldError Views", function () {
beforeEach(function () {
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);
});
it("should render as a DIV element", function() {
it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV");
});
});
describe("Modal Views", function() {
beforeEach(function() {
describe("Modal Views", function () {
beforeEach(function () {
var model = new FieldModel({"id": 1, "sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
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.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.remove();
});
});
describe("Save Views", function() {
beforeEach(function() {
describe("Save Views", function () {
beforeEach(function () {
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);
});
it("should render as a DIV element", function() {
it("should render as a DIV element", function () {
this.view.render().el.nodeName.should.equal("DIV");
});
});
});
describe("Edge cases", function() {
beforeEach(function() {
describe("Edge cases", function () {
beforeEach(function () {
AdminFieldApp.fieldsCollection.reset();
AdminFieldApp.fieldsCollection.add({"sbas-id": sbasId, "name": "Categorie", "tag": "XMP:Categorie"});
AdminFieldApp.dcFieldsCollection.add({
@@ -324,7 +309,7 @@ define([
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.fieldEditView.model.set({
"name": "new name"
@@ -332,15 +317,17 @@ define([
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();
should.exist(AdminFieldApp.fieldEditView);
assert.equal(AdminFieldApp.fieldEditView.model, AdminFieldApp.fieldListView.collection.first(), 'model is updated');
});
it("should reorder collection on drop action", function() {
var ui = {item: {index: function() {return 2;}}};
AdminFieldApp.fieldListView.itemViews[0].dropAction({},ui);
it("should reorder collection on drop action", function () {
var ui = {item: {index: function () {
return 2;
}}};
AdminFieldApp.fieldListView.itemViews[0].dropAction({}, ui);
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/input',
'common/forms/views/error'
], function(
chai,
fixtures,
$,
FormView,
InputView,
ErrorView
) {
], function (chai, fixtures, $, FormView, InputView, ErrorView) {
var expect = chai.expect;
var assert = chai.assert;
var should = chai.should();
@@ -20,10 +13,12 @@ define([
fixtures.path = 'fixtures';
$("body").append(fixtures.read('home/login/form', 'home/login/templates'));
describe("Login Home", function() {
describe("Form View", function() {
it("should initialize validator with proper rules", function() {
var rules = [{name: "hello",rules: "simple_rules"}];
describe("Login Home", function () {
describe("Form View", function () {
it("should initialize validator with proper rules", function () {
var rules = [
{name: "hello", rules: "simple_rules"}
];
var form = new FormView({
el: $('form[name=loginForm]'),
rules: rules
@@ -31,7 +26,7 @@ define([
form.validator.getRules().should.equal(rules);
});
it("should initialize input views", function() {
it("should initialize input views", function () {
var form = new FormView({
el: $('form[name=loginForm]')
});
@@ -39,7 +34,7 @@ define([
Object.keys(form.inputViews).length.should.equal(5);
});
it("should initialize errors", function() {
it("should initialize errors", function () {
var form = new FormView({
el: $('form[name=loginForm]')
});
@@ -47,14 +42,16 @@ define([
assert.isTrue(_.isEmpty(form.validator.getErrors()));
});
it("should render errors on submit", function() {
it("should render errors on submit", function () {
var form = new FormView({
el: $('form[name=loginForm]'),
rules: [{
rules: [
{
"name": "login",
"rules": "required",
"message" : "something is wrong"
}]
"message": "something is wrong"
}
]
});
form._onSubmit(document.createEvent("Event"));
@@ -62,8 +59,8 @@ define([
});
});
describe("Input View", function() {
it("should initialize error view", function() {
describe("Input View", function () {
it("should initialize error view", function () {
var input = new InputView({
"name": "test",
"errorTemplate": "#field_errors"
@@ -72,9 +69,9 @@ define([
});
});
describe("Error View", function() {
it("should render errors", function() {
var error ={
describe("Error View", function () {
it("should render errors", function () {
var error = {
name: "test",
message: "Something is wrong"
};
@@ -82,7 +79,7 @@ define([
var errorView = new ErrorView({
"name": "test",
"errors": [error],
"el" : $(".error-view").first(),
"el": $(".error-view").first(),
"errorTemplate": "#field_errors"
});
@@ -91,7 +88,7 @@ define([
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();
$el.html('previous error here');
@@ -99,7 +96,7 @@ define([
var errorView = new ErrorView({
"name": "test",
"errors": [],
"el" : $el,
"el": $el,
"errorTemplate": "#field_errors"
});

View File

@@ -3,108 +3,108 @@ define([
'models/field',
'models/dcField',
'models/vocabulary'
], function(chai, Field, DcField, Vocabulary) {
], function (chai, Field, DcField, Vocabulary) {
var expect = chai.expect;
var assert = chai.assert;
var should = chai.should();
describe("Models", function(){
describe("Field Model", function(){
describe("Initialization", function() {
describe("Models", function () {
describe("Field Model", function () {
describe("Initialization", function () {
var sbasId = 1;
beforeEach(function() {
beforeEach(function () {
this.field = new Field({
"sbas-id" : sbasId
"sbas-id": sbasId
});
});
it("should throw an exception if 'sbas-id' is missing", function() {
expect(function() {
it("should throw an exception if 'sbas-id' is missing", function () {
expect(function () {
new Field();
}).to.throw("You must set a sbas id");
});
it("should set model url according to provided 'sbas-id'", function() {
this.field.urlRoot().should.equal("/admin/fields/"+sbasId+"/fields");
it("should set model url according to provided 'sbas-id'", function () {
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;
});
it("should default type property to 'string'", function() {
it("should default type property to 'string'", function () {
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");
});
it("should default tbranch property to 'empty'", function() {
it("should default tbranch property to 'empty'", function () {
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("");
});
it("should default required property to 'false'", function() {
it("should default required property to 'false'", function () {
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;
});
it("should default multi property to 'false'", function() {
it("should default multi property to 'false'", function () {
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;
});
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;
});
it("should default report property to 'true'", function() {
it("should default report property to 'true'", function () {
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;
});
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;
});
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;
});
});
});
describe("DcField Model", function(){
describe("Initialization", function() {
beforeEach(function() {
describe("DcField Model", function () {
describe("Initialization", function () {
beforeEach(function () {
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");
});
});
});
describe("DcField Model", function(){
describe("Initialization", function() {
beforeEach(function() {
describe("DcField Model", function () {
describe("Initialization", function () {
beforeEach(function () {
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");
});
});

View File

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

View File

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

View File

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

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);
return false;
}
@@ -19,19 +17,17 @@ $(document).ready(function(){
return true;
}
$('#users th.sortable').live('click', function(){
$('#users th.sortable').live('click',function () {
var $this = $(this);
var sort = $('input', $this).val();
if((sort == $('#users_page_form input[name="srt"]').val())
&& ($('#users_page_form input[name="ord"]').val() == 'asc'))
{
if ((sort == $('#users_page_form input[name="srt"]').val())
&& ($('#users_page_form input[name="ord"]').val() == 'asc')) {
var ord = 'desc';
}
else
{
else {
var ord = 'asc';
}
@@ -39,63 +35,65 @@ $(document).ready(function(){
$('#users_page_form input[name="ord"]').val(ord);
$('#users_page_form').trigger('submit');
}).live('mouseover', function(){$(this).addClass('hover');})
.live('mouseout', function(){$(this).removeClass('hover');});
}).live('mouseover', function () {
$(this).addClass('hover');
})
.live('mouseout', function () {
$(this).removeClass('hover');
});
var buttons = {};
buttons[language.create_user] = function(){
buttons[language.create_user] = function () {
check_new_user(false);
};
buttons[language.annuler] = function(){
buttons[language.annuler] = function () {
$('#user_add_dialog').dialog('close')
};
$('#user_add_dialog').dialog({
buttons:buttons,
modal:true,
resizable:false,
draggable:false,
width:500
buttons: buttons,
modal: true,
resizable: false,
draggable: false,
width: 500
}).dialog('close');
var buttons = {};
buttons[language.create_template] = function(){
buttons[language.create_template] = function () {
check_new_user(true);
};
buttons[language.annuler] = function(){
buttons[language.annuler] = function () {
$('#template_add_dialog').dialog('close');
};
$('#template_add_dialog').dialog({
buttons:buttons,
modal:true,
resizable:false,
draggable:false,
width:500
buttons: buttons,
modal: true,
resizable: false,
draggable: false,
width: 500
}).dialog('close');
function check_new_user(is_template)
{
function check_new_user(is_template) {
var container = is_template ? $('#template_add_dialog') : $('#user_add_dialog');
$('#new_user_loader').show();
$.ajax({
type: 'POST',
url: '../admin/users/create/',
dataType : 'json',
dataType: 'json',
data: {
act:'CREATENEWUSER',
value:$('input[name="value"]', container).val(),
act: 'CREATENEWUSER',
value: $('input[name="value"]', container).val(),
send_credentials: $('input[name="send_credentials"]', 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();
if(!data.error)
{
if (!data.error) {
if (container.data("ui-dialog")) {
container.dialog('close');
}
@@ -106,51 +104,48 @@ $(document).ready(function(){
type: 'POST',
url: '../admin/users/rights/',
data: {
users : data.data
users: data.data
},
success: function(data){
success: function (data) {
$('#right-ajax').removeClass('loading').html(data);
}
});
}
else
{
else {
alert(data.message);
}
},
error:function()
{
error: function () {
alert(language.serverError);
},
timeout:function()
{
timeout: function () {
alert(language.serverTimeout);
}
});
}
$('#users_page .user_adder').live('click', function(){
$('#users_page .user_adder').live('click', function () {
if ($('#user_add_dialog').data("ui-dialog")) {
$('#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")) {
$('#template_add_dialog').dialog('open');
}
});
$('#users_page_form').live('submit', function(){
$('#users_page_form').live('submit', function () {
var datas = $('#users_page_form').serializeArray();
$('#right-ajax').empty().addClass('loading');
$.ajax({
type: 'POST',
url: '../admin/users/search/',
data: datas,
success: function(data){
success: function (data) {
$('#right-ajax').removeClass('loading').empty().html(data);
}
});
@@ -158,14 +153,14 @@ $(document).ready(function(){
return false;
});
$('#users_page_search').live('submit', function(){
$('#users_page_search').live('submit', function () {
var datas = $('#users_page_search').serializeArray();
$('#right-ajax').empty().addClass('loading');
$.ajax({
type: 'POST',
url: '../admin/users/search/',
data: datas,
success: function(data){
success: function (data) {
$('#right-ajax').removeClass('loading').empty().html(data);
}
});
@@ -173,7 +168,7 @@ $(document).ready(function(){
return false;
});
$('#users_page_form .pager').live('click', function(){
$('#users_page_form .pager').live('click', function () {
var form = $('#users_page_form');
var current_page = parseInt($('input[name="page"]', form).val());
@@ -182,32 +177,28 @@ $(document).ready(function(){
var offset_start = 0;
if($(this).hasClass('prev'))
{
offset_start = (current_page-2) * perPage;
if ($(this).hasClass('prev')) {
offset_start = (current_page - 2) * perPage;
}
if($(this).hasClass('first'))
{
if ($(this).hasClass('first')) {
offset_start = 0;
}
if($(this).hasClass('next'))
{
if ($(this).hasClass('next')) {
offset_start = current_page * perPage;
}
if($(this).hasClass('last'))
{
offset_start = (Math.floor(parseInt($('input[name=total_results]').val()) / perPage))* perPage;
if ($(this).hasClass('last')) {
offset_start = (Math.floor(parseInt($('input[name=total_results]').val()) / perPage)) * perPage;
}
$('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 tbody tr, #users tbody td').live('click', function(evt){
if(evt.stopPropagation)
$('#users tbody tr, #users tbody td').live('click',function (evt) {
if (evt.stopPropagation)
evt.stopPropagation();
evt.cancelBubble = true;
evt.preventDefault();
@@ -216,29 +207,24 @@ $(document).ready(function(){
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 index1 = $.inArray($('tr.last_selected', cont)[0],lst);
var index2 = $.inArray($(el)[0],lst);
if(index2<index1)
{
var index1 = $.inArray($('tr.last_selected', cont)[0], lst);
var index2 = $.inArray($(el)[0], lst);
if (index2 < index1) {
var tmp = index1;
index1=(index2-1)<0?index2:(index2-1);
index2=tmp;
index1 = (index2 - 1) < 0 ? index2 : (index2 - 1);
index2 = tmp;
}
var stopped = false;
if(index2 != -1 && index1 != -1)
{
var exp = 'tr:gt('+index1+'):lt('+(index2-index1)+')';
$.each($(exp, cont),function(i,n){
if (index2 != -1 && index1 != -1) {
var exp = 'tr:gt(' + index1 + '):lt(' + (index2 - index1) + ')';
$.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;
return false;
}
@@ -246,63 +232,54 @@ $(document).ready(function(){
});
}
if(!stopped && $.inArray(k,p4.users.sel)<0)
{
if(!users_select_this(el,k))
if (!stopped && $.inArray(k, p4.users.sel) < 0) {
if (!users_select_this(el, k))
return false;
}
}
else
{
if(!is_ctrl_key(evt))
{
if($.inArray(k,p4.users.sel)<0)
{
else {
if (!is_ctrl_key(evt)) {
if ($.inArray(k, p4.users.sel) < 0) {
p4.users.sel = new Array();
$('tr', cont).removeClass('selected');
if(!users_select_this(el,k))
if (!users_select_this(el, k))
return false;
}
}
else
{
if($.inArray(k,p4.users.sel)>=0)
{
p4.users.sel = $.grep(p4.users.sel,function(n){
return(n!=k);
else {
if ($.inArray(k, p4.users.sel) >= 0) {
p4.users.sel = $.grep(p4.users.sel, function (n) {
return(n != k);
});
$(el).removeClass('selected');
}
else
{
if(!users_select_this(el,k))
else {
if (!users_select_this(el, k))
return false;
}
}
}
$('.last_selected', cont).removeClass('last_selected');
$(el).addClass('last_selected');
}).live('mousedown', function(evt){
}).live('mousedown', function (evt) {
if(evt.stopPropagation)
if (evt.stopPropagation)
evt.stopPropagation();
evt.cancelBubble = true;
evt.preventDefault();
});
$('#users_apply_template').live('submit', function(){
$('#users_apply_template').live('submit', function () {
var users = p4.users.sel.join(';');
if(users === '')
{
if (users === '') {
return false;
}
var $this = $(this);
var template = $('select[name="template_chooser"]', $this).val();
if(template === '')
{
if (template === '') {
return false;
}
@@ -313,20 +290,19 @@ $(document).ready(function(){
type: $this.attr('method'),
url: $this.attr('action'),
data: {
users : users,
template : template
users: users,
template: template
},
success: function(data){
success: function (data) {
$('#right-ajax').removeClass('loading').html(data);
}
});
return false;
});
$('#users_page_form .user_modifier').live('click', function(){
$('#users_page_form .user_modifier').live('click', function () {
var users = p4.users.sel.join(';');
if(users === '')
{
if (users === '') {
return false;
}
@@ -336,9 +312,9 @@ $(document).ready(function(){
type: 'POST',
url: '../admin/users/rights/',
data: {
users : users
users: users
},
success: function(data){
success: function (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(';');
if(users === '')
{
if (users === '') {
return false;
}
@@ -359,19 +334,18 @@ $(document).ready(function(){
type: 'POST',
url: '../admin/users/delete/',
data: {
users : users
users: users
},
success: function(data){
success: function (data) {
$('#right-ajax').removeClass('loading').html(data);
}
});
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();
if($.trim(users) === '')
{
if ($.trim(users) === '') {
return false;
}
@@ -381,9 +355,9 @@ $(document).ready(function(){
type: 'POST',
url: '../admin/users/rights/',
data: {
users : users
users: users
},
success: function(data){
success: function (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(){
if(typeof validator_loaded === 'boolean')
$(document).ready(function () {
if (typeof validator_loaded === 'boolean')
return;
$('.confirm_report').live('click',function(){
$('.confirm_report').live('click', function () {
var $this = $(this);
$('.loader', $this).css({
visibility:'visible'
visibility: 'visible'
});
$.ajax({
type: "POST",
url: "/lightbox/ajax/SET_RELEASE/" + $('#basket_validation_id').val() + "/",
dataType: 'json',
error: function(data) {
error: function (data) {
$('.loader', $this).css({
visibility: 'hidden'
});
},
timeout: function(data) {
timeout: function (data) {
$('.loader', $this).css({
visibility: 'hidden'
});
},
success: function(data) {
success: function (data) {
$('.loader', $this).css({
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 agreement = $('#' + $(this).attr('for')).val() == 'yes' ? '1' : '-1';
@@ -49,37 +48,34 @@ $(document).ready(function(){
$.ajax({
type: "POST",
url: "/lightbox/ajax/SET_ELEMENT_AGREEMENT/"+sselcont_id+"/",
url: "/lightbox/ajax/SET_ELEMENT_AGREEMENT/" + sselcont_id + "/",
dataType: 'json',
data: {
agreement : agreement
agreement: agreement
},
error: function(datas){
error: function (datas) {
alert('error');
$.mobile.loading();
},
timeout: function(datas){
timeout: function (datas) {
alert('error');
$.mobile.loading();
},
success: function(datas){
if(!datas.error)
{
if(agreement == '1')
$('.valid_choice_'+sselcont_id).removeClass('disagree').addClass('agree');
success: function (datas) {
if (!datas.error) {
if (agreement == '1')
$('.valid_choice_' + sselcont_id).removeClass('disagree').addClass('agree');
else
$('.valid_choice_'+sselcont_id).removeClass('agree').addClass('disagree');
$('.valid_choice_' + sselcont_id).removeClass('agree').addClass('disagree');
$.mobile.loading();
if(datas.error)
{
if (datas.error) {
alert(datas.datas);
return;
}
releasable = datas.release;
}
else
{
else {
alert(datas.datas);
}
return;
@@ -88,34 +84,33 @@ $(document).ready(function(){
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();
$.mobile.loading();
$.ajax({
type: "POST",
url: "/lightbox/ajax/SET_NOTE/"+sselcont_id+"/",
url: "/lightbox/ajax/SET_NOTE/" + sselcont_id + "/",
dataType: 'json',
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');
$.mobile.loading();
},
timeout: function(datas){
timeout: function (datas) {
alert('error');
$.mobile.loading();
},
success: function(datas){
success: function (datas) {
$.mobile.loading();
if(datas.error)
{
if (datas.error) {
alert(datas.datas);
return;
}
$('#notes_'+sselcont_id).empty().append(datas.datas);
$('#notes_' + sselcont_id).empty().append(datas.datas);
window.history.back();
return;
}

View File

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

View File

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

View File

@@ -2,36 +2,31 @@
var p4 = p4 || {};
;
(function(p4, $){
(function (p4, $) {
function getLevel (level) {
function getLevel(level) {
level = parseInt(level);
if(isNaN(level) || level < 1)
{
if (isNaN(level) || level < 1) {
return 1;
}
return level;
};
function getId (level)
{
function getId(level) {
return 'DIALOG' + getLevel(level);
};
function addButtons(buttons, dialog)
{
if(dialog.options.closeButton === true)
{
buttons[language.fermer] = function() {
function addButtons(buttons, dialog) {
if (dialog.options.closeButton === true) {
buttons[language.fermer] = function () {
dialog.Close();
};
}
if(dialog.options.cancelButton === true)
{
buttons[language.annuler] = function() {
if (dialog.options.cancelButton === true) {
buttons[language.annuler] = function () {
dialog.Close();
};
}
@@ -41,12 +36,11 @@ var p4 = p4 || {};
var phraseaDialog = function (options, level) {
var createDialog = function(level) {
var createDialog = function (level) {
var $dialog = $('#' + getId(level));
if($dialog.length > 0)
{
if ($dialog.length > 0) {
throw 'Dialog already exists at this level';
}
@@ -57,15 +51,15 @@ var p4 = p4 || {};
};
var defaults = {
size : 'Medium',
buttons : {},
loading : true,
title : '',
closeOnEscape : true,
confirmExit:false,
closeCallback:false,
closeButton:false,
cancelButton:false
size: 'Medium',
buttons: {},
loading: true,
title: '',
closeOnEscape: true,
confirmExit: false,
closeCallback: false,
closeButton: false,
cancelButton: false
},
options = typeof options === 'object' ? options : {},
width,
@@ -81,11 +75,10 @@ var p4 = p4 || {};
this.options.buttons = addButtons(this.options.buttons, this);
switch(this.options.size)
{
switch (this.options.size) {
case 'Full':
height = bodySize.y - 30;
width = bodySize.x - 30 ;
width = bodySize.x - 30;
break;
case 'Medium':
width = Math.min(bodySize.x - 30, 730);
@@ -113,14 +106,12 @@ var p4 = p4 || {};
this.$dialog = createDialog(this.level),
zIndex = Math.min(this.level * 5000 + 5000, 32767);
var CloseCallback = function() {
if(typeof $this.options.closeCallback === 'function')
{
var CloseCallback = function () {
if (typeof $this.options.closeCallback === 'function') {
$this.options.closeCallback($this.$dialog);
}
if($this.closing === false)
{
if ($this.closing === false) {
$this.closing = true;
$this.Close();
}
@@ -133,34 +124,32 @@ var p4 = p4 || {};
this.$dialog.attr('title', this.options.title)
.empty()
.dialog({
buttons:this.options.buttons,
draggable:false,
resizable:false,
closeOnEscape:this.options.closeOnEscape,
modal:true,
width:width,
height:height,
open: function() {
buttons: this.options.buttons,
draggable: false,
resizable: false,
closeOnEscape: this.options.closeOnEscape,
modal: true,
width: width,
height: height,
open: function () {
$(this).dialog("widget").css("z-index", zIndex);
},
close:CloseCallback
close: CloseCallback
})
.dialog('open').addClass('dialog-' + this.options.size);
if(this.options.loading === true)
{
if (this.options.loading === true) {
this.$dialog.addClass('loading');
}
if(this.options.size === 'Full')
{
if (this.options.size === 'Full') {
var $this = this;
$(window).unbind('resize.DIALOG' + getLevel(level))
.bind('resize.DIALOG' + getLevel(level), function(){
.bind('resize.DIALOG' + getLevel(level), function () {
if ($this.$dialog.data("ui-dialog")) {
$this.$dialog.dialog('option', {
width : bodySize.x - 30,
height : bodySize.y - 30
width: bodySize.x - 30,
height: bodySize.y - 30
});
}
});
@@ -170,61 +159,59 @@ var p4 = p4 || {};
};
phraseaDialog.prototype = {
Close : function() {
Close: function () {
p4.Dialog.Close(this.level);
},
setContent : function (content) {
setContent: function (content) {
this.$dialog.removeClass('loading').empty().append(content);
},
getId : function () {
getId: function () {
return this.$dialog.attr('id');
},
load : function(url, method, params) {
load: function (url, method, params) {
var $this = this;
this.loader = {
url : url,
method : typeof method === 'undefined' ? 'GET' : method,
params : typeof params === 'undefined' ? {} : params
url: url,
method: typeof method === 'undefined' ? 'GET' : method,
params: typeof params === 'undefined' ? {} : params
};
$.ajax({
type: this.loader.method,
url: this.loader.url,
dataType: 'html',
data : this.loader.params,
beforeSend:function(){
data: this.loader.params,
beforeSend: function () {
},
success: function(data){
success: function (data) {
$this.setContent(data);
return;
},
error: function(){
error: function () {
return;
},
timeout: function(){
timeout: function () {
return;
}
});
},
refresh : function() {
if(typeof this.loader === 'undefined')
{
refresh: function () {
if (typeof this.loader === 'undefined') {
throw 'Nothing to refresh';
}
this.load(this.loader.url, this.loader.method, this.loader.params);
},
getDomElement : function () {
getDomElement: function () {
return this.$dialog;
},
getOption : function (optionName) {
getOption: function (optionName) {
if (this.$dialog.data("ui-dialog")) {
return this.$dialog.dialog('option', optionName);
}
return null;
},
setOption : function (optionName, optionValue) {
if(optionName === 'buttons')
{
setOption: function (optionName, optionValue) {
if (optionName === 'buttons') {
optionValue = addButtons(optionValue, this);
}
if (this.$dialog.data("ui-dialog")) {
@@ -238,10 +225,9 @@ var p4 = p4 || {};
};
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();
}
@@ -251,18 +237,17 @@ var p4 = p4 || {};
return $dialog;
},
get : function (level) {
get: function (level) {
var id = getId(level);
if(id in this.currentStack)
{
if (id in this.currentStack) {
return this.currentStack[id];
}
return null;
},
Close : function (level) {
Close: function (level) {
$(window).unbind('resize.DIALOG' + getLevel(level));
@@ -275,8 +260,7 @@ var p4 = p4 || {};
var id = this.get(level).getId();
if(id in this.currentStack)
{
if (id in this.currentStack) {
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.Context = context;
@@ -10,23 +9,23 @@
this.selection = new Selectable(
$('.user_content .badges', this.container),
{
selector:'.badge'
selector: '.badge'
}
);
var $this = this;
$('.content .options .select-all', this.container).bind('click', function(){
$('.content .options .select-all', this.container).bind('click', function () {
$this.selection.selectAll();
});
$('.content .options .unselect-all', this.container).bind('click', function(){
$('.content .options .unselect-all', this.container).bind('click', function () {
$this.selection.empty();
});
$('.UserTips', this.container).tooltip();
$('a.user_adder', this.container).bind('click', function(){
$('a.user_adder', this.container).bind('click', function () {
var $this = $(this);
@@ -34,22 +33,22 @@
type: "GET",
url: $this.attr('href'),
dataType: 'html',
beforeSend:function(){
beforeSend: function () {
var options = {
size : 'Medium',
title : $this.html()
size: 'Medium',
title: $this.html()
};
p4.Dialog.Create(options, 2).getDomElement().addClass('loading');
},
success: function(data){
success: function (data) {
p4.Dialog.get(2).getDomElement().removeClass('loading').empty().append(data);
return;
},
error: function(){
error: function () {
p4.Dialog.get(2).Close();
return;
},
timeout: function(){
timeout: function () {
p4.Dialog.get(2).Close();
return;
}
@@ -58,7 +57,7 @@
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();
@@ -67,19 +66,19 @@
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 options = {
size : 'Small',
title : $(this).attr('title')
size: 'Small',
title: $(this).attr('title')
};
$dialog = p4.Dialog.Create(options, 2);
$dialog.setContent(content);
$dialog.getDomElement().find('a.adder').bind('click', function(){
$dialog.getDomElement().find('a.adder').bind('click', function () {
$(this).addClass('added');
@@ -90,24 +89,21 @@
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();
if($('.badge_' + usr_id, $this.container).length > 0)
{
if ($('.badge_' + usr_id, $this.container).length > 0) {
$(this).addClass('added');
}
});
return false;
});
$('#PushBox form[name="FeedBackForm"]').bind('submit', function(){
$('#PushBox form[name="FeedBackForm"]').bind('submit', function () {
var $this = $(this);
@@ -116,27 +112,25 @@
url: $this.attr('action'),
dataType: 'json',
data: $this.serializeArray(),
beforeSend:function(){
beforeSend: function () {
},
success: function(data){
if(data.success)
{
success: function (data) {
if (data.success) {
humane.info(data.message);
p4.Dialog.Close(1);
p4.WorkZone.refresh();
}
else
{
else {
humane.error(data.message);
}
return;
},
error: function(){
error: function () {
return;
},
timeout: function(){
timeout: function () {
return;
}
@@ -145,21 +139,20 @@
return false;
});
$('.FeedbackSend', this.container).bind('click', function(){
if($('.badges .badge', $container).length === 0)
{
$('.FeedbackSend', this.container).bind('click', function () {
if ($('.badges .badge', $container).length === 0) {
alert(language.FeedBackNoUsersSelected);
return;
}
var buttons = {};
buttons[language.send] = function(){
buttons[language.send] = function () {
if ($.trim($('input[name="name"]', $dialog.getDomElement()).val()) === '') {
options = {
size : 'Alert',
closeButton : true,
title : language.warning
size: 'Alert',
closeButton: true,
title: language.warning
},
$dialog = p4.Dialog.Create(options, 3);
$dialog.setContent(language.FeedBackNameMandatory);
@@ -178,12 +171,12 @@
};
var options = {
size : 'Small',
buttons : buttons,
loading : true,
title : language.send,
closeOnEscape : true,
cancelButton : true
size: 'Small',
buttons: buttons,
loading: true,
title: language.send,
closeOnEscape: true,
cancelButton: true
};
var $dialog = p4.Dialog.Create(options, 2);
@@ -198,14 +191,14 @@
$('textarea[name="message"]', $dialog.getDomElement()).val($('textarea[name="message"]', $FeedBackForm).val());
$('.' + $this.Context, $dialog.getDomElement()).show();
$('form', $dialog.getDomElement()).submit(function() {
$('form', $dialog.getDomElement()).submit(function () {
return false;
});
});
$('.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);
@@ -216,19 +209,17 @@
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 $badges = $('.user_content .badge.selected', this.container);
var toggles = $('.status_off.toggle_' + feature, $badges);
if(toggles.length === 0)
{
if (toggles.length === 0) {
var toggles = $('.status_on.toggle_' + feature, $badges);
}
if(toggles.length === 0)
{
if (toggles.length === 0) {
humane.info('No user selected');
}
@@ -236,26 +227,25 @@
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');
$elem.fadeOut(function(){
$elem.fadeOut(function () {
$elem.remove();
});
return;
});
$('.list_manager', this.container).bind('click', function(){
$('.list_manager', this.container).bind('click', function () {
$('#PushBox').hide();
$('#ListManager').show();
return false;
});
$('a.list_loader', this.container).bind('click', function(){
$('a.list_loader', this.container).bind('click', function () {
var url = $(this).attr('href');
var callbackList = function(list){
for(var i in list.entries)
{
var callbackList = function (list) {
for (var i in list.entries) {
this.selectUser(list.entries[i].User);
}
};
@@ -267,19 +257,18 @@
$('.options button', this.container);
$('form.list_saver', this.container).bind('submit', function(){
$('form.list_saver', this.container).bind('submit', function () {
var $form = $(this);
var $input = $('input[name="name"]', $form);
var users = p4.Feedback.getUsers();
if(users.length === 0)
{
if (users.length === 0) {
humane.error('No users');
return false;
}
p4.Lists.create($input.val(), function(list){
p4.Lists.create($input.val(), function (list) {
$input.val('');
list.addUsers(users);
});
@@ -289,68 +278,64 @@
$('input[name="users-search"]', this.container).autocomplete({
minLength: 2,
source: function( request, response ) {
source: function (request, response) {
$.ajax({
url: '/prod/push/search-user/',
dataType: "json",
data: {
query: request.term
},
success: function( data ) {
success: function (data) {
response(data);
}
});
},
focus: function( event, ui ) {
$( 'input[name="users-search"]' ).val( ui.item.label );
focus: function (event, ui) {
$('input[name="users-search"]').val(ui.item.label);
},
select: function( event, ui ) {
if(ui.item.type === 'USER') {
select: function (event, ui) {
if (ui.item.type === 'USER') {
$this.selectUser(ui.item);
} else if(ui.item.type === 'LIST') {
for(var e in ui.item.entries) {
} else if (ui.item.type === 'LIST') {
for (var e in ui.item.entries) {
$this.selectUser(ui.item.entries[e].User);
}
}
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
.data("ui-autocomplete")._renderItem = function (ul, item) {
var html = "";
if(item.type === 'USER') {
if (item.type === 'USER') {
html = _.template($("#list_user_tpl").html(), {
item: item
});
} else if(item.type === 'LIST') {
} else if (item.type === 'LIST') {
html = _.template($("#list_list_tpl").html(), {
item: item
});
}
return $(html).data( "ui-autocomplete-item", item ).appendTo(ul);
return $(html).data("ui-autocomplete-item", item).appendTo(ul);
};
return this;
};
Feedback.prototype = {
selectUser : function(user){
if(typeof user !== 'object')
{
if(window.console)
{
selectUser: function (user) {
if (typeof user !== 'object') {
if (window.console) {
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');
return;
}
if(window.console)
{
if (window.console) {
console.log('Selecting', user);
}
@@ -360,7 +345,7 @@
p4.Feedback.appendBadge(html);
},
loadUser : function(usr_id, callback) {
loadUser: function (usr_id, callback) {
var $this = this;
$.ajax({
@@ -368,35 +353,33 @@
url: '/prod/push/user/' + usr_id + '/',
dataType: 'json',
data: {
usr_id : usr_id
usr_id: usr_id
},
success: function(data){
if(typeof callback === 'function')
{
success: function (data) {
if (typeof callback === 'function') {
callback.call($this, data);
}
}
});
},
loadList : function(url, callback) {
loadList: function (url, callback) {
var $this = this;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data){
if(typeof callback === 'function')
{
success: function (data) {
if (typeof callback === 'function') {
callback.call($this, data);
}
}
});
},
appendBadge : function(badge){
appendBadge: function (badge) {
$('.user_content .badges', this.container).append(badge);
},
addUser : function($form, callback){
addUser: function ($form, callback) {
var $this = this;
@@ -405,50 +388,47 @@
url: '/prod/push/add-user/',
dataType: 'json',
data: $form.serializeArray(),
success: function(data){
if(data.success)
{
success: function (data) {
if (data.success) {
humane.info(data.message);
$this.selectUser(data.user);
callback();
}
else
{
else {
humane.error(data.message);
}
}
});
},
getSelection : function() {
getSelection: function () {
return this.selection;
},
getUsers : function() {
return $('.user_content .badge', this.container).map(function(){
getUsers: function () {
return $('.user_content .badge', this.container).map(function () {
return $('input[name="id"]', $(this)).val();
});
}
};
var ListManager = function($container) {
var ListManager = function ($container) {
this.list = null;
this.container = $container;
$('.back_link', this.container).bind('click', function(){
$('.back_link', this.container).bind('click', function () {
$('#PushBox').show();
$('#ListManager').hide();
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),
options = {
size : 'Small',
closeButton : true,
title : $this.attr('title')
size: 'Small',
closeButton: true,
title: $this.attr('title')
},
$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);
@@ -466,21 +446,22 @@
type: "GET",
url: $this.attr('href'),
dataType: 'html',
beforeSend:function(){
beforeSend: function () {
var options = {
size : 'Medium',
title : $this.html()
size: 'Medium',
title: $this.html()
};
p4.Dialog.Create(options, 2).getDomElement().addClass('loading'); },
success: function(data){
p4.Dialog.Create(options, 2).getDomElement().addClass('loading');
},
success: function (data) {
p4.Dialog.get(2).getDomElement().removeClass('loading').empty().append(data);
return;
},
error: function(){
error: function () {
p4.Dialog.get(2).Close();
return;
},
timeout: function(){
timeout: function () {
p4.Dialog.get(2).Close();
return;
}
@@ -490,11 +471,10 @@
});
var initLeft = function () {
$('a.list_refresh', $container).bind('click', function (event) {
var initLeft = function() {
$('a.list_refresh', $container).bind('click', function(event){
var callback = function(datas){
var callback = function (datas) {
$('.all-lists', $container).removeClass('loading').append(datas);
initLeft();
};
@@ -506,13 +486,13 @@
return false;
});
$('a.list_adder', $container).bind('click', function(event){
$('a.list_adder', $container).bind('click', function (event) {
var makeDialog = function (box) {
var buttons = {};
buttons[language.valider] = function() {
buttons[language.valider] = function () {
var callbackOK = function () {
$('a.list_refresh', $container).trigger('click');
@@ -521,8 +501,7 @@
var name = $('input[name="name"]', p4.Dialog.get(2).getDomElement()).val();
if($.trim(name) === '')
{
if ($.trim(name) === '') {
alert(language.listNameCannotBeEmpty);
return;
}
@@ -531,9 +510,9 @@
};
var options = {
cancelButton : true,
buttons : buttons,
size:'Alert'
cancelButton: true,
buttons: buttons,
size: 'Alert'
};
p4.Dialog.Create(options, 2).setContent(box);
@@ -546,7 +525,7 @@
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);
@@ -557,11 +536,11 @@
type: 'GET',
url: $this.attr('href'),
dataType: 'html',
success: function(data){
success: function (data) {
$('.editor', $container).removeClass('loading').append(data);
initRight();
},
beforeSend: function(){
beforeSend: function () {
$('.editor', $container).empty().addClass('loading');
}
});
@@ -570,11 +549,11 @@
});
};
var initRight = function(){
var initRight = function () {
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 dest = $('.list-editor-results', $container);
@@ -584,10 +563,10 @@
type: $this.attr('method'),
dataType: "html",
data: $this.serializeArray(),
beforeSend : function () {
beforeSend: function () {
dest.empty().addClass('loading');
},
success: function( datas ) {
success: function (datas) {
dest.empty().removeClass('loading').append(datas);
}
@@ -595,20 +574,20 @@
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');
});
$('.EditToggle', $container).bind('click', function(){
$('.EditToggle', $container).bind('click', function () {
$('.content.readonly, .content.readwrite', $('#ListManager')).toggle();
return false;
});
$('.Refresher', $container).bind('click', function(){
$('.Refresher', $container).bind('click', function () {
$('#ListManager ul.lists .list.selected a').trigger('click');
return false;
});
$('form[name="SaveName"]', $container).bind('submit', function(){
$('form[name="SaveName"]', $container).bind('submit', function () {
var $this = $(this);
$.ajax({
@@ -616,26 +595,24 @@
url: $this.attr('action'),
dataType: 'json',
data: $this.serializeArray(),
beforeSend:function(){
beforeSend: function () {
},
success: function(data){
if(data.success)
{
success: function (data) {
if (data.success) {
humane.info(data.message);
$('#ListManager .lists .list_refresh').trigger('click');
}
else
{
else {
humane.error(data.message);
}
return;
},
error: function(){
error: function () {
return;
},
timeout: function(){
timeout: function () {
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();
@@ -653,7 +630,7 @@
var buttons = {};
buttons[language.valider] = function() {
buttons[language.valider] = function () {
var callbackOK = function () {
$('#ListManager .all-lists a.list_refresh').trigger('click');
@@ -665,9 +642,9 @@
};
var options = {
cancelButton : true,
buttons : buttons,
size:'Alert'
cancelButton: true,
buttons: buttons,
size: 'Alert'
};
p4.Dialog.Create(options, 2).setContent(box);
@@ -683,15 +660,15 @@
initLeft();
$('.badges a.deleter', this.container).live('click', function(){
$('.badges a.deleter', this.container).live('click', function () {
var badge = $(this).closest('.badge');
var usr_id = badge.find('input[name="id"]').val();
var callback = function(list, datas){
$('.counter.current, .list.selected .counter', $('#ListManager')).each(function(){
var callback = function (list, datas) {
$('.counter.current, .list.selected .counter', $('#ListManager')).each(function () {
$(this).text(parseInt($(this).text()) - 1);
});
@@ -706,19 +683,18 @@
};
ListManager.prototype = {
workOn : function(list_id) {
workOn: function (list_id) {
this.list = new document.List(list_id);
},
getList : function(){
getList: function () {
return this.list;
},
appendBadge : function(datas) {
appendBadge: function (datas) {
$('#ListManager .badges').append(datas);
}
};
window.Feedback = Feedback;
window.ListManager = ListManager;

View File

@@ -1,9 +1,9 @@
(function() {
$(document).ready(function() {
(function () {
$(document).ready(function () {
humane.info = humane.spawn({addnCls: 'humane-libnotify-info', 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';
if ($this.hasClass('small-dialog')) {
@@ -25,7 +25,7 @@
type: "GET",
url: $this.attr('href'),
dataType: 'html',
success: function(data) {
success: function (data) {
$dialog.setContent(data);
return;
}

View File

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

View File

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

View File

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

View File

@@ -1,46 +1,39 @@
//////////////////////////////////////////////////////////////////////////////
// sprintf function for javascript
function sprintf()
{
if (!arguments || arguments.length < 1 || !RegExp)
{
function sprintf() {
if (!arguments || arguments.length < 1 || !RegExp) {
return '';
}
str = arguments[0];
while((newstr = str.replace("\n", "\x01")) != str)
while ((newstr = str.replace("\n", "\x01")) != str)
str = newstr;
// 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");
re["$*"] = true;
var a = b = [], numSubstitutions = 0, numMatches = 0;
a = re.exec(str);
while (a)
{
while (a) {
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);
if (pType == '%')
{
if (pType == '%') {
subst = '%';
}
else
{
else {
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).');
}
var param = arguments[numSubstitutions];
var pad = '';
if (pPad && pPad.substr(0,1) == "'")
{
pad = leftpart.substr(1,1);
if (pPad && pPad.substr(0, 1) == "'") {
pad = leftpart.substr(1, 1);
}
else if (pPad)
{
else if (pPad) {
pad = pPad;
}
var justifyRight = true;
@@ -50,13 +43,11 @@ function sprintf()
if (pMinLength)
minLength = parseInt(pMinLength);
var precision = -1;
if (pPrecision && pType == 'f')
{
if (pPrecision && pType == 'f') {
precision = parseInt(pPrecision.substring(1));
}
var subst = param;
switch (pType)
{
switch (pType) {
case 'b':
subst = parseInt(param).toString(2);
break;
@@ -64,7 +55,7 @@ function sprintf()
subst = String.fromCharCode(parseInt(param));
break;
case 'd':
subst = parseInt(param)? parseInt(param) : 0;
subst = parseInt(param) ? parseInt(param) : 0;
break;
case 'u':
subst = Math.abs(param);
@@ -89,20 +80,18 @@ function sprintf()
}
var padLeft = minLength - subst.toString().length;
var padding;
if (padLeft > 0)
{
var arrTmp = new Array(padLeft+1);
padding = arrTmp.join(pad?pad:" ");
if (padLeft > 0) {
var arrTmp = new Array(padLeft + 1);
padding = arrTmp.join(pad ? pad : " ");
}
else
{
else {
padding = "";
}
}
str = leftpart + padding + subst + rightPart;
a = re.exec(str);
}
while((newstr = str.replace("\x01", "\n")) != str)
while ((newstr = str.replace("\x01", "\n")) != str)
str = newstr;
return(str);
}

View File

@@ -1,26 +1,21 @@
function loadXMLDoc(url, post_parms, asxml)
{
if(typeof(asxml)=="undefined")
function loadXMLDoc(url, post_parms, asxml) {
if (typeof(asxml) == "undefined")
asxml = false;
out = null;
xmlhttp = null;
// code for Mozilla, etc.
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
// xmlhttp.onreadystatechange=state_Change
if(post_parms)
{
if (post_parms) {
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);
}
else
{
else {
xmlhttp.open("GET", url, false);
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 ret = 0;
var thb = branch.firstChild.nextSibling.nextSibling;
// 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;
// alert(branch.firstChild.nextSibling.nodeValue + " : " + thb.id);
}
@@ -56,13 +48,11 @@ function showFound2(term, lterm, branch, depth)
// if(ret > 0)
// if(depth > 0)
// {
if(ret > 0)
{
if (ret > 0) {
//eventObj.Src0.innerHTML = "+";
thb.className = "OB";
}
else
{
else {
//eventObj.Src0.innerHTML = "+";
thb.className = "ob";
}
@@ -81,24 +71,20 @@ function showFound2(term, lterm, branch, depth)
return(ret);
}
function showAll(branch, depth)
{
function showAll(branch, depth) {
depth = parseInt(depth);
var c;
for(c=branch.firstChild; c; c=c.nextSibling)
{
if(c.nodeType==1 && c.nodeName=="DIV") // 1=XML_ELEMENT_NODE
showAll(c, depth+1);
for (c = branch.firstChild; c; c = c.nextSibling) {
if (c.nodeType == 1 && c.nodeName == "DIV") // 1=XML_ELEMENT_NODE
showAll(c, depth + 1);
}
if(depth > 0)
if (depth > 0)
branch.style.display = "";
if(depth===0)
{
document.getElementById("WT1").style.visibility="hidden";
if(document.forms["fTh"].textT1.value!=="")
{
if (depth === 0) {
document.getElementById("WT1").style.visibility = "hidden";
if (document.forms["fTh"].textT1.value !== "") {
// oups! le mot a changé durant le traitement, on recommence
evt_kup_T1();
}
@@ -106,33 +92,28 @@ function showAll(branch, depth)
}
function scanTerms(inputName, zTerm, showhide)
{
function scanTerms(inputName, zTerm, showhide) {
showhide = !!showhide;
var lTerm = zTerm.length;
var zTable = document.getElementById("L"+inputName);
var zTable = document.getElementById("L" + inputName);
var zTr = zTable.childNodes; // TR's
var l = zTr.length;
var found = null;
for(var i=0; i<l; i++)
{
for (var i = 0; i < l; i++) {
// if(renum)
// zTr[i].id = inputName+"_"+i
var t = zTr[i].firstChild.firstChild.nodeValue;
// alert(i+" "+t);
if(zTerm == t)
if (zTerm == t)
found = zTr[i];
if(showhide === true)
{
if(lTerm==0 || (t.substr(0, lTerm)==zTerm))
if (showhide === true) {
if (lTerm == 0 || (t.substr(0, lTerm) == zTerm))
zTr[i].style.display = "";
else
zTr[i].style.display = "none";
}
else
{
else {
zTr[i].style.display = "";
}
}
@@ -141,8 +122,8 @@ function scanTerms(inputName, zTerm, showhide)
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
zTerm = document.forms["fTh"]["text"+inputName].value;
if (typeof(zTerm) == "undefined") // si pas de terme en argument, prendre dans la zone de saisie
zTerm = document.forms["fTh"]["text" + inputName].value;
// alert(zTerm);
// on cherche si le zTerm existe déjà
// 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
var found = scanTerms(inputName, zTerm, false); // tout afficher
if(!found)
{
if (!found) {
// on cherche la div "thb" si elle existe
var thb, thRef;
for(thb=selectedThesaurusItem.firstChild; thb; thb=thb.nextSibling)
{
if(thb.nodeType==1 && thb.tagName=="DIV" && thb.id.substr(0,4)=="THB_")
for (thb = selectedThesaurusItem.firstChild; thb; thb = thb.nextSibling) {
if (thb.nodeType == 1 && thb.tagName == "DIV" && thb.id.substr(0, 4) == "THB_")
break;
}
if(!thb)
{
if (!thb) {
// on ajoute le premier fils ...
// ... on crée le +/- en face du terme
selectedThesaurusItem.firstChild.className = "tri";
@@ -174,27 +152,25 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
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
var nextid = parseInt(selectedThesaurusItem.getAttribute("nextid"));
// 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
var div = document.createElement("DIV");
div.className = "s_";
if(selectedThesaurusItem.id == "THE_")
if (selectedThesaurusItem.id == "THE_")
div.id = "THE_" + nextid;
else
div.id = selectedThesaurusItem.id + "." + nextid;
if(typeof(oldid)=="undefined")
{
if (typeof(oldid) == "undefined") {
// div.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.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.appendChild(document.createTextNode(zTerm));
thRef = thb.appendChild(p);
nextid = document.getElementById("L"+inputName).nextid++;
nextid = document.getElementById("L" + inputName).nextid++;
}
// 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
document.forms["fTh"]["text"+inputName].value = "";
document.forms["fTh"]["text" + inputName].value = "";
termChanged = true;
@@ -235,8 +211,7 @@ function addTerm(inputName, zTerm, oldid) // inputName = "TS"|"TA"|"SY"
evt_kup(inputName);
}
function dirty()
{
function dirty() {
thesaurusChanged = true;
document.getElementById("saveButton").style.display = "";
}
@@ -363,60 +338,50 @@ function dirty()
}
*/
// supprime un terme et tous ses fils (deplace 'e plat') dans '(deleted)'
function deleteBranch(the, thb_deleted)
{
if(the.id.substr(0,4)=="THE_")
{
var d = thb_deleted.appendChild(document.createElement("DIV") );
function deleteBranch(the, thb_deleted) {
if (the.id.substr(0, 4) == "THE_") {
var d = thb_deleted.appendChild(document.createElement("DIV"));
d.className = "s_ R_";
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) );
d.appendChild(the.firstChild.nextSibling.cloneNode(false) );
d.setAttribute("oldid", the.oldid ? the.oldid : the.id.substr(4) );
if(the.firstChild.nextSibling.nextSibling)
{
for(var the=the.firstChild.nextSibling.nextSibling.firstChild; the; the=the.nextSibling)
{
thb_deleted.parentNode.setAttribute("nextid", parseInt(thb_deleted.parentNode.getAttribute("nextid") + 1));
d.appendChild(the.firstChild.nextSibling.cloneNode(false));
d.setAttribute("oldid", the.oldid ? the.oldid : the.id.substr(4));
if (the.firstChild.nextSibling.nextSibling) {
for (var the = the.firstChild.nextSibling.nextSibling.firstChild; the; the = the.nextSibling) {
deleteBranch(the, thb_deleted);
}
}
}
}
function alertNode(n, msg)
{
if(typeof(msg)=="undefined")
function alertNode(n, msg) {
if (typeof(msg) == "undefined")
msg = "";
if(n)
{
if(n.nodeType==1)
{
alert(msg + " : <"+n.nodeName+" id='"+n.id+"'>");
if (n) {
if (n.nodeType == 1) {
alert(msg + " : <" + n.nodeName + " id='" + n.id + "'>");
}
else
{
alert(msg + " : nodeType="+n.nodeType);
else {
alert(msg + " : nodeType=" + n.nodeType);
}
}
else
{
else {
alert(msg + " : NULL");
}
}
function appendTerm(inputName, new_term, id)
{
function appendTerm(inputName, new_term, id) {
var tr = document.createElement("TR");
tr.id = inputName + "_"+id;
tr.id = inputName + "_" + id;
tr.className = "s_";
var td = tr.appendChild(document.createElement("TD"));
td.appendChild(document.createTextNode(new_term));
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.appendChild(document.createTextNode(" "));
var zTable = document.getElementById("L"+inputName);
var zTable = document.getElementById("L" + inputName);
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)
{
if(typeof(asxml)=="undefined")
function loadXMLDoc(url, post_parms, asxml) {
if (typeof(asxml) == "undefined")
asxml = false;
out = null;
xmlhttp = null;
// code for Mozilla, etc.
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp)
{
if (xmlhttp) {
// xmlhttp.onreadystatechange=state_Change
if(post_parms)
{
if (post_parms) {
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);
}
else
{
else {
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
}