User:Abronner/Gadget-cosyne-ui.js

var APP_SERVER = 'http://prototype.cosyne.eu'; // wgServer; var APP_PORT = 8080; // 8082 var APP_BASE = APP_SERVER + ':' + APP_PORT + '/cosyne/rest/client'; var APP_SYNC_JSONP = '/sync/jsonp'; var APP_STATUS_JSONP = '/status/jsonp'; var APP_SUBMIT_JSONP = '/submit/jsonp'; var WIKI_API = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php';

var ID_SEP = '-'; var META_PREFIX = 'm'; var SRC_TRANS_PREFIX = 'st'; var SRC_PREFIX = 's'; var TARGET_PREFIX = 'u';

var APP_IMAGE_PATH = '/demo/pool/images'; // '/wiki/dev/pool/images'; var ADD_BUTTON_ICON = APP_SERVER + APP_IMAGE_PATH + '/2/2f/Plus.png'; var APPROVE_BUTTON_ICON = APP_SERVER + APP_IMAGE_PATH + '/0/01/Approve.png'; var UNDO_BUTTON_ICON = APP_SERVER + APP_IMAGE_PATH + '/8/8b/Undo.png'; var CLOSE_BUTTON_ICON = APP_SERVER + APP_IMAGE_PATH + '/5/5c/Del.png'; var INFO_BUTTON_ICON = APP_SERVER + APP_IMAGE_PATH + '/b/b3/Info.png'; var DELETED_TEXT_ICON = APP_SERVER + APP_IMAGE_PATH + '/5/57/Deleted.png'; var HIDE_ICON = APP_SERVER + APP_IMAGE_PATH + '/9/96/Hide.png'; var SHOW_ICON = APP_SERVER + APP_IMAGE_PATH + '/1/15/Show.png';

var STAR_OFF_IMG = APP_SERVER + APP_IMAGE_PATH + '/1/11/Star_off.png'; var STAR_ON_IMG = APP_SERVER + APP_IMAGE_PATH + '/8/85/Star_on.png';

var FLAG_EN = APP_SERVER + APP_IMAGE_PATH + '/3/3b/En.png'; var FLAG_NL = APP_SERVER + APP_IMAGE_PATH + '/9/98/Nl.png'; var FLAG_IT = APP_SERVER + APP_IMAGE_PATH + '/d/dd/It.png'; var FLAG_DE = APP_SERVER + APP_IMAGE_PATH + '/8/8f/De.png'; var FLAGS_ICONS = { "en" : FLAG_EN, "nl" : FLAG_NL, "it" : FLAG_IT, "de" : FLAG_DE};

var LEFT_ARROW = APP_SERVER + APP_IMAGE_PATH + '/f/f1/Prev.png'; var RIGHT_ARROW = APP_SERVER + APP_IMAGE_PATH + '/c/c4/Next.png';

var SUGGESTION_LABELS = {'CONTRADICT' : 'Resolve', 'REPLACE' : 'Replace', 'KEEP' : 'Keep', 'ADD' : 'Add (Unrelated)', 'ASK' : 'Add (Unaligned)'}; var ENTAILMENT_LABELS = {'LEFT_SPECIFIC' : 'More Specific', 'RIGHT_SPECIFIC' : 'Less Specific', 'UNKNOWN' : 'Additional (Unrelated)', 'EQUIVALENT' : 'Equivalent', 'CONTRADICTION' : 'Contradicting', 'NO_DECISION' : 'Irrelevant' }; var EDIT_TYPE_LABELS = {'FACTUAL' : 'Factual Edit', 'FLUENCY' : 'Fluency Edit', 'NO_EDIT' : 'No Edit' };

var ENTAILMENT_SUGGESTION = {'LEFT_SPECIFIC' : 'REPLACE', 'RIGHT_SPECIFIC' : 'KEEP', 'UNKNOWN' : 'ADD', 'EQUIVALENT' : 'KEEP', 'CONTRADICTION' : 'CONTRADICT', 'NO_DECISION' : 'KEEP' };

//--

$(document).ready(function{   loadSyncDataByURI;    $("#bodyContent").after(getControls);    $("#source_edit_from_date_input").datepicker({ dateFormat: "yy-mm-dd", maxDate: "+0" });

});

function loadSyncDataByURI { var params = window.location.search.substring(1).split('&'); for (var i=0;i length && param.substring(0, length) == "syncsetURI=") { var syncsetURI = param.substring(length); loadSyncData(syncsetURI, 'previewCallback'); return; }   }    }

