/**
 * @author raph
 */

var gomNs = {
    minYear: -5000,
    maxYear: 2010,
    tlPixels: 960,
    tlGamma: 6,
    heatGamma: 2,
    displayedDates: [ -5000, 0, 500, 1000, 1200, 1400, 1600, 1700, 1750, 1800, 1850, 1900, 1950, 2010 ],
    mappingLibrary: 'leaflet',
    gradientStart: [ 255, 255, 240 ],
    gradientEnd: [ 255, 160, 30 ],
    zeroColor: [ 230, 230, 235 ],
    languageCode: 'fr'
}

function yearToPx(year) {
    return gomNs.tlPixels * Math.pow( ( year - gomNs.minYear ) / ( gomNs.maxYear - gomNs.minYear ), gomNs.tlGamma );
}

function pxToYear(px) {
    return gomNs.minYear + ( gomNs.maxYear - gomNs.minYear ) * Math.pow( px / gomNs.tlPixels, 1 / gomNs.tlGamma );
}

function getGradient(_pos) {
    if (_pos == 0) {
        var _rgb = gomNs.zeroColor;
    } else {
        var _rgb = [],
            _exp = Math.pow(_pos, 1/gomNs.heatGamma);
        for (var i=0; i<3; i++) {
            _rgb.push(Math.floor(_exp*gomNs.gradientEnd[i] + (1-_exp)*gomNs.gradientStart[i]));
        }
    }
    return "rgb(" + _rgb.join(",") + ")"
}

function polygon_to_gmap(polycoords, dbpedia_uri) {
    var _opts =  {
        strokeColor: "#000000",
        strokeWeight: .5,
        fillColor: "rgb(" + gomNs.zeroColor.join(",") + ")",
        fillOpacity: 1
    }
    _opts.paths = polycoords.map(function(path) {
        return path.map(function(coord) {
            return new google.maps.LatLng(coord[1], coord[0]);
        });
    });
    var _polygon = new google.maps.Polygon(_opts);
    _polygon.setMap(gomNs.map);
    google.maps.event.addListener(_polygon, 'click', function(a,b) {
        addFilter('country', dbpedia_uri);
    })
    return _polygon;
}

function showCountriesGmap(geoJson) {
    gomNs.countries = {};
    _(geoJson.features).each(function(feature) {
        var _el = { "properties" : feature.properties };
        if (feature.id == 'ATA') {
            _el.gPolygons = [];
        } else {
            switch(feature.geometry.type) {
                case('Polygon'):
                    _el.gPolygons = [ polygon_to_gmap(feature.geometry.coordinates, feature.properties.dbpedia_uri) ];
                break;
                case('MultiPolygon'):
                    _el.gPolygons = feature.geometry.coordinates.map(function(polygon) {
                        return polygon_to_gmap(polygon, feature.properties.dbpedia_uri);
                    })
                break;
            }
        }
        gomNs.countries[feature.properties.dbpedia_uri] = _el;
    });
}

function showCountriesLeaflet(geoJson) {
    gomNs.countries = {};
    var gJ = new L.GeoJSON();
    gJ.on('featureparse', function(_f) {
        var isocode = _f.id;
        _f.layer.setStyle({
            color: "#000000",
            weight: .5,
            fillOpacity: 1,
            fillColor: "rgb(" + gomNs.zeroColor.join(",") + ")"
        });
        _f.layer.on('click', function() {
            addFilter('country', _f.properties.dbpedia_uri);
        });
        gomNs.countries[_f.properties.dbpedia_uri] = {
            "properties" : _f.properties,
            "layer" : _f.layer
        }
    });
    gJ.addGeoJSON(geoJson);
    gomNs.map.addLayer(gJ);
}


