/**
 * @author raph
 */

var gomNs = {
    minYear: -5000,
    maxYear: 2010,
    tlPixels: 960,
    tlGamma: 6,
    heatGamma: 4,
    displayedDates: [-5000,0,500,1000,1200,1400,1600,1700,1750,1800,1850,1900,1950,2010],
    urls: {}
}

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 tagInfo(_taglabel) {
    var _urlParam = { "label": _taglabel };
    $.getJSON(gomNs.urls['tag_info'],
        _urlParam,
        function(data) {
            $("#tagsearch").val(data.requested_label).removeClass("grise");
            $("#tagcount").html(data.content_count
                + ' contenu' + (data.content_count > 1 ? 's' : '') + ' pour ce tag');
            var _html = '';
            if (data.wikipedia_url) {
                _html += '<h3><a href="'
                    + data.wikipedia_url
                    + '" target="_blank">Wikipédia: '
                    + decodeURI(data.wikipedia_url.match(/[^\/]+$/)[0]).replace("_"," ")
                    + '</a></h3>'
            }
            if (data.thumbnail) {
                _html += '<img id="img_wikipedia" src="'
                    + data.thumbnail
                    + '" />';
            }
            if (data.abstract) {
                _html += '<p>' + _(data.abstract).escape() + '</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);
        });
    filterTag(_taglabel);
    $("#showlist").removeClass("actif");
}

function filterTag(_tagLabel) {
    var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
    if (_curView.type == 'filter') {
        _curView.tag.push(_tagLabel);
        updateFilters();
        debouncedSaveChanges();
    }
}

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

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

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 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;
    if (!_curView.period && !_fl) {
        _htmFilters = '<li class="nofilter">Aucun filtre</li>';
    }
    if (_curView.period) {
        _htmFilters += '<li class="filperiod"><span class="spyr" id="sp_0" onclick="changeSpan(this);">'
            + _curView.period[0]
            + '</span> à <span class="spyr" id="sp_1" onclick="changeSpan(this);">'
            + _curView.period[1]
            + '</span></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 (_fl) {
        _htmFilters += _(_curView.tag).map(function(_t, _i) {
            return '<li class="filtag">'
                + _t
                + '<a href="#" class="remfil" onclick="removeFilter('
                + _i
                + '); return false;">[x]</a></li>'; 
        }).join("");
    }
    $("#filters").html(_htmFilters);
    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><h4><a href="'
                    + _d.url
                    + '" target="_blank">'
                    + _d.url
                    + '</a></h4><p>'
                    + _d.description
                    + '</p><ul class="content-tags">'
                    + _d.tags.map(function(_t) {
                        return '<li class="content-tag-item"><a href="#" onclick="tagInfo($(this).text()); return false;"'
                            + (_t.match ? ' class="tagmatch"' : '')
                            + '>'
                            + _t.label
                            + '</a></li>';
                    }).join('')
                    + '</ul><h4>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>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 ? 'Ajouter à' : '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('Retirer de "' + _.escape(_view.name) + '"' );
            } else {
                _view.list.splice(_io, 1);
                $(this).html('Ajouter à "' + _.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>") : 'Annoter ce contenu...' ) + '</ul>';
                        debouncedSaveChanges();
                    });
                    $(this).html(_el);
                    _el.focus();
                    _el.select();
                }
            });
        }
    }
    else {
        $("#contents").html("");
    }
}