function getControls { var html = ''; html += ''; html += 'Exit '; html += 'CoSyne '; html += 'Preview '; html += ' ';

html += ''; html += ''; html += ""; html += "</a></li>"; html += '</ul>'; html += ' ';//end options header

html += '<div id="cosyne_options_form" style="display:none;">';

html += '<label for="source_language"> Source Language: '; html += '<div id="source_language">'; if (wgContentLanguage != 'en') { html += '<input id="source_language_en" type="radio" value="en" name="source_language" />'; html += '<label for="source_language_en""> English ';               }    if (wgContentLanguage != 'de') {        html += '<input id="source_language_de" type="radio" value="de" name="source_language" />';        html += '<label for="source_language_de""> Deutch '; }   if (wgContentLanguage != 'it') { html += '<input id="source_language_it" type="radio" value="it" name="source_language" />'; html += '<label for="source_language_it""> Italiano ';               }    if (wgContentLanguage != 'nl') {        html += '<input id="source_language_nl" type="radio" value="nl" name="source_language" />';        html += '<label for="source_language_nl""> Nederlands '; }   html += ' '; //end select language

html += '<label for="source_edit_method"> Source Edits: '; html += '<div id="source_edit_method">'; html += '<input id="source_edit_from_outset" type="radio" value="FROM_OUTSET" name="source_edit_method" checked="true" />'; html += '<label for="source_edit_from_outset"> From Outset '; html += '<input id="source_edit_from_last_edit" type="radio" value="FROM_LAST_EDIT" name="source_edit_method" />'; html += '<label for="source_edit_from_last_edit""> From Last Edit ';       html += '<input id="source_edit_from_last_sync" type="radio" value="FROM_LAST_SYNC" name="source_edit_method" />';    html += '<label for="source_edit_from_last_sync""> From Last Sync '; html += '<input id="source_edit_from_date" type="radio" value="FROM_DATE" name="source_edit_method" />'; html += '<label for="source_edit_from_date""> From Date ';   html += '<input id="source_edit_from_date_input" class="date_input_text" type="text"> ';    html += '<input id="source_edit_period_in_days" type="radio" value="PERIOD_IN_DAYS" name="source_edit_method" />';    html += '<label for="source_edit_period_in_days""> Period in Days '; html += '<input id="source_edit_period_in_days_input" class="number_input_text" type="text" > '; html += ' '; //end source edit method

html += ' '; //end options form

html += ' <div id="cosyne_status"> '; html += ' '; html += ' '; return html; }

function getSourceLanguage { var srcLang = $("input:radio[name='source_language']:checked").val; if (srcLang == undefined || srcLang == null) { if (wgContentLanguage != 'en') { srcLang = 'en'; } else { srcLang = ''; }   }    return srcLang; }

function getSourceEditMethod { var srcEditMethod = $("input:radio[name='source_edit_method']:checked").val; if (srcEditMethod == undefined || srcEditMethod == null) { srcEditMethod = 'FROM_OUTSET'; }   return srcEditMethod; }

function getSourceEditValue(srcEditMethod) { var srcEditVal = ''; if (srcEditMethod == 'FROM_DATE') { srcEditVal = $("#source_edit_from_date_input").val; try { $.datepicker.parseDate("yy-mm-dd", srcEditVal); } catch (e) { srcEditVal = ''; }

} else if (srcEditMethod == 'PERIOD_IN_DAYS') { srcEditVal = $("#source_edit_period_in_days_input").val; if (!isNumber(srcEditVal)) { srcEditVal = ''; }   }    return srcEditVal; }

function requestSync(resubmit) { var url = APP_BASE + APP_SYNC_JSONP; var srcLang = getSourceLanguage; var srcEditMethod = getSourceEditMethod; var srcEditVal = getSourceEditValue(srcEditMethod); console.debug('source edit method: ' + srcEditMethod + ' (value: ' + srcEditVal + ')');

$.ajax({       type: 'GET',        url: url,        data: {            'title' : wgPageName, 'pageId' : wgArticleId , 'revId' : wgCurRevisionId , 'user' : wgUserName ,            'server' : wgServer , 'path' : wgScriptPath ,            'srceditmethod' : srcEditMethod , 'srceditvalue' : srcEditVal ,            'srcLang' : srcLang,            'resubmit' : (resubmit ? 'true' : 'false'), 'reload' : true , 'nocache' : true       },        dataType: 'jsonp',        jsonp : 'callback',        jsonpCallback: 'syncCallback'    }); }