function tagInfo(_taglabel) {
    var _urlParam = { "label": _taglabel };
    $.getJSON(gomNs.urls['tag_info'],
        _urlParam,
        function(data) {
            $("#tagsearch").val(data.translated_label).removeClass("grise");
            $("#tagcount").html(data.content_count
                + ' ' + ngettext("contenu", "contenus", data.content_count) + ' '+gettext("pour ce tag"));
            var _html = '';
            if (data.wikipedia_url) {
                _html += '<h3><a href="'
                    + data.wikipedia_url
                    + '" target="_blank">Wikipedia: '
                    + decodeURI(data.wikipedia_url.match(/[^\/]+$/)[0]).replace("_"," ")
                    + '</a></h3>'
            }
            if (data.thumbnail) {
                _html += '<img id="img_wikipedia" src="'
                    + data.thumbnail
                    + '" />';
            }
            if (data.translated_abstract) {
                _html += '<p>' + _(data.translated_abstract).escape().replace(/(^.{0,240})([\s]|$)(.*)/,'$1&hellip;') + '</p>';
            }
/*            if (data.links) {
                var _lC = data.requested_label.toLowerCase();
                var _t = data.links.map(function(d) {
                    return (d.subject.toLowerCase() == _lC) ? d.object : d.subject;
                });
                _t.sort();
                _t = _(_t).uniq(true);
                _html += '<h3>Tags liés (dbpedia)</h3><ul class="content-tags">'
                    + _t.map(function(d) {
                        return '<li class="content-tag-item"><a href="#" onclick="tagInfo($(this).text()); return false;">'
                            + d
                            + '</a></li>';
                    }).join('')
                    + '</ul>';
            } */
            $("#tagdata").html(_html);
        });
    addFilter('tag', _taglabel);
    $("#showlist").removeClass("actif");
}

function addFilter(_type, _label) {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
    	if (_curView[_type].indexOf(_label) < 0) {
        	_curView[_type].push(_label);
    	}
        updateFilters();
        debouncedSaveChanges();
    }
}

function removeFilter(_type, _index) {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
        _curView[_type].splice(_index,1);
        updateFilters();
        debouncedSaveChanges();
    }
}

function getUpdates() {
    var _params = {},
        _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
        if (!(_curView.period[0] == gomNs.minYear && _curView.period[1] == gomNs.maxYear)) {
            _params.period = _curView.period.join(',');
        }
        if (_curView.tag.length) {
            _params.label = _curView.tag.join(',');
        }
        if (_curView.country.length) {
            _params.country = _curView.country.join(',');
        }
        $.getJSON(gomNs.urls['filter'], _params, updateDisplay);
        animLoad();
    }
}

var debouncedGetUpdates = _.debounce(getUpdates, 300);

function updatePeriod(_n, _val) {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
        var _int = parseInt(_val);
        if (_int != NaN) {
            if ((_n == 1 && _val >= _curView.period[0]) || (_n == 0 && _val <= _curView.period[1])) {
                _curView.period[_n] = _int;
            }
            updateFilters();
            debouncedSaveChanges();
        }
    }
}

function removePeriod() {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
        _curView.period[0] = gomNs.minYear;
        _curView.period[1] = gomNs.maxYear;
        updateFilters();
        debouncedSaveChanges();
    }
}

function changeSpan(_this) {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
        if (!$(_this).children().length) {
            var _el = document.createElement('input'),
                _n = _this.id.split('_')[1];
            _el.value = _curView.period[_n];
            _el.style.width = $(_this).width() + 'px';
            $(_el).focusout(function() {
                updatePeriod(_n, this.value);
            }).keypress(function(e) {
                if (e.keyCode == 13) {
                    updatePeriod(_n, this.value);
                }
            });
            $(_this).html(_el);
            _el.focus();
            _el.select();
        }
    }
}

function updateFilters() {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type != 'filter') {
        return;
    }
    var _htmFilters = '',
        _fl = _curView.tag.length,
        _cl = _curView.country.length;