function updateDisplay(data) {
    if (gomNs.dhmPaper) {
        gomNs.dhmPaper.clear();
    } else {
        gomNs.dhmPaper = new Raphael("dateheat");
    }
    var _s = (data.count>1?'s':'');
    $("#contentcount").html('<b>'+data.count+'</b> notice'+_s);
    var _sl = data.sparkline.length;
    if (_sl) {
        var _maxheat = _(data.sparkline).max(function(_d) { return parseInt(_d.score); }).score,
            _exp = 1 / gomNs.heatGamma,
            _scale = Math.pow(_maxheat, - _exp);
        _(data.sparkline).each(function(_d, _i) {
            var _nxt = (_i == _sl - 1) ? gomNs.maxYear + 1 : data.sparkline[_i + 1].year,
                _x1 = yearToPx(_d.year),
                _x2 = yearToPx(_nxt),
                _heat = _scale * Math.pow(_d.score, _exp);
            gomNs.dhmPaper.rect(_x1, 0, _x2 - _x1, 20).attr({
                "fill" : "rgb(255, 128, 128)",
                "opacity" : _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" : "rgb(128,0,0)",
            "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 = 20 / 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($(this).text()); return false;"'
                    + (_d.match ? ' class="tagmatch"' : '')
                    + '>'
                    + _d.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(function(_c) { return _c.score}).score);
        _(data.countries).each(function(_c) {
            var _cc = gomNs.countries[_c.isocode];
            if (_cc) {
                var _gb = parseInt(255 * (1 - _c.score / _max ));
                _(_cc.gPolygons).each(function(_p) {
                    _p.setOptions({
                        "fillColor" : ( _c.score ? "rgb(255," + _gb + "," + _gb + ")" : "#7070a0" ),
                    });
                });
            }
        });
    }
    if (data.disciplines) {
        var _disc = data.disciplines.filter(function(_d) {
            return +_d.score > 0;
        }),
            _echelle = d3.scale
                .linear()
                .range([0, 120])
                .domain([0, d3.max(_disc, function(_d) { return +_d.score })]),
            _barres = gomNs.disChart.selectAll("g.discbarre").data(_disc);
            
        var _newels = _barres.enter()
            .append("svg:g")
            .attr("class","discbarre");
        
        _newels.append("svg:rect")
            .attr("stroke","none")
            .attr("fill","rgb(255,128,128)")
            .attr("x","0").
            attr("y","0")
            .attr("height","25");
        _newels.append("svg:text")
            .attr("font-size","12px")
            .attr("x","5")
            .attr("y","16");
        
        _barres.exit().remove();
        
        _barres.on("click", function(_d) {
            tagInfo(_d.label);
        }).on("mouseover", function() {
            d3.select(this).select("rect").attr("fill","rgb(128,128,255)");
        }).on("mouseout", function() {
            d3.select(this).select("rect").attr("fill","rgb(255,128,128)");
        }).attr("transform",function(_d,_k) {
           return "translate(" + ( 30 + 40 * _k ) + ",120) rotate(-90)";
        });
        _barres.select("text").text(function(_d) {
            return _d.label;
        });
        _barres.select("rect").attr("width", function(_d) {
            return _echelle(_d.score);
        });
    }
}

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("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('Gérer 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>Annoter cette vue...</li></ul>' : '' ) );
    switch(_curView.type) {
        case 'list':
            $("#bandefiltre, .handle").hide();
            $.getJSON(gomNs.urls['filter'], {
                contentlist: _curView.list.join(',')
            }, updateDisplay);
            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];
        $("#rourl").html(_baseUrl + "#" + data.sessionid );
        gomNs.hash = "#" + data.sessionid + (data.sessionkey ? ':' + data.sessionkey : '');
        document.location.hash = gomNs.hash;
        $("#rwurl").html(_baseUrl + gomNs.hash);
        gomNs.sessiondata = JSON.parse(data.data);
        if (!gomNs.sessiondata.title) {
            gomNs.sessiondata.title = 'Nouvelle session';
        }
        if (!gomNs.sessiondata.views) {
            gomNs.sessiondata.views = [];
        }
        if (!gomNs.sessiondata.views.length) {
            addView( 'filter', 'Mes résultats de recherche' );
            addView( 'list', '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"> (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 = [];
            gomNs.sessiondata.view = gomNs.sessiondata.views.length;
            break;
        case 'list':
            _content.list = [];
            break;
    }
    gomNs.sessiondata.views.push(_content);
    debouncedSaveChanges();
}

$(document).ready(function() {
    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'], showCountries);
    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");
        $(this).attr("class",_pu.is(":visible") ? "" : "actif");
        _pu.slideToggle();
        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").change(function() {
        var _curView = gomNs.sessiondata.views[gomNs.sessiondata.view];
        _curView.name = $(this).val();
        $("#view_" + gomNs.sessiondata.view + " a").html(_.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>") : '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("Comment souhaitez-vous nommer votre nouvelle vue ?","Nouveaux résultats de recherche");
       if (_txt !== null) {
           addView('filter', _txt); 
           displayViewList();
       }
       return false;
    });
    $("#nouv_liste").click(function() {
       var _txt = prompt("Comment souhaitez-vous nommer votre nouvelle vue ?","Nouvelle liste");
       if (_txt !== null) {
           addView('list', _txt);
           displayViewList();
       }
       return false;
    });
});