function syncCallback(syncData) { console.debug(syncData); if (syncData != undefined && syncData != null && syncData.status != undefined && syncData.status != null) { syncSuccess(syncData); } else{ syncFailure; } }

function previewCallback(syncData) { console.debug(syncData); if (syncData != undefined && syncData != null && syncData.status != undefined && syncData.status != null && syncData.status == 'completed') { var wikitext = buildPreviewText(syncData); console.debug(wikitext); $("#wpTextbox1").text(wikitext); $("#wpPreview").trigger('click'); } else{ syncFailure; }   }

function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }

function retry { requestSync(true); }

function syncSuccess(syncData) { if (syncData.status == 'completed') { initFeedbackForUser(syncData); wikitextToHTML(syncData);

} else if (syncData.status == 'in_process' || syncData.status == 'submitted' || syncData.status == 'resubmitted') { updateProgress(syncData);

//       } else if (syncData.status == 'failed' || syncData.status == 'abort') { } else { syncFailure(syncData);

} }

function initFeedbackForUser(syncData) { if (syncData.targetById != undefined && syncData.targetById != null) { for (var targetId in syncData.targetById) { var target = syncData.targetById[targetId]; if (target.alignments != undefined && target.alignments != null) { for (var sourceId in target.alignments) { var alignment = target.alignments[sourceId]; if (alignment.feedbacks == undefined || alignment.feedbacks == null) { alignment.feedbacks = {}; }                   if (alignment.feedbacks[wgUserName] == undefined || alignment.feedbacks[wgUserName] == null) { alignment.feedbacks[wgUserName] = { 'user' : wgUserName, 'action' : 'KEEP' }; }                                   }            }        }    } }

function buildWikitext(syncData) { var wikitext = ''; syncData.targetIdOrdering.forEach( function(targetId) {       var target = syncData.targetById[targetId];        wikitext += '<span id="';        wikitext += target.id;        wikitext += '" class="';        if(target.analyzed) {            wikitext += 'targetspan ';            if (target.sourceIdOrdering.length > 0) {                wikitext += target.alignments[target.sourceIdOrdering[0]].suggestion.toLowerCase;            } else {                wikitext += 'keep';            }        } else {            wikitext += 'unanalyzedspan';        }                wikitext += '">';        wikitext += getText(target);        wikitext += ' ';    }); return wikitext; }

function syncFailure(syncData) { console.debug(syncData); var html = ' '; html += ' The system failed to obtain the suggestions from other languages '; if (getSourceLanguage == '') { html += ' Please select a source language '; showOptions; }   html += 'Do you wish to retry? ';   html += ' '; $("#dialog").html(html); $("#dialog").dialog({       buttons: {            "Retry": function {                      console.debug('resubmitting...');                $(this).dialog("close");                retry;                         },            "Another time": function {                $(this).dialog("close");            }        },        title : 'Failed to synchronize'    }); $('#progressbar').html('<div id="cosyne_status"> '); $('#progressbar').css('display', 'none'); }

function applyCoSyneMask(syncData) { $.each($('.targetspan'), function {       if ($(this).text.length == 0) {            $(this).append(' <img src="' + ADD_BUTTON_ICON + '"> ');        }    });

$.each($('.targetspan'), function {       attachHoverPanel($(this), syncData);            }); }

function loadSyncData(syncsetURI, callbackFunc) { console.debug('Loading the progress data...'); var url = APP_BASE + APP_STATUS_JSONP;

$.ajax({       type: 'GET',        url: url,        data: { 'syncset' : syncsetURI, 'user' : wgUserName } ,        dataType: 'jsonp',        jsonp : 'callback',        jsonpCallback: callbackFunc    }); }