/*    if (!_curView.period && !_fl && !_cl) {
        _htmFilters = '<li class="nofilter">Aucun filtre</li>';
} */
    if (_curView.period[0] == gomNs.minYear && _curView.period[1] == gomNs.maxYear) {
        _htmFilters += '<li class="filperiod">'+gettext("Toutes periodes")+'</li>';
    } else {
        _htmFilters += '<li class="filperiod">'+gettext("Periode&nbsp;:")+' <span class="spyr" id="sp_0" onclick="changeSpan(this);">'
            + _curView.period[0]
            + '</span> ' + gettext('a')+' <span class="spyr" id="sp_1" onclick="changeSpan(this);">'
            + _curView.period[1]
            + '</span><a href="#" class="remfil" onclick="removePeriod(); return false;">[x]</a></li>';
    }
    $("#handle_0").css({
        "left" : yearToPx(_curView.period[0])+"px",
    }).attr("year", _curView.period[0])
    .find(".handleinner")
    .css({
        "margin-left" : "-20px"
    });
    $("#handle_1").css({
        "left" : yearToPx(_curView.period[1])+"px",
    }).attr("year", _curView.period[1])
    .find(".handleinner")
    .css({
        "margin-left" : "0"
    });
    if (_cl) {
        _htmFilters += _(_curView.country).map(function(_t, _i) {
            return '<li class="filcountry">'+gettext('Pays&nbsp;:')+' '
                + ( (typeof gomNs.countries == "object" && typeof gomNs.countries[_t] == "object") ? gomNs.countries[_t].properties.labels[gomNs.languageCode] : decodeURIComponent(_t.match('[^/]+$')[0]).replace('_',' '))
                + '<a href="#" class="remfil" onclick="removeFilter(\'country\','
                + _i
                + '); return false;">[x]</a></li>'; 
        }).join("");
    }
    if (_fl) {
        _htmFilters += _(_curView.tag).map(function(_t, _i) {
            return '<li class="filtag">'+gettext('Tag&nbsp;:')+' '
                + '<span class="filtag_label">'+_t+'</span>'
                + '<a href="#" class="remfil" onclick="removeFilter(\'tag\','
                + _i
                + '); return false;">[x]</a></li>'; 
        }).join("");
    }
    $("#filters").html(_htmFilters).hide();
    debouncedGetUpdates();
}

function displayContents(contentdata) {
    if (contentdata && contentdata.length) {
        var _htmlCl = '<ul id="contentlist">'
            + contentdata.map(function(_d) {
                var _html = '<li class="content-item"><h3>'
                    + _d.title
                    + '</h3>'
                    + ( typeof _d.coords == "object" ?
                        '<div class="maplet"><img src="http://maps.googleapis.com/maps/api/staticmap?center=47,1.5&zoom=4&size=160x160&maptype=roadmap&markers=color:red%7C'
                        + _d.coords.latitude
                        + ','
                        + _d.coords.longitude
                        + '&sensor=false" /><h4>Localisation&nbsp;: '
                        + _d.coords.city_name
                        + '</h4></div>'
                        : '')
                    + '<h4><a href="'
                    + _d.url
                    + '" target="_blank">'
                    + _d.url.replace(/(^.{40}).+(.{30}$)/m,'$1 &hellip; $2')
                    + '</a></h4><p>'
                    + _d.description.replace(/(^.{0,160})([\s]|$)(.*)/,'$1&hellip;')
                    + '</p><ul class="content-tags">'
                    + _d.tags.map(function(_t) {
                        return '<li class="content-tag-item"><a href="#" onclick="tagInfo(\''+_t.label+'\'); return false;"'
                            + (_t.match ? ' class="tagmatch"' : '')
                            + '>'
                            + _t.translated_label
                            + '</a></li>';
                    }).join('')
                    + '</ul><h4>'+gettext("Annotations")+'</h4><div class="content-annotation" contentid="'
                    + _d.id
                    + '">'
                    + ( gomNs.sessiondata.annotations[_d.id] && gomNs.sessiondata.annotations[_d.id].texte
                        ? '<ul><li>'
                            + _.escape(gomNs.sessiondata.annotations[_d.id].texte).replace(/\n/gm,"</li><li>")
                            + '</li>'
                        : ( gomNs.write_allowed ? '<ul><li>'+gettext("Annoter ce contenu")+'...</li></ul>' : '' ) )
                    + '</div>';
                if (gomNs.write_allowed) {
                    _(gomNs.sessiondata.views).each(function(_view, _k) {
                        if (_view.type == 'list') {
                            _html += '<p><a href="#" class="addremlist" contentid="'
                                + _d.id
                                + '" viewid="'
                                + _k
                                + '">'
                                + ( _view.list.indexOf(_d.id) == -1 ? gettext('Ajouter a') : gettext('Retirer de') )
                                + ' "'
                                + _.escape(_view.name)
                                + '"</a></p>'
                        }
                    });
                }
                _html += '</li>';
                return _html;
            }).join('')
            + '</ul>';
        $("#contents").html(_htmlCl).scrollTop(0);
        $("a.addremlist").click(function() {
            var _id = $(this).attr("contentid"),
                _vid = 
                _view = gomNs.sessiondata.views[$(this).attr("viewid")],
                _io = _view.list.indexOf(_id);
            if ( _io == -1) {
                _view.list.push(_id);
                $(this).html(gettext('Retirer de')+' "' + _.escape(_view.name) + '"' );
            } else {
                _view.list.splice(_io, 1);
                $(this).html(gettext('Ajouter a')+' "' + _.escape(_view.name) + '"');
            }
            if (gomNs.sessiondata.view == 1) {
                showView();
            }
            debouncedSaveChanges();
            return false;
        })
        if (gomNs.write_allowed) {
            $("div.content-annotation").click(function() {
                if (this.children[0].tagName == 'UL') {
                    var _el = document.createElement('textarea'),
                        _id = $(this).attr("contentid");
                    _el.innerHTML = (gomNs.sessiondata.annotations[_id] && gomNs.sessiondata.annotations[_id].texte) ? gomNs.sessiondata.annotations[_id].texte : '';
                    $(_el).focusout(function() {
                        var _id = this.parentNode.attributes.contentid.nodeValue;
                        if (!gomNs.sessiondata.annotations[_id]) {
                            gomNs.sessiondata.annotations[_id] = {};
                        }
                        gomNs.sessiondata.annotations[_id].texte = this.value;
                        this.parentNode.innerHTML = '<ul><li>' + (this.value.length ? _.escape(gomNs.sessiondata.annotations[_id].texte).replace(/\n/gm,"</li><li>") : gettext('Annoter ce contenu')+'...' ) + '</ul>';
                        debouncedSaveChanges();
                    });
                    $(this).html(_el);
                    _el.focus();
                    _el.select();
                }
            });
        }
    }
    else {
        $("#contents").html("");
    }
}