function updateProgress(syncData, init) { var percentage = 0; var error = false; if (syncData.progress == undefined) { console.debug('PROGDATA WAS UNDEFINED'); error = true; } else { var progressSteps = syncData.progress.length + 1; var stepPercent = 100 / progressSteps; console.debug(progressSteps + ' steps, each of ' + stepPercent + ' percent'); percentage = stepPercent; $('#cosyne_status').html('processing');

$.each(syncData.progress, function(stepIndex, step) {           console.debug(step);            if(step.status == 'failed' || step.status == 'abort'){                error = true;                return false;                     } else if (step.status == 'completed') {                //add this step to the percentage completed                percentage += stepPercent;                     } else {                if(step.status == 'in_process') {                    //updateStatus(name, stat);                    $('#cosyne_status').html(step.name);                }                return false;            }        }); }

//if there is an error, remove the progress bar and show a retry dialog if (error) { syncFailure;

} else { //show the progress bar console.debug('Synchronization %: ' + percentage); $('#progressbar').css('display', 'block'); $("#progressbar").progressbar({ value: Math.floor(percentage) }); if(Math.floor(percentage) < 100) { console.debug('Getting the status in 2sec'); setTimeout(function {               loadSyncData(syncData.syncsetURI, 'syncCallback');            }, 2000); } else { loadSyncData(syncData.syncsetURI, 'syncCallback'); }   } }

function wikitextToHTML(syncData) { var wikitext = buildWikitext(syncData); $.ajax({       type : 'post',        url : WIKI_API,        data : { 'action': 'parse', 'text' : wikitext, 'prop' : 'text', 'format' : 'xml'},        success : function(data) {            $("#bodyContent").html($(data).find('text').text);

//clear the progress bar $('#progressbar').html('<div id="cosyne_status"> '); $('#progressbar').css('display', 'none');

// display buttons $('#btn_sync').css('display', 'none'); $('#cosyne_options_header').css('display', 'none'); $('#cosyne_options_form').css('display', 'none'); $('#btn_back').css('display', 'block'); $('#btn_submit').css('display', 'block'); $('#btn_submit').click(function {               preview(syncData);            }); //after putting the HTML on the screen, the CoSyne annotation layer is applied on the screen applyCoSyneMask(syncData); },       failure: function(data) { console.debug('failed parsing wikitext to html: ' + wikitext); }   }); }

function panelWikitextToHTML(wikitext, suggestion, spanId) { var targetSpan = $('#' + spanId); if (suggestion != '') { targetSpan.removeClass('add replace keep contradict'); targetSpan.addClass(suggestion); }   if (wikitext == '') { targetSpan.html(''); if (targetSpan.hasClass('add')) { targetSpan.append('<img src="' + ADD_BUTTON_ICON + '">'); } else if (targetSpan.hasClass('ask')) { targetSpan.append('<img src="' + ADD_BUTTON_ICON + '">'); } else { targetSpan.append('<img src="' + DELETED_TEXT_ICON + '">'); }   } else { $.ajax({           type : 'post',            url : WIKI_API,            data : { 'action': 'parse', 'text' : wikitext, 'prop' : 'text', 'format' : 'xml'},            success : function(data) {                var text = $(data).find('text').text;                var temp = $('  ');                temp.html(text);                if(temp.find('p').html != null) {                    $('#' + spanId).html(temp.find('p').html);                } else {                    $('#' + spanId).html(temp.html);                }            },            failure: function(data) {                console.debug('failed parsing wikitext to html: ' + wikitext);            }        }); } }

function attachHoverPanel(targetSpan, syncData) { var targetId = targetSpan.attr('id'); var panelId = targetId + ID_SEP +'h'; targetSpan.click(function {       var hoverPanel = $('#' + panelId);        if(hoverPanel.length == 0) {                       var hoverBox = buildHoverBox(panelId, targetSpan, syncData); //            console.debug(hoverbox);            targetSpan.before(hoverBox);            hoverBox.position({ my: "left top", at: "left bottom", of: targetSpan, collision: "fit" });           showPanel(hoverBox.find('.hoverpanel'), targetSpan);        } else if (hoverPanel.css('display') == 'none') {            showPanel(hoverPanel, targetSpan);        } else if (hoverPanel.css('display') == 'block') {            hidePanel(hoverPanel, targetSpan);        }    }); }

function buildHoverBox(panelId, targetSpan, syncData) { var targetId = targetSpan.attr('id'); console.debug('build hover panel for ' + targetId); var target = syncData.targetById[targetId];

var hoverBox = $(getHoverHTML(panelId, target, syncData)); hoverBox.draggable({ containment: '#wrapper'});

var hoverPanel = hoverBox.find('.hoverpanel'); hoverPanel.find('.suggestion_text textarea').val(getText(target));

// add click events: hoverPanel.click(function(event) {       moveToFront(hoverPanel, targetSpan);        event.stopPropagation;    });

setHoverPanelButtons(targetSpan, hoverPanel, target, syncData); setHoverPanelSuggestion(targetSpan, hoverPanel, target, syncData); setHoverPanelFeedback(targetSpan, hoverPanel, target, syncData);

hoverPanel.css('display', 'block');

return hoverBox; }

function setHoverPanelButtons(targetSpan, hoverPanel, target, syncData) { hoverPanel.find('.btn_revert').click(function(event) {          setText(hoverPanel, target.text);        if (target.submittedTexts != undefined && target.submittedTexts != null) {            target.submittedTexts[wgUserName] = null;        }        for (var alignment in target.alignment) {            alignment.feedbacks[wgUserName].action = 'KEEP'; //            alignment.feedbacks[wgUserName] = null;        }        event.stopPropagation;    });

hoverPanel.find('.btn_close').click(function(event) {              hidePanel(hoverPanel, targetSpan);        event.stopPropagation;    });

hoverPanel.find('.btn_approve').click(function(event) {              approveSuggestion(hoverPanel, target, syncData);        hidePanel(hoverPanel, targetSpan);        event.stopPropagation;    }); }

function getAlignment(sourceId, targetId, syncData) { var alignment = null; var target = syncData.targetById[targetId]; if (target != null && target.alignments != null) { alignment = target.alignments[sourceId]; }   if (alignment == null) { var source = syncData.sourceById[sourceId]; if (source != null && source.alignments != null) { alignment = source.alignments[targetId];

if (alignment == null) { for (var id in source.alignments) { var a = source.alignments[id]; if (a.feedbacks != null && a.feedbacks[wgUserName] != null && a.feedbacks[wgUserName].targetId == targetId) { alignment = a;                   } }           }        }    }    return alignment; }

function getAlignmentFromId(id, syncData) { // suggestion or feedback id where the format is SG/FB_targetId_sourceId var index1 = id.indexOf('_'); var index2 = id.lastIndexOf('_'); var targetId = id.substring(index1 + 1, index2); var sourceId = id.substring(index2 + 1); return getAlignment(sourceId, targetId, syncData);

}

function getSourceFromId(id, syncData) { // suggestion or feedback id where the format is SG/FB_targetId_sourceId //   var index1 = id.indexOf('_'); var index2 = id.lastIndexOf('_'); //   var targetId = draggedId.substring(index1 + 1, index2); var sourceId = id.substring(index2 + 1); return syncData.sourceById[sourceId]; }

function setHoverPanelSuggestion(targetSpan, hoverPanel, target, syncData) { hoverPanel.find('.suggestion').each(function {       var suggestionId = $(this).attr('id');        if(suggestionId != undefined) {                    var source = getSourceFromId(suggestionId, syncData);            var alignment = getAlignmentFromId(suggestionId, syncData);

//           $(this).draggable; //           $(this).droppable({ //            drop: function(event, ui) { //            var draggedId = ui.draggable.attr('id'); //            if(draggedId != undefined) { //            var draggedAlignment = getAlignmentFromId(draggedId, syncData); //            if (draggedAlignment != null) { //            draggedAlignment.feedbacks[wgUserName].targetId = target.id; //            } //            submit(syncData); //            } //            } //            });

$(this).find('.sug_src_trans').each(function {               $(this).mouseover(function { $(this).css('-moz-box-shadow', '0 0 15px #333'); $(this).css('-webkit-box-shadow', '0 0 15px #333'); $(this).css('box-shadow', '0 0 15px #333'); });

$(this).mouseout(function {                   $(this).css('-moz-box-shadow', '0 0 0px #888');                    $(this).css('-webkit-box-shadow', '0 0 0px #888');                    $(this).css('box-shadow', '0 0 0px #888');                });

$(this).click(function(event) {                   if (event.shiftKey) {                        setText(hoverPanel, source.translation, false);                        alignment.feedbacks[wgUserName].action = 'REPLACE';                    } else {                        setText(hoverPanel, source.translation, true);                        alignment.feedbacks[wgUserName].action = 'ADD';                    }                    //prevent the event from bubbling up to the sentence class                    event.stopPropagation;                });

});

}   });                        }

function setHoverPanelFeedback(targetSpan, hoverPanel, target, syncData) { hoverPanel.find('.feedback').each(function {       var feedbackId = $(this).attr('id');               if(feedbackId != undefined) {            var alignment = getAlignmentFromId(feedbackId, syncData);            var feedback = alignment.feedbacks[wgUserName];            console.debug(feedback);            var stars = $(this).find('.stars');

stars.mouseout(function {                              var translationQuality = -1;                if (feedback.translationQuality != undefined && feedback.translationQuality != null) {                    translationQuality = feedback.translationQuality;                }                setStarsImage(stars, translationQuality);            });

stars.find('li a').mouseover(function {               var current = $(this).attr('id');                var translationQuality = -1;                if (feedback.translationQuality != undefined && feedback.translationQuality != null) {                    translationQuality = feedback.translationQuality;                }                setStarsImage(stars, Math.max(current, translationQuality));            });

stars.find('li a').click(function {               var translationQuality = $(this).attr('id');                feedback.translationQuality = translationQuality;                setStarsImage(stars, translationQuality);            });

$(this).find('.entailment_feedback input').click(function {               var entailment = $(this).val;                feedback.entailment = entailment;            });

$(this).find('.alignment_feedback input').click(function {               var alignment = $(this).val;                if (alignment != null && alignment != '') {                    feedback.alignment = alignment;                    }            });

}

});   }

function setStarsImage(stars, value) { stars.find('li img').each(function(index){       if(index <= value) {            $(this).attr('src', STAR_ON_IMG);        } else {                                   $(this).attr('src', STAR_OFF_IMG);        }    }); }

function setText(hoverPanel, text, append) { var textarea = hoverPanel.find('.suggestion_text textarea'); var existingText = textarea.val; if (hoverPanel.textStack == undefined) { hoverPanel.textStack = []; }   hoverPanel.textStack.push(existingText); if (hoverPanel.textStack.length > 20) { hoverPanel.textStack.shift; }   if (append && existingText != null  && existingText != '') { textarea.val(existingText + ' ' + text); } else { textarea.val(text); } }

function undoText(hoverPanel) { if (hoverPanel.textStack != undefined && hoverPanel.textStack != null && hoverPanel.textStack.length > 0) { var text = hoverPanel.textStack.pop; hoverPanel.find('.suggestion_text textarea').val(text); } }

function approveSuggestion(hoverPanel, target, syncData) { var submittedText = hoverPanel.find('.suggestion_text textarea').val; var submittedSuggetion = ''; var feedbackId = hoverPanel.find('.feedback').attr('id'); var entailmentFeedback = $("input:radio[name='" + feedbackId + "_entailment_feedback']:checked").val; if (entailmentFeedback != undefined && entailmentFeedback != null) { submittedSuggetion = ENTAILMENT_SUGGESTION[entailmentFeedback]; }   if (target.submittedTexts == undefined || target.submittedTexts == null) { target.submittedTexts = {}; }   if (target.text != submittedText) { target.submittedTexts[wgUserName] = { 'text' : submittedText, 'manuallyEdited' : 'true' }; } else { target.submittedTexts[wgUserName] = null; }   submitSyncData(syncData); panelWikitextToHTML(submittedText, submittedSuggetion.toLowerCase, target.id); }

function submitSyncData(syncData) { var url = APP_BASE + APP_SUBMIT_JSONP; $.ajax({       type: 'POST',        url: url,        data: {            'user' : wgUserName, 'data' : JSON.stringify(syncData) //, 'syncset' : syncData.syncsetURI        },        dataType: 'json'    });

}

function hidePanel(hoverPanel, targetSpan) { hoverPanel.css('display', 'none'); hoverPanel.removeClass('front_hp'); targetSpan.removeClass('selected_span'); }

function showPanel(hoverPanel, targetSpan) { hoverPanel.css('top', '24px'); hoverPanel.css('display', 'block'); moveToFront(hoverPanel, targetSpan); hoverPanel.find('.suggestion_text textarea').focus; }

function moveToFront(hoverPanel, targetSpan) { $.each($('.front_hp'), function {       $(this).removeClass('front_hp');    }); hoverPanel.addClass('front_hp');

$.each($('.selected_span'), function {       $(this).removeClass('selected_span');    }); targetSpan.addClass('selected_span'); }

function synchronize { hideOptions; requestSync(false); }

function preview(syncData) { var url = mw.config.get('wgServer') + mw.config.get('wgScript') + '?title=' + wgPageName + '&action=submit' + '&syncsetURI=' + syncData.syncsetURI; window.location.href = url; }

function getText(target) { var text = target.text; if (target.submittedTexts != undefined && target.submittedTexts != null) { var submittedText = target.submittedTexts[wgUserName]; if (submittedText != undefined && submittedText != null && submittedText.text != null) { text = submittedText.text; }   }    return text; }

function buildPreviewText(syncData) { var wikitext = ''; syncData.targetIdOrdering.forEach( function(targetId) {       var target = syncData.targetById[targetId];        wikitext += getText(target);        if (wikitext.charAt(wikitext.length-1) != '\n') {            wikitext += ' ';        }    }); return wikitext; }

function backToPage { var url = mw.config.get('wgServer') + mw.config.get('wgScript') + '/' + wgPageName; window.location.href = url; }

function getHoverHTML(panelId, target, syncData) { console.debug('Getting hover panel: '+ panelId + ' for target ' + target.id); //draw the panel var html = '<span class="hover_box">'; html += '<div id="';   html += panelId;    html += '" class="hoverpanel">'; html += ' '; html += ' '; html += ' ';

console.debug('getHoverHTML:' + html); return html; }

function getLabel(alignment) { var label = ''; if (alignment.suggestion != undefined && alignment.suggestion != null) { label = SUGGESTION_LABELS[alignment.suggestion]; } else { label = 'Unknown'; } //   if (alignment.entailment != undefined && alignment.entailment != null) { //   label = ENTAILMENT_LABELS[alignment.entailment]; //   } else if (alignment.sourceEditType != undefined && alignment.sourceEditType != null && alignment.sourceEditType != 'FACTUAL') { //   label = EDIT_TYPE_LABELS[alignment.sourceEditType]; //   } else if (alignment.suggestion != undefined && alignment.suggestion != null) { //   label = SUGGESTION_LABELS[alignment.suggestion]; //   } else { //   label = 'Unknown'; //   }    return label; }

function getInfoTooltip(alignment) { var tooltip = ''; if (alignment.sourceEditType != undefined && alignment.sourceEditType != null) { tooltip += EDIT_TYPE_LABELS[alignment.sourceEditType]; tooltip += ', '; }   if (alignment.entailment != undefined && alignment.entailment != null) { tooltip += ENTAILMENT_LABELS[alignment.entailment]; tooltip += ', '; }   tooltip += SUGGESTION_LABELS[alignment.suggestion]; tooltip += '!'; return tooltip; }

function getSuggestionHTML(index, target, syncData) { // sug, uid, count, targetLang) {   console.debug('getSuggestionHTML');    var html = '';    var sourceId = target.sourceIdOrdering[index];    if (sourceId != null) {        var source = syncData.sourceById[sourceId];        if (source != null) {            var alignment = getAlignment(sourceId, target.id, syncData);            if (alignment != null) {

var feedbackEntailment = alignment.entailment; var feedbackTranslationQuality = -1; if (alignment.feedbacks != undefined && alignment.feedbacks != null) { var feedback = alignment.feedbacks[wgUserName]; if (feedback != undefined && feedback != null) { if (feedback.entailment != null) { feedbackEntailment = feedback.entailment; }                       if (feedback.translationQuality != null) { feedbackTranslationQuality = feedback.translationQuality; }                   }                }

var suggestionId = 'SG_' + target.id + '_' + sourceId; html += '<div id="' + suggestionId + '" class="suggestion sug_';               html += alignment.suggestion.toLowerCase;                html += '" style="display:';                html += (index > 0 ? 'none' : 'block'); // display first suggestion                html += ';">'; html += '<div class="sug_header">'; html += getLabel(alignment); html += '<a href="javascript:void(0);" title="';               html += getInfoTooltip(alignment);                html += '">'; html += ' <img src="';               html += INFO_BUTTON_ICON;                html += '"></a> '; html += '<div class="sug_src_trans" title="translation (click to add, shift-click to replace)">'; html += source.translation; html += ' <img src="';               html += FLAGS_ICONS[target.lang];                html += '"> '; html += '<div class="sug_src_text" title="source">'; html += source.text; html += ' <img src="';               html += FLAGS_ICONS[source.lang];                html += '"> ';

html += ' '; //end of suggestion

//scoring panel (separate panel from suggestion) var feedbackId = 'FB_' + target.id + '_' + sourceId; html += '<div id="'+feedbackId+'" class="feedback" style="display:'+(index > 0 ? 'none' : 'block')+';">';

//feedback header html += '<div class="feedback_header">'; //feedback header label html += '<ul class="feedback_label">'; html += '<li>Feedback: </li>'; html += '<li><a href="javascript:void(0);" title="Please provide your feedback, the system will learn from it">'; html += ' <img src="'+INFO_BUTTON_ICON+'"></a></li>'; html += '</ul>'; //feedback header like buttons html += '<ul class="feedback_buttons">'; html += "<li><a class=\"show_feedback\" href=\"javascript:void(0);\" onclick=\"showFeedback('" + feedbackId + "');\"><img src=\"" + SHOW_ICON + "\"></a></li>"; html += "<li><a class=\"hide_feedback\" href=\"javascript:void(0);\" onclick=\"hideFeedback('" + feedbackId + "');\"><img src="+HIDE_ICON+"></a></li>"; html += '</ul>'; html += ' ';//end scoring header

//feedback form html += '<div class="feedback_form" style="display:none;">'; html += '<div class="entailment_feedback">'; $.each(ENTAILMENT_LABELS, function(key, label) {                   html += '<input id="' + feedbackId + '_' + key.toLowerCase + '" type="radio" value="' + key + '" name="' + feedbackId + '_entailment_feedback"';                    if (key == feedbackEntailment) {                        html += ' checked="true"';                    }                    html += '/>';                    html += '<label for="' + feedbackId + '_' + key.toLower + '">' + label + ' ';                });

html += ' '; //end of entailment feedback

html += '<div class="translation_quality_feedback">'; //       html += '<input id="fb_translation_quality_'+feedbackId+'" type="checkbox"/>'; html += '<label for="fb_translation_quality_'+feedbackId+'">Translation quality: ';

html += ' '; for(var i=0;i<5;i++) { html += '<li><a id="';                   html += i;                    html += '" href=\"javascript:void(0);\">'; // onclick=\"registerScore('"+target.id+"', "+i+")\">";                           if (i <= feedbackTranslationQuality) {                        html += '<img src="'+STAR_ON_IMG+'">';                    } else {                        html += '<img src="'+STAR_OFF_IMG+'">';                                    }                    html += "</a></li>";                }                html += '</ul>';

html += ' ';//end of translation quality feedback

//       html += '<div class="alignment_feedback">'; //       html += '<label for="' + feedbackId + '_alignment_feedback">Irrelevant (detach): '; //       html += '<input id="' + feedbackId + '_alignment_feedback" type="checkbox" value="detach" name="' + feedbackId + '_alignment_feedback" />'; //       html += ' '; // end of alignment feedback

html += ' ';//end feedback form

html += ' ';//end scoring }       }    }    console.debug('getSuggestionHTML: ' + html); return html; }

function showFeedback(feedbackId) { $('#' + feedbackId + ' .feedback_form').css('display', 'block'); $('#' + feedbackId + ' .show_feedback').css('display', 'none'); $('#' + feedbackId + ' .hide_feedback').css('display', 'inline'); }

function hideFeedback(feedbackId) { $('#' + feedbackId + ' .feedback_form').css('display', 'none'); $('#' + feedbackId + ' .show_feedback').css('display', 'inline'); $('#' + feedbackId + ' .hide_feedback').css('display', 'none'); }

function showPrevSuggestion(hid, total) { var i = 0; $.each($('#' + hid + ' .suggestion'), function(index, div){       if($(this).css('display') == 'block' && index != 0) {                      $(this).css('display', 'none');            $('#' + hid + ' .feedback:eq('+(index)+')').css('display', 'none');            console.debug(index);            i = index;                      return;        }    }); i--; if(i >= 0) { $('#' + hid + ' .sug_next img').css('display', 'block'); if (i == 0) { $('#' + hid + ' .sug_prev img').css('display', 'none'); }       $('#' + hid + ' .suggestion:eq('+(i)+')').css('display', 'block'); $('#' + hid + ' .feedback:eq('+(i)+')').css('display', 'block'); $('#' + hid + ' .sug_paging').html((i+1) + '/' + total); } }

function showNextSuggestion(hid, total) { var i = 0; $.each($('#' + hid + ' .suggestion'), function(index, div) {       if($(this).css('display') == 'block' && index < total -1) {            $(this).css('display', 'none');            $('#' + hid + ' .feedback:eq('+(index)+')').css('display', 'none');            console.debug(index);            i = index;            return;        }    }); i++; if(i < total) { $('#' + hid + ' .sug_prev img').css('display', 'block'); if(i == total -1) { $('#' + hid + ' .sug_next img').css('display', 'none'); }       $('#' + hid + ' .suggestion:eq('+(i)+')').css('display', 'block'); $('#' + hid + ' .feedback:eq('+(i)+')').css('display', 'block'); $('#' + hid + ' .sug_paging').html((i+1) + '/' + total); } }

function showOptions { $('#cosyne_options_form').css('display', 'block'); $('#show_cosyne_options').css('display', 'none'); $('#hide_cosyne_options').css('display', 'inline'); }

function hideOptions { $('#cosyne_options_form').css('display', 'none'); $('#show_cosyne_options').css('display', 'inline'); $('#hide_cosyne_options').css('display', 'none'); }