function updateDisplay(data) {
    animStop();
    
    // translate filters
    $('.filtag_label').each(function(index, elt) {
    	txt = $(this).text();
    	if(txt in data.tagtranslations) {
    		$(this).text(data.tagtranslations[txt]);
    	}
    });
    $("#filters").show();
    
    
    if (gomNs.dhmPaper) {
        gomNs.dhmPaper.clear();
    } else {
        gomNs.dhmPaper = new Raphael("dateheat");
    }
    $("#contentcount").html('<b>'+data.count+'</b> ' + ngettext('notice', 'notices', data.count));
    if (!data.sparkline.length || data.sparkline[0].year != gomNs.minYear) {
        data.sparkline.splice(0,0,{"year": gomNs.minYear, "score": 0});
    }
    var _maxheat = _(data.sparkline).max(function(_d) { return parseInt(_d.score); }).score;
    _(data.sparkline).each(function(_d, _i) {
        var _nxt = (_i == data.sparkline.length - 1) ? (gomNs.maxYear + 1) : data.sparkline[_i + 1].year,
            _x1 = yearToPx(_d.year),
            _x2 = yearToPx(_nxt),
            _heat = _d.score / _maxheat;
        gomNs.dhmPaper.rect(_x1, 0, _x2 - _x1, 20).attr({
            "fill" : getGradient(_heat),
            "stroke" : "none"
        })
    });
    if (gomNs.sessiondata.view == 0) {
        var _h0 = $("#handle_0").position().left,
            _h1 = $("#handle_1").position().left;
        gomNs.dhmPaper.rect(Math.min(_h0, _h1) - 1, 0, Math.abs(_h0 - _h1) + 2, 20).attr({
            "stroke" : "#cc0066",
            "stroke-width" : "3"
        });
    }
    if (data.tags.length) {
        var _scores = _(data.tags).map(function(_d) { return parseInt(_d.score)}),
            _maxTag = _(_scores).max(),
            _minTag = Math.min(_(_scores).min(), _maxTag - 1),
            _scale = 10 / Math.sqrt(_maxTag - _minTag),
            _htmlTc = '<ul id="tclist">'
            + _(data.tags).map(function(_d) {
                return '<li style="font-size:'
                    + parseInt(10 + _scale * Math.sqrt(_d.score - _minTag))
                    + 'px;"><a href="#" onclick="tagInfo(\''+_d.label+'\'); return false;"'
                    + (_d.match ? ' class="tagmatch"' : '')
                    + '>'
                    + _d.translated_label
                    + '</a></li>';
            }).join('')
            + '</ul>';
        $("#tagcloud").html(_htmlTc);
    }
    else {
        $("#tagcloud").html("<h4>Pas de mots-clés trouvés</h4>");
    }
    displayContents(data.contents);
    if (gomNs.countries && data.countries) {
        var _max = Math.max(1, _(data.countries).max());
        _(gomNs.countries).each(function(_country, _k) {
            var _val = data.countries[_k] || 0,
                _fill = getGradient(_val/_max);
            switch(gomNs.mappingLibrary) {
                case 'gmaps':
                    _(_country.gPolygons).each(function(_p) {
                        _p.setOptions({
                            "fillColor" : _fill,
                            "fillOpacity" : 1
                        });
                    });
                break;
                case 'leaflet':
                    _country.layer.setStyle({
                        "fillColor" : _fill,
                        "fillOpacity" : 1
                    })
                break;
            }
        });
    }
    if (data.disciplines) {
        var _disc = data.disciplines.filter(function(_d) {
                return +_d.score > 0;
            }),
            _max = _disc.reduce(function(_a, _b) {
                return Math.max(_a,_b.score)
            }, 1);
        $("#disciplines").html(
            '<ul class="disc-ul">'
            + _disc.map(function(_d) {
                var _col = getGradient(_d.score / _max);
                return '<li class="disc-li" onclick="tagInfo(\''+_d.label+'\'); return false;"><div class="disc-label"><a href="#">'
                    + _d.translated_label
                    + '</a></div><div class="disc-bar" style="background:'
                    + _col
                    + '; width:'
                    + Math.floor(120 * (_d.score / _max))
                    + 'px">'
            }).join("")
            + '</ul>'
        )
        
    }
}

function saveChanges() {
    if (gomNs.sessionid && gomNs.sessionkey) {
        $.getJSON(gomNs.urls['session_info'], {
            "sessionid" : gomNs.sessionid,
            "sessionkey" : gomNs.sessionkey,
            "data" : JSON.stringify(gomNs.sessiondata),
        });
    }
}

var debouncedSaveChanges = _.debounce(saveChanges, 3000);

function changeView(nview) {
    var _curView = gomNs.sessiondata.views[nview];
    if (_curView.type == 'list' && (!_curView.list || !_curView.list.length)) {
        alert(gettext("La liste de contenus est vide ! Ajoutez des contenus pour afficher la liste !"));
    } else {
        gomNs.sessiondata.view = nview;
        debouncedSaveChanges();
        showView();
    }
}

function showView() {
    $(".lienvue").removeClass("actif");
    $("#view_" + gomNs.sessiondata.view).addClass("actif");
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    $("#titrevue").val(_curView.name);
    $("#bloc_gestvue h2").html(gettext('Gerer la vue')+' "' + _.escape(_curView.name) + '"');
    $("div.bloc").show();
    $("#widgetlist input").prop("checked",true);
    _(_curView.hiddenWidgets).each(function(_w) {
        $("#chbx_" + _w).prop("checked",false);
        $("#" + _w).hide();
    });
    $("#notes").html( _curView.notes
        ? '<ul><li>' + _.escape(_curView.notes).replace(/\n/gm,"</li><li>") + '</li></ul>'
        : ( gomNs.write_allowed ? '<ul><li>'+gettext('Annoter cette vue')+'...</li></ul>' : '' ) );
    switch(_curView.type) {
        case 'list':
            $("#bandefiltre, .handle").hide();
            $.getJSON(gomNs.urls['filter'], {
                contentlist: _curView.list.join(',')
            }, updateDisplay);
            animLoad();
            break;
        case 'filter':
            $("#bandefiltre, .handle").show();
            updateFilters();
            break;
    }
}

function displayViewList() {
    $("#ongletsvues").html(gomNs.sessiondata.views.map(function(_v, _k) {
            return '<li class="lienvue" id="view_'
                + _k
                + '" onclick="changeView('
                + _k
                + '); return false;"><a href="#">'
                + _.escape(_v.name)
                + '</a></li>';
        }).join(""))
}

function getInitialView() {
    var _urlParam = {};
    if (document.location.hash) {
        var _tab = document.location.hash.replace("#","").split(":");
        _urlParam.sessionid = _tab[0];
        if (_tab.length > 1) {
            _urlParam.sessionkey = _tab[1];
        }
    }
    $.getJSON(gomNs.urls['session_info'], _urlParam, function(data) {
        gomNs.sessionid = data.sessionid;
        if (data.sessionkey) {
            gomNs.sessionkey = data.sessionkey;
        }
        gomNs.write_allowed = data.write_allowed;
        if (data.write_allowed) {
            $("#partagerw").show();
        } else {
            $("#partagerw").hide();
        }
        var _baseUrl = document.location.href.split("#")[0];
        gomNs.hash = "#" + data.sessionid + (data.sessionkey ? (':' + data.sessionkey) : '');
        document.location.hash = gomNs.hash;
        gomNs.sessiondata = typeof data.data == "string" ? JSON.parse(data.data) : (typeof data.data == "object" ? data.data : {});
        if (!gomNs.sessiondata.title) {
            gomNs.sessiondata.title = gettext('Nouvelle session');
        }
        if (!gomNs.sessiondata.views) {
            gomNs.sessiondata.views = [];
        }
        if (!gomNs.sessiondata.views.length) {
            addView( 'filter', gettext('Mes resultats de recherche') );
            addView( 'list', gettext('Ma liste') );
        }
        if (!gomNs.sessiondata.annotations) {
            gomNs.sessiondata.annotations = {};
        }
        if (data.write_allowed) {
            $("#bloc_gestvue").show();
        } else {
            $("#bloc_gestvue").hide();
        }
        $("#sessionname").html(gomNs.sessiondata.title
            + ( data.write_allowed ? '' : '<span class="lectseul"> ('+gettext("lecture seule")+')</span>' ) );
        gomNs.hrefinterval = setInterval(function() {
            if (document.location.hash != gomNs.hash) {
                clearInterval(gomNs.hrefinterval);
                getInitialView();
            }
        }, 500);
        displayViewList();
        showView();
    });
}

function changeSessionTitle(title) {
    gomNs.sessiondata.title = _.escape(title);
    $("#sessionname").html(gomNs.sessiondata.title);
    debouncedSaveChanges();
}

function addView(viewtype, viewname) {
    var _content = {
        type: viewtype,
        name: viewname,
        hiddenWidgets: [],
    };
    switch(viewtype) {
        case 'filter':
            _content.period = [ gomNs.minYear, gomNs.maxYear ];
            _content.tag = [];
            _content.country = [];
            gomNs.sessiondata.view = gomNs.sessiondata.views.length;
            break;
        case 'list':
            _content.list = [];
            break;
    }
    gomNs.sessiondata.views.push(_content);
    debouncedSaveChanges();
}

function animLoad() {
    //console.log("animLoad");
    var _d = $("#waiting"),
        _w = _d.width(),
        _h = _d.height(),
        _r = .33*Math.min(_w,_h),
        _count = 24,
        _html = '',
        _f = 2* Math.PI / _count;
    _d.empty().show();
    for (var _i = 0; _i < _count; _i++) {
        var _x = Math.floor(Math.sin(_i * _f)*_r + _w/2),
            _y = Math.floor(-Math.cos(_i * _f)*_r + _h/2),
            _el = document.createElement('div');
        _el.className = 'waittick';
        _d.append(_el);
        $(_el).css({
            "left": _x + "px",
            "top": _y + "px"
        }).delay(200*_i).fadeIn(400).delay(600 + 200* _i).fadeOut();
    }
}

function animStop() {
    $("#waiting").empty().fadeOut();
}

$(document).ready(function() {
    switch(gomNs.mappingLibrary) {
        case 'gmaps':
            gomNs.map = new google.maps.Map(document.getElementById("map"),
                {
                    center: new google.maps.LatLng(30, 0),
                    zoom: 1,
                    mapTypeId: google.maps.MapTypeId.SATELLITE
                });
            $.getJSON(gomNs.urls['countries'], showCountriesGmap);
            break;
        case 'leaflet':
            gomNs.map = new L.Map('map', {
                center: new L.LatLng(30, 0),
                zoom: 1
            });
            //gomNs.map.addLayer(new L.TileLayer("http://s3.amazonaws.com/com.modestmaps.bluemarble/{z}-r{y}-c{x}.jpg", {maxZoom: 9}));
            $.getJSON(gomNs.urls['countries'], showCountriesLeaflet);
            break;
    }
    var _html = gomNs.displayedDates.map(function(_v) {
        return '<li style="left: '
            + parseInt(yearToPx(_v))
            + 'px"><div class="datelabel">'
            + _v
            + '</div></li>'
    }).join('');
    $("#dates").html(_html);
    $("#apartager").click(function() {
        var _pu = $("#partageurls");
        if (_pu.is(":visible")) {
            $(this).removeClass("actif");
        } else {
            $(this).addClass("actif");
            $("#partagero").addClass("actif");
            $("#partagerw").removeClass("actif");
            var _url = document.location.href.split("#")[0] + "#" + gomNs.sessionid;
            $("#zc-partageinput").val( _url );
        }
        $(this).attr("class",_pu.is(":visible") ? "" : "actif");
        _pu.slideToggle(function() {
            if ($(this).is(":visible")) {
                if (typeof gomNs.clip == "undefined") {
                    gomNs.clip = new ZeroClipboard.Client();
                    gomNs.clip.setHandCursor( true );
                    gomNs.clip.glue('zc-partageinput');
                }
                gomNs.clip.show();
                gomNs.clip.setText( _url );
            } else {
                console.log("Let's hide it");
                gomNs.clip.hide();
            }
        });
        return false;
    })
    $("#partagero").click(function() {
        $("#partagero").addClass("actif");
        $("#partagerw").removeClass("actif");
        var _url = document.location.href.split("#")[0] + "#" + gomNs.sessionid;
        $("#zc-partageinput").val( _url );
        gomNs.clip.setText( _url );
        return false;
    });
    $("#partagerw").click(function() {
        $("#partagerw").addClass("actif");
        $("#partagero").removeClass("actif");
        var _url = document.location.href.split("#")[0] + gomNs.hash;
        $("#zc-partageinput").val( _url );
        gomNs.clip.setText( _url );
        return false;
    });
    $(".handle").draggable({
        "axis" : "x",
        "containment" : "parent",
        "drag": function() {
            $(this).attr("year",parseInt(pxToYear($(this).position().left)));
            var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
            if (_curView.type == 'filter') {
                var _h0 = $("#handle_0"),
                    _h1 = $("#handle_1"),
                    _h0v = parseInt(_h0.attr("year")),
                    _h1v = parseInt(_h1.attr("year"));
                _curView.period = [ Math.min(_h0v, _h1v), Math.max(_h0v, _h1v)];
                _h0.find(".handleinner").css({
                    "margin-left" : (_h0v>_h1v ? "0" : "-20px")
                })
                _h1.find(".handleinner").css({
                    "margin-left" : (_h1v>_h0v ? "0" : "-20px")
                })
                updateFilters();
                debouncedSaveChanges();
            }
        }
    })
    var _defLab = $( "#tagsearch" ).val();
    $( "#tagsearch" ).autocomplete({
        source: gomNs.urls['tag_search'],
        minLength: 2,
        select: function( event, ui ) {
            tagInfo(ui.item.label);
            return false;
        }
    }).addClass("grise")
    .focusin(function() {
        if ($(this).val() == _defLab) {
            $(this).val("").removeClass("grise");
        }
    });
    $("#sessionname").click(function() {
        if (gomNs.write_allowed && !$(this).children().length) {
            var _el = document.createElement('input');
            _el.value = gomNs.sessiondata.title;
            $(_el).focusout(function() {
                changeSessionTitle(this.value);
            }).keypress(function(e) {
                if (e.keyCode == 13) {
                    changeSessionTitle(this.value);
                }
            });
            $(this).html(_el);
            _el.focus();
            _el.select();
        }
    });
    $("#titrevue").keyup(function() {
        var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
        _curView.name = $(this).val();
        $("#view_" + gomNs.sessiondata.view + " a").html(_.escape(_curView.name))
        $("#bloc_gestvue h2").html(gettext('Gerer la vue')+' "' + _.escape(_curView.name) + '"');
        debouncedSaveChanges();
    });
    $("#notes").click(function() {
        if (gomNs.write_allowed) {
            if (this.children[0].tagName == 'UL') {
                var _el = document.createElement('textarea'),
                    _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
                _el.innerHTML = _curView.notes ? _curView.notes : '';
                $(_el).focusout(function() {
                    _curView.notes = this.value;
                    this.parentNode.innerHTML = '<ul><li>' + (this.value.length ? _.escape(_curView.notes).replace(/\n/gm,"</li><li>") : gettext('Annoter cette vue')+'...' ) + '</ul>';
                    debouncedSaveChanges();
                });
                $(this).html(_el);
                _el.focus();
                _el.select();
            }
        }
    });
/*    gomNs.disChart = d3.select("#disciplines")
        .append("svg:svg")
        .attr("width", 475)
        .attr("height", 120); */
    getInitialView();
    $(".barrebloc").click(function() {
        $(this).next().slideToggle(); 
    });
    gomNs.widgetList = [];
    var _html = '<ul id="widgetlist">';
    $("div.bloc").each(function() {
       gomNs.widgetList.push(this.id);
       _html += '<li><input type="checkbox" id="chbx_'
        + this.id
        + '" /><label>' + $(this).find("h2").html() + '</label></li>'
    });
    _html + '</ul>';
    $("#gestvue").append(_html);
    $("#nouvellevue").click(function() {
        $("#plusdevues").slideToggle();
        return false;
    })
    $("#widgetlist input").change(function() {
        var _newWL = [];
        $("#widgetlist input").each(function(_k, _e) {
            var _id = _e.id.substr(5);
            if (!$(_e).prop("checked")) {
                $("#" + _id).hide();
                _newWL.push(_id);
            } else {
                $("#" + _id).show();
            }
        });
        gomNs.sessiondata.views[gomNs.sessiondata.view].hiddenWidgets = _newWL;
        debouncedSaveChanges();
    });
    $("#nouv_resrech").click(function() {
       var _txt = prompt(gettext("Comment souhaitez-vous nommer votre nouvelle vue ?"),gettext("Nouveaux resultats de recherche"));
       if (_txt !== null) {
           addView('filter', _txt); 
           displayViewList();
       }
       return false;
    });
    $("#nouv_liste").click(function() {
       var _txt = prompt(gettext("Comment souhaitez-vous nommer votre nouvelle vue ?"),gettext("Nouvelle liste"));
       if (_txt !== null) {
           addView('list', _txt);
           displayViewList();
       }
       return false;
    });
});
