<commit_before>var warnOnRedirect=true;$(document).ready(function(){insertOnRedirectWarning();onWizardPage()});function onWizardPage(){attachHelpTooltips();attachDatePickers();attachDateTimePickers();attachTableEvents();handleWizardTable();new TableEditor().init({tableIdentifier:"div.table",rowIdentifier:"div.row",columnIdentifier:"div.column",headerIdentifier:"div.header"});new OntologyChooser().init();new SelectAddMore().init({rel:"term",url:baseUrl+"/termEditor",vars:"ontologies",label:"add more...",style:"addMore",onClose:function(a){refreshWebFlow()}});new SelectAddMore().init({rel:"template",url:baseUrl+"/templateEditor",vars:"entity,ontologies",label:"add / modify..",style:"modify",onClose:function(a){refreshWebFlow()}});new SelectAddMore().init({rel:"person",url:baseUrl+"/person/list?dialog=true",vars:"person",label:"add / modify persons...",style:"modify",onClose:function(a){refreshWebFlow()}});new SelectAddMore().init({rel:"role",url:baseUrl+"/personRole/list?dialog=true",vars:"role",label:"add / modify roles...",style:"modify",onClose:function(a){refreshWebFlow()}});$("#accordion").accordion()}function insertOnRedirectWarning(){$("a").each(function(){var a=$(this);var b=/^#/gi;if(!a.attr("href").match(/^#/gi)&&!a.attr("href").match(/\/([^\/]+)\/wizard\/pages/gi)){a.bind("click",function(){if(warnOnRedirect){return onDirectWarning()}})}})}function onDirectWarning(){return confirm("Warning: navigating away from the wizard causes loss of work and unsaved data. Are you sure you want to continue?")}function attachHelpTooltips(){$("div#wizard").find("div.helpIcon").each(function(){helpIcon=$(this);helpContent=helpIcon.parent().find("div.helpContent");if(!helpContent.html()){helpContent=helpIcon.parent().parent().find("div.helpContent")}var html=(helpContent.html())?helpContent.html():"";if(html){var specialContent=html.match(/\[([^:]+)\:([^\]]+)\]/);if(specialContent){eval(specialContent[1]+"('"+specialContent[2]+"',helpContent)")}helpIcon.qtip({content:"leftMiddle",position:{corner:{tooltip:"leftMiddle",target:"rightMiddle"}},style:{border:{width:5,radius:10},padding:10,textAlign:"center",tip:true,name:"blue"},content:helpContent.html(),show:"mouseover",hide:"mouseout",api:{beforeShow:function(){}}});helpContent.remove()}})}function youtube(b,a){a.html("

");var c={allowScriptAccess:"always"};var d={id:"myytplayer_"+b};swfobject.embedSWF("http://www.youtube.com/v/"+b+"?enablejsapi=1&playerapiid=ytplayer_"+b,b,"200","150","8",null,null,c,d)}function onYouTubePlayerReady(a){ytplayer=document.getElementById("my"+a);ytplayer.playVideo()}function attachDatePickers(){$("div#wizard").find("input[type=text][rel$='date']").each(function(){$(this).datepicker({numberOfMonths:3,showButtonPanel:true,changeMonth:true,changeYear:true,dateFormat:"dd/mm/yy",altField:"#"+$(this).attr("name")+"Example",altFormat:"DD, d MM, yy"})})}function attachDateTimePickers(){$("div#wizard").find("input[type=text][rel$='datetime']").each(function(){$(this).datepicker({changeMonth:true,changeYear:true,dateFormat:"dd/mm/yy",altField:"#"+$(this).attr("name")+"Example",altTimeField:"#"+$(this).attr("name")+"Example2",altFormat:"DD, d MM, yy",showTime:true,time24h:true})})}function attachTableEvents(){$("div#wizard").find("div.row").each(function(){$(this).hover(function(){$(this).addClass("highlight")},function(){$(this).removeClass("highlight")})})}function handleWizardTable(){var b=this;var a=$("div#wizard").find("div.table");a.each(function(){var d=$(this);var g=(d.next().attr("class")=="sliderContainer")?d.next():null;var h=d.find("div.header");var f=20;var e=0;var c=[];h.children().each(function(){var m=$(this);var k=m.width();var i=parseInt(m.css("padding-left"),10)+parseInt(m.css("padding-right"),10);var l=parseInt(m.css("margin-left"),10)+parseInt(m.css("margin-right"),10);var j=parseInt(m.css("borderLeftWidth"),10)+parseInt(m.css("borderRightWidth"),10);if(i){k+=i}if(l){k+=l}if(j){k+=j}f+=k;c[e]=m.width();e++});h.css({width:f+"px"});d.find("div.row").each(function(){var j=$(this);var i=0;j.children().each(function(){$(this).css({width:c[i]+"px"});i++});j.css({width:f+"px"})});if(g){if(h.width()<d.width()){g.hide()}else{g.slider({value:1,min:1,max:h.width()-d.width(),step:1,slide:function(i,j){d.find("div.header, div.row").css({"margin-left":(1-j.value)+"px"})}})}}})}function showExampleReltime(a){var d=a.name;var b=function(f,g,e){if(e.status==200){document.getElementById(d+"Example").value=f}};var c=function(e,g,f){document.getElementById(d+"Example").value=""};$.ajax({url:baseUrl+"/wizard/ajaxParseRelTime?reltime="+a.value,success:b,error:c})}function fileUploadField(a){new AjaxUpload("#upload_button_"+a,{action:baseUrl+"/file/upload",data:{},name:a,autoSubmit:true,onChange:function(b,c){oldFile=$("#"+a).val();if(oldFile!=""){if(!confirm("The old file is deleted when uploading a new file. Do you want to continue?")){return false}}this.setData({field:a,oldFile:oldFile});$("#"+a+"Example").html("Uploading "+createFileHTML(b))},onComplete:function(c,b){if(b==""){$("#"+a).val("");$("#"+a+"Example").html('Error uploading '+createFileHTML(c)+"")}else{$("#"+a).val(b);$("#"+a+"Example").html("Uploaded "+createFileHTML(c))}}})}function createFileHTML(a){return''+a+""}function addPublication(a){jQuery.ajax({type:"GET",url:baseUrl+"/publication/getID?"+$("#"+a+"_form").serialize(),success:function(c,e){var d=parseInt(c);var b=getPublicationIds(a);if($.inArray(d,b)==-1){b[b.length]=d;$("#"+a+"_ids").val(b.join(","));showPublication(a,d,$("#"+a+"_form").find("[name=publication-title]").val(),$("#"+a+"_form").find("[name=publication-authorsList]").val(),b.length-1);$("#"+a+"_none").css("display","none")}},error:function(b,d,c){alert("Publication could not be added.")}});return false}function removePublication(b,d){var c=getPublicationIds(b);if($.inArray(d,c)!=-1){c.splice($.inArray(d,c),1);$("#"+b+"_ids").val(c.join(","));var a=$("#"+b+"_item_"+d);if(a){a.remove()}if(c.length==0){$("#"+b+"_none").css("display","inline")}}}function getPublicationIds(a){var c=$("#"+a+"_ids").val();if(c==""){return new Array()}else{ids_array=c.split(",");for(var b=0;b<ids_array.length;b++){ids_array[b]=parseInt(ids_array[b])}return ids_array}}function showPublication(c,a,g,f,h){var e=document.createElement("img");e.className="famfamfam delete_button";e.setAttribute("alt","remove this publication");e.setAttribute("src",baseUrl+"/plugins/famfamfam-1.0.1/images/icons/delete.png");e.onclick=function(){removePublication(c,a);return false};var b=document.createElement("div");b.className="title";b.appendChild(document.createTextNode(g));var d=document.createElement("div");d.className="authors";d.appendChild(document.createTextNode(f));var i=document.createElement("li");i.setAttribute("id",c+"_item_"+a);i.className=h%2==0?"even":"odd";i.appendChild(e);i.appendChild(b);i.appendChild(d);$("#"+c+"_list").append(i)}function createPublicationDialog(a){if($("."+a+"_publication_dialog").length==0){$("#"+a+"_dialog").dialog({title:"Add publication",autoOpen:false,width:800,height:400,modal:true,dialogClass:a+"_publication_dialog",position:"center",buttons:{Add:function(){addPublication(a);$(this).dialog("close")},Close:function(){$(this).dialog("close")}},close:function(){}}).width(790).height(400)}else{$("#"+a+"_dialog").remove()}}function openPublicationDialog(a){var b=$("#"+a);b.autocomplete("close");b.val("");$("#"+a+"_dialog").dialog("open");b.focus();enableButton("."+a+"_publication_dialog","Add",false)}function getDialogButton(b,a){var e=$(b+" .ui-dialog-buttonpane button");for(var d=0;d<e.length;++d){var c=$(e[d]);if(c.text()==a){return c}}return null}function enableButton(b,a,c){var d=getDialogButton(b,a);if(d){if(c){d.attr("disabled","");d.removeClass("ui-state-disabled")}else{d.attr("disabled","disabled");d.addClass("ui-state-disabled")}}}function addContact(b){var e=$("#"+b+"_person").val();var a=$("#"+b+"_role").val();var c=e+"-"+a;var d=getContactIds(b);if($.inArray(c,d)==-1){d[d.length]=c;$("#"+b+"_ids").val(d.join(","));showContact(b,c,$("#"+b+"_person  :selected").text(),$("#"+b+"_role :selected").text(),d.length-1);$("#"+b+"_none").css("display","none")}}function removeContact(b,c){var d=getContactIds(b);if($.inArray(c,d)!=-1){d.splice($.inArray(c,d),1);$("#"+b+"_ids").val(d.join(","));var a=$("#"+b+"_item_"+c);if(a){a.remove()}if(d.length==0){$("#"+b+"_none").css("display","inline")}}}function getContactIds(a){var b=$("#"+a+"_ids").val();if(b==""){return new Array()}else{ids_array=b.split(",");return ids_array}}function showContact(c,a,d,f,h){var g=document.createElement("img");g.className="famfamfam delete_button";g.setAttribute("alt","remove this person");g.setAttribute("src",baseUrl+"/plugins/famfamfam-1.0.1/images/icons/delete.png");g.onclick=function(){removeContact(c,a);return false};var b=document.createElement("div");b.className="person";b.appendChild(document.createTextNode(d));var e=document.createElement("div");e.className="role";e.appendChild(document.createTextNode(f));var i=document.createElement("li");i.setAttribute("id",c+"_item_"+a);i.className=h%2==0?"even":"odd";i.appendChild(g);i.appendChild(b);i.appendChild(e);$("#"+c+"_list").append(i)}function addUser(a){id=parseInt($("#"+a+"_form select").val());var b=getUserIds(a);if($.inArray(id,b)==-1){b[b.length]=id;$("#"+a+"_ids").val(b.join(","));showUser(a,id,$("#"+a+"_form select option:selected").text(),b.length-1);$("#"+a+"_none").css("display","none")}return false}function removeUser(b,d){var c=getUserIds(b);if($.inArray(d,c)!=-1){c.splice($.inArray(d,c),1);$("#"+b+"_ids").val(c.join(","));var a=$("#"+b+"_item_"+d);if(a){a.remove()}if(c.length==0){$("#"+b+"_none").css("display","inline")}}}function getUserIds(a){var c=$("#"+a+"_ids").val();if(c==""){return new Array()}else{ids_array=c.split(",");for(var b=0;b<ids_array.length;b++){ids_array[b]=parseInt(ids_array[b])}return ids_array}}function showUser(c,g,f,d){var b=document.createElement("img");b.className="famfamfam delete_button";b.setAttribute("alt","remove this user");b.setAttribute("src",baseUrl+"/plugins/famfamfam-1.0.1/images/icons/delete.png");b.onclick=function(){removeUser(c,g);return false};var e=document.createElement("div");e.className="username";e.appendChild(document.createTextNode(f));var a=document.createElement("li");a.setAttribute("id",c+"_item_"+g);a.className=d%2==0?"even":"odd";a.appendChild(b);a.appendChild(e);$("#"+c+"_list").append(a)}function createUserDialog(a){if($("."+a+"_user_dialog").length==0){$("#"+a+"_dialog").dialog({title:"Add user",autoOpen:false,width:800,height:400,modal:true,dialogClass:a+"_user_dialog",position:"center",buttons:{Add:function(){addUser(a);$(this).dialog("close")},Close:function(){$(this).dialog("close")}},close:function(){}}).width(790).height(400)}else{$("#"+a+"_dialog").remove()}}function openUserDialog(a){var b=$("#"+a);b.val("");$("#"+a+"_dialog").dialog("open");b.focus()};<commit_msg>Automated continuous integration commit of minified JS/CSS<commit_after>var warnOnRedirect=true;$(document).ready(function(){insertOnRedirectWarning();onWizardPage()});function onWizardPage(){attachHelpTooltips();attachDatePickers();attachDateTimePickers();attachTableEvents();handleWizardTable();new TableEditor().init({tableIdentifier:"div.table",rowIdentifier:"div.row",columnIdentifier:"div.column",headerIdentifier:"div.header"});new OntologyChooser().init();new SelectAddMore().init({rel:"term",url:baseUrl+"/termEditor",vars:"ontologies",label:"add more...",style:"addMore",onClose:function(a){refreshWebFlow()}});new SelectAddMore().init({rel:"template",url:baseUrl+"/templateEditor",vars:"entity,ontologies",label:"add / modify..",style:"modify",onClose:function(a){refreshWebFlow()}});new SelectAddMore().init({rel:"person",url:baseUrl+"/person/list?dialog=true",vars:"person",label:"add / modify persons...",style:"modify",onClose:function(a){refreshWebFlow()}});new SelectAddMore().init({rel:"role",url:baseUrl+"/personRole/list?dialog=true",vars:"role",label:"add / modify roles...",style:"modify",onClose:function(a){refreshWebFlow()}});$("#accordion").accordion()}function insertOnRedirectWarning(){$("a").each(function(){var a=$(this);var b=/^#/gi;if(!a.attr("href").match(/^#/gi)&&!a.attr("href").match(/\/([^\/]+)\/wizard\/pages/gi)){a.bind("click",function(){if(warnOnRedirect){return onDirectWarning()}})}})}function onDirectWarning(){return confirm("Warning: navigating away from the wizard causes loss of work and unsaved data. Are you sure you want to continue?")}function attachHelpTooltips(){$("div#wizard").find("div.helpIcon").each(function(){helpIcon=$(this);helpContent=helpIcon.parent().find("div.helpContent");if(!helpContent.html()){helpContent=helpIcon.parent().parent().find("div.helpContent")}var html=(helpContent.html())?helpContent.html():"";if(html){var specialContent=html.match(/\[([^:]+)\:([^\]]+)\]/);if(specialContent){eval(specialContent[1]+"('"+specialContent[2]+"',helpContent)")}helpIcon.qtip({content:"leftMiddle",position:{corner:{tooltip:"leftMiddle",target:"rightMiddle"}},style:{border:{width:5,radius:10},padding:10,textAlign:"center",tip:true,name:"blue"},content:helpContent.html(),show:"mouseover",hide:"mouseout",api:{beforeShow:function(){}}});helpContent.remove()}})}function youtube(b,a){a.html("

");var c={allowScriptAccess:"always"};var d={id:"myytplayer_"+b};swfobject.embedSWF("http://www.youtube.com/v/"+b+"?enablejsapi=1&playerapiid=ytplayer_"+b,b,"200","150","8",null,null,c,d)}function onYouTubePlayerReady(a){ytplayer=document.getElementById("my"+a);ytplayer.playVideo()}function attachDatePickers(){$("div#wizard").find("input[type=text][rel$='date']").each(function(){$(this).datepicker({numberOfMonths:3,showButtonPanel:true,changeMonth:true,changeYear:true,dateFormat:"dd/mm/yy",altField:"#"+$(this).attr("name")+"Example",altFormat:"DD, d MM, yy"})})}function attachDateTimePickers(){$("div#wizard").find("input[type=text][rel$='datetime']").each(function(){$(this).datepicker({changeMonth:true,changeYear:true,dateFormat:"dd/mm/yy",altField:"#"+$(this).attr("name")+"Example",altTimeField:"#"+$(this).attr("name")+"Example2",altFormat:"DD, d MM, yy",showTime:true,time24h:true})})}function attachTableEvents(){$("div#wizard").find("div.row").each(function(){$(this).hover(function(){$(this).addClass("highlight")},function(){$(this).removeClass("highlight")})})}function handleWizardTable(){var b=this;var a=$("div#wizard").find("div.table");a.each(function(){var d=$(this);var g=(d.next().attr("class")=="sliderContainer")?d.next():null;var h=d.find("div.header");var f=20;var e=0;var c=[];h.children().each(function(){var m=$(this);var k=m.width();var i=parseInt(m.css("padding-left"),10)+parseInt(m.css("padding-right"),10);var l=parseInt(m.css("margin-left"),10)+parseInt(m.css("margin-right"),10);var j=parseInt(m.css("borderLeftWidth"),10)+parseInt(m.css("borderRightWidth"),10);if(i){k+=i}if(l){k+=l}if(j){k+=j}f+=k;c[e]=m.width();e++});h.css({width:f+"px"});d.find("div.row").each(function(){var j=$(this);var i=0;j.children().each(function(){$(this).css({width:c[i]+"px"});i++});j.css({width:f+"px"})});if(g){if(h.width()<d.width()){g.hide()}else{g.slider({value:1,min:1,max:h.width()-d.width(),step:1,slide:function(i,j){d.find("div.header, div.row").css({"margin-left":(1-j.value)+"px"})}})}}})}function showExampleReltime(a){var d=a.name;var b=function(f,g,e){if(e.status==200){document.getElementById(d+"Example").value=f}};var c=function(e,g,f){document.getElementById(d+"Example").value=""};$.ajax({url:baseUrl+"/wizard/ajaxParseRelTime?reltime="+a.value,success:b,error:c})}function fileUploadField(a){new AjaxUpload("#upload_button_"+a,{action:baseUrl+"/file/upload",data:{},name:a,autoSubmit:true,onChange:function(b,c){oldFile=$("#"+a).val();if(oldFile!=""){if(!confirm("The old file is deleted when uploading a new file. Do you want to continue?")){return false}}this.setData({field:a,oldFile:oldFile});$("#"+a+"Example").html("Uploading "+createFileHTML(b))},onComplete:function(c,b){if(b==""){$("#"+a).val("");$("#"+a+"Example").html('Error uploading '+createFileHTML(c)+"")}else{$("#"+a).val(b);$("#"+a+"Example").html("Uploaded "+createFileHTML(c))}}})}function createFileHTML(a){return''+a+""}function addPublication(a){jQuery.ajax({type:"GET",url:baseUrl+"/publication/getID?"+$("#"+a+"_form").serialize(),success:function(c,e){var d=parseInt(c);var b=getPublicationIds(a);if($.inArray(d,b)==-1){b[b.length]=d;$("#"+a+"_ids").val(b.join(","));showPublication(a,d,$("#"+a+"_form").find("[name=publication-title]").val(),$("#"+a+"_form").find("[name=publication-authorsList]").val(),b.length-1);$("#"+a+"_none").css("display","none")}},error:function(b,d,c){alert("Publication could not be added.")}});return false}function removePublication(b,d){var c=getPublicationIds(b);if($.inArray(d,c)!=-1){c.splice($.inArray(d,c),1);$("#"+b+"_ids").val(c.join(","));var a=$("#"+b+"_item_"+d);if(a){a.remove()}if(c.length==0){$("#"+b+"_none").css("display","inline")}}}function getPublicationIds(a){var c=$("#"+a+"_ids").val();if(c==""){return new Array()}else{ids_array=c.split(",");for(var b=0;b<ids_array.length;b++){ids_array[b]=parseInt(ids_array[b])}return ids_array}}function showPublication(c,a,g,f,h){var e=document.createElement("img");e.className="famfamfam delete_button";e.setAttribute("alt","remove this publication");e.setAttribute("src",baseUrl+"/plugins/famfamfam-1.0.1/images/icons/delete.png");e.onclick=function(){removePublication(c,a);return false};var b=document.createElement("div");b.className="title";b.appendChild(document.createTextNode(g));var d=document.createElement("div");d.className="authors";d.appendChild(document.createTextNode(f));var i=document.createElement("li");i.setAttribute("id",c+"_item_"+a);i.className=h%2==0?"even":"odd";i.appendChild(e);i.appendChild(b);i.appendChild(d);$("#"+c+"_list").append(i)}function createPublicationDialog(a){if($("."+a+"_publication_dialog").length==0){$("#"+a+"_dialog").dialog({title:"Add publication",autoOpen:false,width:800,height:400,modal:true,dialogClass:a+"_publication_dialog",position:"center",buttons:{Add:function(){addPublication(a);$(this).dialog("close")},Close:function(){$(this).dialog("close")}},close:function(){}}).width(790).height(400)}else{$("#"+a+"_dialog").remove()}}function openPublicationDialog(a){var b=$("#"+a);b.autocomplete("close");b.val("");$("#"+a+"_dialog").dialog("open");b.focus();enableButton("."+a+"_publication_dialog","Add",false)}function getDialogButton(b,a){var e=$(b+" .ui-dialog-buttonpane button");for(var d=0;d<e.length;++d){var c=$(e[d]);if(c.text()==a){return c}}return null}function enableButton(b,a,c){var d=getDialogButton(b,a);if(d){if(c){d.attr("disabled","");d.removeClass("ui-state-disabled")}else{d.attr("disabled","disabled");d.addClass("ui-state-disabled")}}}function addContact(b){var e=$("#"+b+"_person").val();var a=$("#"+b+"_role").val();if(e==""||e==0||a==""||a==0){alert("Please select both a person and a role.");return false}var c=e+"-"+a;var d=getContactIds(b);if($.inArray(c,d)==-1){d[d.length]=c;$("#"+b+"_ids").val(d.join(","));showContact(b,c,$("#"+b+"_person  :selected").text(),$("#"+b+"_role :selected").text(),d.length-1);$("#"+b+"_none").css("display","none")}return true}function removeContact(b,c){var d=getContactIds(b);if($.inArray(c,d)!=-1){d.splice($.inArray(c,d),1);$("#"+b+"_ids").val(d.join(","));var a=$("#"+b+"_item_"+c);if(a){a.remove()}if(d.length==0){$("#"+b+"_none").css("display","inline")}}}function getContactIds(a){var b=$("#"+a+"_ids").val();if(b==""){return new Array()}else{ids_array=b.split(",");return ids_array}}function showContact(c,a,d,f,h){var g=document.createElement("img");g.className="famfamfam delete_button";g.setAttribute("alt","remove this person");g.setAttribute("src",baseUrl+"/plugins/famfamfam-1.0.1/images/icons/delete.png");g.onclick=function(){removeContact(c,a);return false};var b=document.createElement("div");b.className="person";b.appendChild(document.createTextNode(d));var e=document.createElement("div");e.className="role";e.appendChild(document.createTextNode(f));var i=document.createElement("li");i.setAttribute("id",c+"_item_"+a);i.className=h%2==0?"even":"odd";i.appendChild(g);i.appendChild(b);i.appendChild(e);$("#"+c+"_list").append(i)}function addUser(a){id=parseInt($("#"+a+"_form select").val());var b=getUserIds(a);if($.inArray(id,b)==-1){b[b.length]=id;$("#"+a+"_ids").val(b.join(","));showUser(a,id,$("#"+a+"_form select option:selected").text(),b.length-1);$("#"+a+"_none").css("display","none")}return false}function removeUser(b,d){var c=getUserIds(b);if($.inArray(d,c)!=-1){c.splice($.inArray(d,c),1);$("#"+b+"_ids").val(c.join(","));var a=$("#"+b+"_item_"+d);if(a){a.remove()}if(c.length==0){$("#"+b+"_none").css("display","inline")}}}function getUserIds(a){var c=$("#"+a+"_ids").val();if(c==""){return new Array()}else{ids_array=c.split(",");for(var b=0;b<ids_array.length;b++){ids_array[b]=parseInt(ids_array[b])}return ids_array}}function showUser(c,g,f,d){var b=document.createElement("img");b.className="famfamfam delete_button";b.setAttribute("alt","remove this user");b.setAttribute("src",baseUrl+"/plugins/famfamfam-1.0.1/images/icons/delete.png");b.onclick=function(){removeUser(c,g);return false};var e=document.createElement("div");e.className="username";e.appendChild(document.createTextNode(f));var a=document.createElement("li");a.setAttribute("id",c+"_item_"+g);a.className=d%2==0?"even":"odd";a.appendChild(b);a.appendChild(e);$("#"+c+"_list").append(a)}function createUserDialog(a){if($("."+a+"_user_dialog").length==0){$("#"+a+"_dialog").dialog({title:"Add user",autoOpen:false,width:800,height:400,modal:true,dialogClass:a+"_user_dialog",position:"center",buttons:{Add:function(){addUser(a);$(this).dialog("close")},Close:function(){$(this).dialog("close")}},close:function(){}}).width(790).height(400)}else{$("#"+a+"_dialog").remove()}}function openUserDialog(a){var b=$("#"+a);b.val("");$("#"+a+"_dialog").dialog("open");b.focus()};<|endoftext|>


<commit_before>// Currently requires polyfills for
// Array#forEach
// Object.keys
// String#trim

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['q'], function(Q) {
      return factory(XMLHttpRequest, Q)
    })
  } else if (typeof exports === 'object' && typeof module === 'object') {
    // CommonJS, mainly for testing
    module.exports = factory
  } else {
    if (typeof Q !== 'undefined') {
      factory(XMLHttpRequest, Q)
    }
  }
})(function(XHR, Q) {
  // shallow extend with varargs
  function extend(dst) {
    Array.prototype.forEach.call(arguments, function(obj) {
      if (obj && obj !== dst) {
        Object.keys(obj).forEach(function(key) {
          dst[key] = obj[key]
        })
      }
    })

    return dst
  }

  function lowercase(str) {
    return (str || '').toLowerCase()
  }

  function parseHeaders(headers) {
    var parsed = {}, key, val, i

    if (!headers) return parsed

    headers.split('\n').forEach(function(line) {
      i = line.indexOf(':')
      key = lowercase(line.substr(0, i).trim())
      val = line.substr(i + 1).trim()

      if (key) {
        if (parsed[key]) {
          parsed[key] += ', ' + val
        } else {
          parsed[key] = val
        }
      }
    })

    return parsed
  }

  function headersGetter(headers) {
    var headersObj = typeof headers === 'object' ? headers : undefined;

    return function(name) {
      if (!headersObj) headersObj = parseHeaders(headers)

      if (name) {
        return headersObj[lowercase(name)]
      }

      return headersObj
    }
  }

  function transformData(data, headers, fns) {
    if (typeof fns === 'function') {
      return fns(data, headers)
    }

    fns.forEach(function(fn) {
      data = fn(data, headers)
    })

    return data
  }

  function isSuccess(status) {
    return 200 <= status && status < 300
  }

  function forEach(obj, iterator, context) {
    var keys = Object.keys(obj)
    keys.forEach(function(key) {
      iterator.call(context, obj[key], key)
    })
    return keys
  }

  function forEachSorted(obj, iterator, context) {
    var keys = Object.keys(obj).sort()
    keys.forEach(function(key) {
      iterator.call(context, obj[key], key)
    })
    return keys
  }

  function buildUrl(url, params) {
    if (!params) return url
    var parts = []
    forEachSorted(params, function(value, key) {
      if (value == null) return
      if (!Array.isArray(value)) value = [value]

      value.forEach(function(v) {
        if (typeof v === 'object') {
          v = JSON.stringify(v)
        }
        parts.push(encodeURIComponent(key) + '=' +
                   encodeURIComponent(v))
      })
    })
    return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&')
  }

  Q.xhr = function (requestConfig) {
    var defaults = Q.xhr.defaults,
    config = {
      transformRequest: defaults.transformRequest,
      transformResponse: defaults.transformResponse
    },
    mergeHeaders = function(config) {
      var defHeaders = defaults.headers,
          reqHeaders = extend({}, config.headers),
          defHeaderName, lowercaseDefHeaderName, reqHeaderName,

      execHeaders = function(headers) {
        forEach(headers, function(headerFn, header) {
          if (typeof headerFn === 'function') {
            var headerContent = headerFn()
            if (headerContent != null) {
              headers[header] = headerContent
            } else {
              delete headers[header]
            }
          }
        })
      }

      defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);

      // execute if header value is function
      execHeaders(defHeaders);
      execHeaders(reqHeaders);

      // using for-in instead of forEach to avoid unecessary iteration after header has been found
      defaultHeadersIteration:
      for (defHeaderName in defHeaders) {
        lowercaseDefHeaderName = lowercase(defHeaderName);

        for (reqHeaderName in reqHeaders) {
          if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
            continue defaultHeadersIteration;
          }
        }

        reqHeaders[defHeaderName] = defHeaders[defHeaderName];
      }

      return reqHeaders;
    },
    headers = mergeHeaders(requestConfig)

    extend(config, requestConfig)
    config.headers = headers
    config.method = (config.method || 'GET').toUpperCase()

    var serverRequest = function(config) {
      headers = config.headers
      var reqData = transformData(config.data, headersGetter(headers), config.transformRequest)

      // strip content-type if data is undefined TODO does it really matter?
      if (config.data == null) {
        forEach(headers, function(value, header) {
          if (lowercase(header) === 'content-type') {
              delete headers[header]
          }
        })
      }

      if (config.withCredentials == null && defaults.withCredentials != null) {
        config.withCredentials = defaults.withCredentials
      }

      // send request
      return sendReq(config, reqData, headers).then(transformResponse, transformResponse)
    },

    transformResponse = function(response) {
      response.data = transformData(response.data, response.headers, config.transformResponse)
      return isSuccess(response.status) ? response : Q.reject(response)
    },

    promise = Q.when(config)

    // build a promise chain with request interceptors first, then the request, and response interceptors
    Q.xhr.interceptors.filter(function(interceptor) {
        return !!interceptor.request || !!interceptor.requestError
      }).map(function(interceptor) {
        return { success: interceptor.request, failure: interceptor.requestError }
      })
    .concat({ success: serverRequest })
    .concat(Q.xhr.interceptors.filter(function(interceptor) {
        return !!interceptor.response || !!interceptor.responseError
      }).map(function(interceptor) {
        return { success: interceptor.response, failure: interceptor.responseError }
      })
    ).forEach(function(then) {
      promise = promise.then(then.success, then.failure)
    })

    return promise
  }

  var contentTypeJson = { 'Content-Type': 'application/json;charset=utf-8' }

  Q.xhr.defaults = {
    transformResponse: [function(data, headers) {
      if (typeof data === 'string' && (headers('content-type') || '').indexOf('json') >= 0) {
        data = JSON.parse(data)
      }
      return data
    }],

    transformRequest: [function(data) {
      return !!data && typeof data === 'object' && data.toString() !== '[object File]' ?
        JSON.stringify(data) : data
    }],

    headers: {
      common: {
        'Accept': 'application/json, text/plain, */*'
      },
      post:   contentTypeJson,
      put:    contentTypeJson,
      patch:  contentTypeJson
    },
  }

  Q.xhr.interceptors = []
  Q.xhr.pendingRequests = []

  function sendReq(config, reqData, reqHeaders) {
    var deferred = Q.defer(),
        promise = deferred.promise,
        url = buildUrl(config.url, config.params),
        xhr = new XHR(),
        aborted = -1,
        status,
        timeoutId

    Q.xhr.pendingRequests.push(config)

    xhr.open(config.method, url, true)
    forEach(config.headers, function(value, key) {
      if (value) {
        xhr.setRequestHeader(key, value)
      }
    })

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var response, responseHeaders
        if (status !== aborted) {
          responseHeaders = xhr.getAllResponseHeaders()
          // responseText is the old-school way of retrieving response (supported by IE8 & 9)
          // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
          response = xhr.responseType ? xhr.response : xhr.responseText
        }

        // cancel timeout and subsequent timeout promise resolution
        timeoutId && clearTimeout(timeoutId)
        status = status || xhr.status
        xhr = null

        // normalize status, including accounting for IE bug (http://bugs.jquery.com/ticket/1450)
        status = Math.max(status == 1223 ? 204 : status, 0)

        var idx = Q.xhr.pendingRequests.indexOf(config)
        if (idx !== -1) Q.xhr.pendingRequests.splice(idx, 1)

        ;(isSuccess(status) ? deferred.resolve : deferred.reject)({
          data: response,
          status: status,
          headers: headersGetter(responseHeaders),
          config: config
        })
      }
    }

    xhr.onprogress = function (progress) {
      deferred.notify(progress)
    }

    if (config.withCredentials) {
      xhr.withCredentials = true
    }

    if (config.responseType) {
      xhr.responseType = config.responseType;
    }

    xhr.send(reqData || null)

    if (config.timeout > 0) {
      timeoutId = setTimeout(function() {
        status = aborted;
        xhr && xhr.abort()
      }, config.timeout)
    }

    return promise
  }

  ['get', 'delete', 'head'].forEach(function(name) {
    Q.xhr[name] = function(url, config) {
      return Q.xhr(extend(config || {}, {
        method: name,
        url: url
      }))
    }
  });

  ['post', 'put', 'patch'].forEach(function(name) {
    Q.xhr[name] = function(url, data, config) {
      return Q.xhr(extend(config || {}, {
        method: name,
        url: url,
        data: data
      }))
    }
  })

  return Q
})<commit_msg>Add try/catch to JSON parsing code<commit_after>// Currently requires polyfills for
// Array#forEach
// Object.keys
// String#trim

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['q'], function(Q) {
      return factory(XMLHttpRequest, Q)
    })
  } else if (typeof exports === 'object' && typeof module === 'object') {
    // CommonJS, mainly for testing
    module.exports = factory
  } else {
    if (typeof Q !== 'undefined') {
      factory(XMLHttpRequest, Q)
    }
  }
})(function(XHR, Q) {
  // shallow extend with varargs
  function extend(dst) {
    Array.prototype.forEach.call(arguments, function(obj) {
      if (obj && obj !== dst) {
        Object.keys(obj).forEach(function(key) {
          dst[key] = obj[key]
        })
      }
    })

    return dst
  }

  function lowercase(str) {
    return (str || '').toLowerCase()
  }

  function parseHeaders(headers) {
    var parsed = {}, key, val, i

    if (!headers) return parsed

    headers.split('\n').forEach(function(line) {
      i = line.indexOf(':')
      key = lowercase(line.substr(0, i).trim())
      val = line.substr(i + 1).trim()

      if (key) {
        if (parsed[key]) {
          parsed[key] += ', ' + val
        } else {
          parsed[key] = val
        }
      }
    })

    return parsed
  }

  function headersGetter(headers) {
    var headersObj = typeof headers === 'object' ? headers : undefined;

    return function(name) {
      if (!headersObj) headersObj = parseHeaders(headers)

      if (name) {
        return headersObj[lowercase(name)]
      }

      return headersObj
    }
  }

  function transformData(data, headers, fns) {
    if (typeof fns === 'function') {
      return fns(data, headers)
    }

    fns.forEach(function(fn) {
      data = fn(data, headers)
    })

    return data
  }

  function isSuccess(status) {
    return 200 <= status && status < 300
  }

  function forEach(obj, iterator, context) {
    var keys = Object.keys(obj)
    keys.forEach(function(key) {
      iterator.call(context, obj[key], key)
    })
    return keys
  }

  function forEachSorted(obj, iterator, context) {
    var keys = Object.keys(obj).sort()
    keys.forEach(function(key) {
      iterator.call(context, obj[key], key)
    })
    return keys
  }

  function buildUrl(url, params) {
    if (!params) return url
    var parts = []
    forEachSorted(params, function(value, key) {
      if (value == null) return
      if (!Array.isArray(value)) value = [value]

      value.forEach(function(v) {
        if (typeof v === 'object') {
          v = JSON.stringify(v)
        }
        parts.push(encodeURIComponent(key) + '=' +
                   encodeURIComponent(v))
      })
    })
    return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&')
  }

  Q.xhr = function (requestConfig) {
    var defaults = Q.xhr.defaults,
    config = {
      transformRequest: defaults.transformRequest,
      transformResponse: defaults.transformResponse
    },
    mergeHeaders = function(config) {
      var defHeaders = defaults.headers,
          reqHeaders = extend({}, config.headers),
          defHeaderName, lowercaseDefHeaderName, reqHeaderName,

      execHeaders = function(headers) {
        forEach(headers, function(headerFn, header) {
          if (typeof headerFn === 'function') {
            var headerContent = headerFn()
            if (headerContent != null) {
              headers[header] = headerContent
            } else {
              delete headers[header]
            }
          }
        })
      }

      defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);

      // execute if header value is function
      execHeaders(defHeaders);
      execHeaders(reqHeaders);

      // using for-in instead of forEach to avoid unecessary iteration after header has been found
      defaultHeadersIteration:
      for (defHeaderName in defHeaders) {
        lowercaseDefHeaderName = lowercase(defHeaderName);

        for (reqHeaderName in reqHeaders) {
          if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
            continue defaultHeadersIteration;
          }
        }

        reqHeaders[defHeaderName] = defHeaders[defHeaderName];
      }

      return reqHeaders;
    },
    headers = mergeHeaders(requestConfig)

    extend(config, requestConfig)
    config.headers = headers
    config.method = (config.method || 'GET').toUpperCase()

    var serverRequest = function(config) {
      headers = config.headers
      var reqData = transformData(config.data, headersGetter(headers), config.transformRequest)

      // strip content-type if data is undefined TODO does it really matter?
      if (config.data == null) {
        forEach(headers, function(value, header) {
          if (lowercase(header) === 'content-type') {
              delete headers[header]
          }
        })
      }

      if (config.withCredentials == null && defaults.withCredentials != null) {
        config.withCredentials = defaults.withCredentials
      }

      // send request
      return sendReq(config, reqData, headers).then(transformResponse, transformResponse)
    },

    transformResponse = function(response) {
      response.data = transformData(response.data, response.headers, config.transformResponse)
      return isSuccess(response.status) ? response : Q.reject(response)
    },

    promise = Q.when(config)

    // build a promise chain with request interceptors first, then the request, and response interceptors
    Q.xhr.interceptors.filter(function(interceptor) {
        return !!interceptor.request || !!interceptor.requestError
      }).map(function(interceptor) {
        return { success: interceptor.request, failure: interceptor.requestError }
      })
    .concat({ success: serverRequest })
    .concat(Q.xhr.interceptors.filter(function(interceptor) {
        return !!interceptor.response || !!interceptor.responseError
      }).map(function(interceptor) {
        return { success: interceptor.response, failure: interceptor.responseError }
      })
    ).forEach(function(then) {
      promise = promise.then(then.success, then.failure)
    })

    return promise
  }

  var contentTypeJson = { 'Content-Type': 'application/json;charset=utf-8' }

  Q.xhr.defaults = {
    transformResponse: [function(data, headers) {
      if (typeof data === 'string' && (headers('content-type') || '').indexOf('json') >= 0) {
        try {
          data = JSON.parse(data);
        } catch (e) {
          return data;
        }
      }
      return data
    }],

    transformRequest: [function(data) {
      return !!data && typeof data === 'object' && data.toString() !== '[object File]' ?
        JSON.stringify(data) : data
    }],

    headers: {
      common: {
        'Accept': 'application/json, text/plain, */*'
      },
      post:   contentTypeJson,
      put:    contentTypeJson,
      patch:  contentTypeJson
    },
  }

  Q.xhr.interceptors = []
  Q.xhr.pendingRequests = []

  function sendReq(config, reqData, reqHeaders) {
    var deferred = Q.defer(),
        promise = deferred.promise,
        url = buildUrl(config.url, config.params),
        xhr = new XHR(),
        aborted = -1,
        status,
        timeoutId

    Q.xhr.pendingRequests.push(config)

    xhr.open(config.method, url, true)
    forEach(config.headers, function(value, key) {
      if (value) {
        xhr.setRequestHeader(key, value)
      }
    })

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var response, responseHeaders
        if (status !== aborted) {
          responseHeaders = xhr.getAllResponseHeaders()
          // responseText is the old-school way of retrieving response (supported by IE8 & 9)
          // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
          response = xhr.responseType ? xhr.response : xhr.responseText
        }

        // cancel timeout and subsequent timeout promise resolution
        timeoutId && clearTimeout(timeoutId)
        status = status || xhr.status
        xhr = null

        // normalize status, including accounting for IE bug (http://bugs.jquery.com/ticket/1450)
        status = Math.max(status == 1223 ? 204 : status, 0)

        var idx = Q.xhr.pendingRequests.indexOf(config)
        if (idx !== -1) Q.xhr.pendingRequests.splice(idx, 1)

        ;(isSuccess(status) ? deferred.resolve : deferred.reject)({
          data: response,
          status: status,
          headers: headersGetter(responseHeaders),
          config: config
        })
      }
    }

    xhr.onprogress = function (progress) {
      deferred.notify(progress)
    }

    if (config.withCredentials) {
      xhr.withCredentials = true
    }

    if (config.responseType) {
      xhr.responseType = config.responseType;
    }

    xhr.send(reqData || null)

    if (config.timeout > 0) {
      timeoutId = setTimeout(function() {
        status = aborted;
        xhr && xhr.abort()
      }, config.timeout)
    }

    return promise
  }

  ['get', 'delete', 'head'].forEach(function(name) {
    Q.xhr[name] = function(url, config) {
      return Q.xhr(extend(config || {}, {
        method: name,
        url: url
      }))
    }
  });

  ['post', 'put', 'patch'].forEach(function(name) {
    Q.xhr[name] = function(url, data, config) {
      return Q.xhr(extend(config || {}, {
        method: name,
        url: url,
        data: data
      }))
    }
  })

  return Q
})
<|endoftext|>


<commit_before>angular.module('NgModelOptionsOnInvalid', []).directive('ngModelOptionsOnInvalid', function () {
  return {
    require: ['ngModel', '^form'],
    controller: function ($element, $scope, $attrs) {
      var
        ngModelOptionsController = $element.controller('ngModel'),
        formController = $element.controller('form');

      var unwatch = $scope.$watch(formController.$name + '.' + $attrs.name + '.$valid', function (newVal) {
        if (newVal === false) {

        // TODO: get the options from the attr

        // var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
        // $options = copy($scope.$eval($attrs.ngModelOptions))
        // $options.updateOn.replace(DEFAULT_REGEXP, function() {
        //   $options.updateOnDefault = true;
        //   return ' ';
        // })
        // ngModelOptionsController.$$setOptions($options);

          ngModelOptionsController.$$setOptions({
            updateOn: 'default'
          });

          unwatch();
        }
      });
    }
  };
});
<commit_msg>Fix options object<commit_after>angular.module('NgModelOptionsOnInvalid', []).directive('ngModelOptionsOnInvalid', function () {
  return {
    require: ['ngModel', '^form'],
    controller: function ($element, $scope, $attrs) {
      var
        ngModelOptionsController = $element.controller('ngModel'),
        formController = $element.controller('form');

      var unwatch = $scope.$watch(formController.$name + '.' + $attrs.name + '.$valid', function (newVal) {
        if (newVal === false) {

        // TODO: get the options from the attr

        // var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
        // $options = copy($scope.$eval($attrs.ngModelOptions))
        // $options.updateOn.replace(DEFAULT_REGEXP, function() {
        //   $options.updateOnDefault = true;
        //   return ' ';
        // })
        // ngModelOptionsController.$$setOptions($options);

          ngModelOptionsController.$$setOptions({
            updateOnDefault: true
          });

          unwatch();
        }
      });
    }
  };
});
<|endoftext|>


<commit_before>/**
 * This plugin overrides jQuery's height() and width() functions and
 * adds more handy stuff for cross-browser compatibility.
 */

/**
 * Returns the css height value for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example $("#testdiv").height()
 * @result "200px"
 *
 * @example $(document).height();
 * @result 800
 *
 * @example $(window).height();
 * @result 400
 *
 * @name height
 * @type Object
 * @cat Dimensions
 */
jQuery.fn.height = function() {
	if ( this.get(0) == window )
		return self.innerHeight ||
			jQuery.boxModel && document.documentElement.clientHeight ||
			document.body.clientHeight;

	if ( this.get(0) == document )
		return Math.max( document.body.scrollHeight, document.body.offsetHeight );

	return this.css("height");
};

/**
 * Returns the css width value for the first matched element.
 * If used on document, returns the document's width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example $("#testdiv").width()
 * @result "200px"
 *
 * @example $(document).width();
 * @result 800
 *
 * @example $(window).width();
 * @result 400
 *
 * @name width
 * @type Object
 * @cat Dimensions
 */
jQuery.fn.width = function() {
	if ( this.get(0) == window )
		return self.innerWidth ||
			jQuery.boxModel && document.documentElement.clientWidth ||
			document.body.clientWidth;

	if ( this.get(0) == document )
		return Math.max( document.body.scrollWidth, document.body.offsetWidth );

	return this.css("width");
};

/**
 * Returns the inner height value (without border) for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example $("#testdiv").innerHeight()
 * @result 800
 *
 * @name innerHeight
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.innerHeight = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.height() :
		this.get(0).offsetHeight - parseInt(this.css("borderTop") || 0) - parseInt(this.css("borderBottom") || 0);
};

/**
 * Returns the inner width value (without border) for the first matched element.
 * If used on document, returns the document's Width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example $("#testdiv").innerWidth()
 * @result 1000
 *
 * @name innerWidth
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.innerWidth = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.width() :
		this.get(0).offsetWidth - parseInt(this.css("borderLeft") || 0) - parseInt(this.css("borderRight") || 0);
};

/**
 * Returns the outer height value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerHeight()
 * @result 1000
 *
 * @name outerHeight
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.outerHeight = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.height() :
		this.get(0).offsetHeight;
};

/**
 * Returns the outer width value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerWidth()
 * @result 1000
 *
 * @name outerWidth
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.outerWidth = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.width() :
		this.get(0).offsetWidth;
};

/**
 * Returns how many pixels the user has scrolled to the right (scrollLeft).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollLeft()
 * @result 100
 *
 * @name scrollLeft
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.scrollLeft = function() {
	if ( this.get(0) == window || this.get(0) == document )
		return self.pageXOffset ||
			jQuery.boxModel && document.documentElement.scrollLeft ||
			document.body.scrollLeft;

	return this.get(0).scrollLeft;
};

/**
 * Returns how many pixels the user has scrolled to the bottom (scrollTop).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollTop()
 * @result 100
 *
 * @name scrollTop
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.scrollTop = function() {
	if ( this.get(0) == window || this.get(0) == document )
		return self.pageYOffset ||
			jQuery.boxModel && document.documentElement.scrollTop ||
			document.body.scrollTop;

	return this.get(0).scrollTop;
};

/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @param String refElement This is an expression. The offset returned will be relative to the first matched element.
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @param jQuery refElement The offset returned will be relative to the first matched element.
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @param HTMLElement refElement The offset returned will be relative to this element.
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(refElem) {
	if (!this[0]) throw 'jQuery.fn.offset requires an element.';

	refElem = (refElem) ? jQuery(refElem)[0] : null;
	var x = 0, y = 0, elm = this[0], parent = this[0], pos = null, borders = [0,0], isElm = true, sl = 0, st = 0;
	do {
		if (parent.tagName == 'BODY' || parent.tagName == 'HTML') {
			// Safari and IE don't add margin for static and relative
			if ((jQuery.browser.safari || jQuery.browser.msie) && pos != 'absolute') {
				x += parseInt(jQuery.css(parent, 'marginLeft')) || 0;
				y += parseInt(jQuery.css(parent, 'marginTop'))  || 0;
			}
			break;
		}

		pos    = jQuery.css(parent, 'position');
		border = [parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0,
							parseInt(jQuery.css(parent, 'borderTopWidth'))  || 0];
		sl = parent.scrollLeft;
		st = parent.scrollTop;

		x += (parent.offsetLeft || 0) + border[0] - sl;
		y += (parent.offsetTop  || 0) + border[1] - st;

		// Safari and Opera include the border already for parents with position = absolute|relative
		if ((jQuery.browser.safari || jQuery.browser.opera) && !isElm && (pos == 'absolute' || pos == 'relative')) {
			x -= border[0];
			y -= border[1];
		}

		parent = parent.offsetParent;
		isElm  = false;
	} while(parent);

	if (refElem) {
		var offset = jQuery(refElem).offset();
		x  = x  - offset.left;
		y  = y  - offset.top;
		sl = sl - offset.scrollLeft;
		st = st - offset.scrollTop;
	}

	return {
		top:  y,
		left: x,
		width:  elm.offsetWidth,
		height: elm.offsetHeight,
		borderTop:  parseInt(jQuery.css(elm, 'borderTopWidth'))  || 0,
		borderLeft: parseInt(jQuery.css(elm, 'borderLeftWidth')) || 0,
		marginTop:  parseInt(jQuery.css(elm, 'marginTopWidth'))  || 0,
		marginLeft: parseInt(jQuery.css(elm, 'marginLeftWidth')) || 0,
		scrollTop:  st,
		scrollLeft: sl,
		pageYOffset: window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop  || 0,
		pageXOffset: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0
	};
};<commit_msg>* Fixed a bug in jQuery.fn.offset relating to the calculation of scroll offsets. * Fixed jQuery.fn.height and jQuery.fn.width to properly pass on a value for setting the height and width of an element if passed in.<commit_after>/**
 * This plugin overrides jQuery's height() and width() functions and
 * adds more handy stuff for cross-browser compatibility.
 */

/**
 * Returns the css height value for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example $("#testdiv").height()
 * @result "200px"
 *
 * @example $(document).height();
 * @result 800
 *
 * @example $(window).height();
 * @result 400
 *
 * @name height
 * @type Object
 * @cat Dimensions
 */
jQuery.fn.height = function() {
	if ( this.get(0) == window )
		return self.innerHeight ||
			jQuery.boxModel && document.documentElement.clientHeight ||
			document.body.clientHeight;

	if ( this.get(0) == document )
		return Math.max( document.body.scrollHeight, document.body.offsetHeight );

	return this.css("height", arguments[0]);
};

/**
 * Returns the css width value for the first matched element.
 * If used on document, returns the document's width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example $("#testdiv").width()
 * @result "200px"
 *
 * @example $(document).width();
 * @result 800
 *
 * @example $(window).width();
 * @result 400
 *
 * @name width
 * @type Object
 * @cat Dimensions
 */
jQuery.fn.width = function() {
	if ( this.get(0) == window )
		return self.innerWidth ||
			jQuery.boxModel && document.documentElement.clientWidth ||
			document.body.clientWidth;

	if ( this.get(0) == document )
		return Math.max( document.body.scrollWidth, document.body.offsetWidth );

	return this.css("width", arguments[0]);
};

/**
 * Returns the inner height value (without border) for the first matched element.
 * If used on document, returns the document's height (innerHeight)
 * If used on window, returns the viewport's (window) height
 *
 * @example $("#testdiv").innerHeight()
 * @result 800
 *
 * @name innerHeight
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.innerHeight = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.height() :
		this.get(0).offsetHeight - parseInt(this.css("borderTop") || 0) - parseInt(this.css("borderBottom") || 0);
};

/**
 * Returns the inner width value (without border) for the first matched element.
 * If used on document, returns the document's Width (innerWidth)
 * If used on window, returns the viewport's (window) width
 *
 * @example $("#testdiv").innerWidth()
 * @result 1000
 *
 * @name innerWidth
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.innerWidth = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.width() :
		this.get(0).offsetWidth - parseInt(this.css("borderLeft") || 0) - parseInt(this.css("borderRight") || 0);
};

/**
 * Returns the outer height value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerHeight()
 * @result 1000
 *
 * @name outerHeight
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.outerHeight = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.height() :
		this.get(0).offsetHeight;
};

/**
 * Returns the outer width value (including border) for the first matched element.
 * Cannot be used on document or window.
 *
 * @example $("#testdiv").outerWidth()
 * @result 1000
 *
 * @name outerWidth
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.outerWidth = function() {
	return this.get(0) == window || this.get(0) == document ?
		this.width() :
		this.get(0).offsetWidth;
};

/**
 * Returns how many pixels the user has scrolled to the right (scrollLeft).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollLeft()
 * @result 100
 *
 * @name scrollLeft
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.scrollLeft = function() {
	if ( this.get(0) == window || this.get(0) == document )
		return self.pageXOffset ||
			jQuery.boxModel && document.documentElement.scrollLeft ||
			document.body.scrollLeft;

	return this.get(0).scrollLeft;
};

/**
 * Returns how many pixels the user has scrolled to the bottom (scrollTop).
 * Works on containers with overflow: auto and window/document.
 *
 * @example $("#testdiv").scrollTop()
 * @result 100
 *
 * @name scrollTop
 * @type Number
 * @cat Dimensions
 */
jQuery.fn.scrollTop = function() {
	if ( this.get(0) == window || this.get(0) == document )
		return self.pageYOffset ||
			jQuery.boxModel && document.documentElement.scrollTop ||
			document.body.scrollTop;

	return this.get(0).scrollTop;
};

/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @param String refElement This is an expression. The offset returned will be relative to the first matched element.
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @param jQuery refElement The offset returned will be relative to the first matched element.
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
/**
 * This returns an object with top, left, width, height, borderLeft,
 * borderTop, marginLeft, marginTop, scrollLeft, scrollTop,
 * pageXOffset, pageYOffset.
 *
 * The top and left values include the scroll offsets but the
 * scrollLeft and scrollTop properties of the returned object
 * are the combined scroll offets of the parent elements
 * (not including the window scroll offsets). This is not the
 * same as the element's scrollTop and scrollLeft.
 *
 * For accurate readings make sure to use pixel values.
 *
 * @name offset
 * @type Object
 * @param HTMLElement refElement The offset returned will be relative to this element.
 * @cat Dimensions
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.offset = function(refElem) {
	if (!this[0]) throw 'jQuery.fn.offset requires an element.';

	refElem = (refElem) ? jQuery(refElem)[0] : null;
	var x = 0, y = 0, elem = this[0], parent = this[0], sl = 0, st = 0;
	do {
		if (parent.tagName == 'BODY' || parent.tagName == 'HTML') {
			// Safari and IE don't add margin for static and relative
			if ((jQuery.browser.safari || jQuery.browser.msie) && jQuery.css(parent, 'position') != 'absolute') {
				x += parseInt(jQuery.css(parent, 'marginLeft')) || 0;
				y += parseInt(jQuery.css(parent, 'marginTop'))  || 0;
			}
			break;
		}

		x += parent.offsetLeft || 0;
		y += parent.offsetTop  || 0;

		// Mozilla and IE do not add the border
		if (jQuery.browser.mozilla || jQuery.browser.msie) {
			x += parseInt(jQuery.css(parent, 'borderLeftWidth')) || 0;
			y += parseInt(jQuery.css(parent, 'borderTopWidth'))  || 0;
		}

		// Need to get scroll offsets in-between offsetParents
		var op = parent.offsetParent;
		do {
			sl += parent.scrollLeft || 0;
			st += parent.scrollTop  || 0;
			parent = parent.parentNode;
		} while (parent != op);
	} while (parent);

	if (refElem) { // Get the relative offset
		var offset = jQuery(refElem).offset();
		x  = x  - offset.left;
		y  = y  - offset.top;
		sl = sl - offset.scrollLeft;
		st = st - offset.scrollTop;
	}

	// Safari and Opera do not add the border for the element
	if (jQuery.browser.safari || jQuery.browser.opera) {
		x += parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0;
		y += parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0;
	}

	return {
		top:  y - st,
		left: x - sl,
		width:  elem.offsetWidth,
		height: elem.offsetHeight,
		borderTop:  parseInt(jQuery.css(elem, 'borderTopWidth'))  || 0,
		borderLeft: parseInt(jQuery.css(elem, 'borderLeftWidth')) || 0,
		marginTop:  parseInt(jQuery.css(elem, 'marginTopWidth'))  || 0,
		marginLeft: parseInt(jQuery.css(elem, 'marginLeftWidth')) || 0,
		scrollTop:  st,
		scrollLeft: sl,
		pageYOffset: window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop  || 0,
		pageXOffset: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0
	};
};<|endoftext|>


<commit_before>(function(angular) {
    'use strict';

    /**
     * @ngdoc directive
     * @name esriApp.directive:esriLegend
     * @description
     * # esriLegend
     */
    angular.module('esri.map')
      .directive('esriLegend', function ($document, $q) {
        return {
          //run last
          priority: -10,
          scope:{},
          replace: true,
          // require the esriMap controller
          // you can access these controllers in the link function
          require: ['^esriMap'],

          // now we can link our directive to the scope, but we can also add it to the map..
          link: function(scope, element, attrs, controllers){
            // controllers is now an array of the controllers from the 'require' option
            var mapController = controllers[0];
            var targetId = attrs.targetId || attrs.id;
            var legendDeferred = $q.defer();

            require(['esri/dijit/Legend', 'dijit/registry'], function (Legend, registry) {
              mapController.getMap().then(function(map) {
                var opts = {
                    map: map
                };
                var layerInfos = mapController.getLayerInfos();
                if (layerInfos) {
                  opts.layerInfos = layerInfos;
                }
                // NOTE: need to come up w/ a way to that is not based on id
                // or handle destroy at end of this view's lifecyle
                var legend = registry.byId(targetId);
                if (legend) {
                  legend.destroyRecursive();
                }
                legend = new Legend(opts, targetId);
                legend.startup();
                scope.$watchCollection(function () { return mapController.getLayerInfos(); }, function (newValue/*, oldValue, scope*/) {
                    legend.refresh(newValue);
                });
                legendDeferred.resolve(legend);
              });
            });
          }
        };
      });

})(angular);
<commit_msg>general cleanup on esriLegend<commit_after>(function(angular) {
  'use strict';

  /**
   * @ngdoc directive
   * @name esriApp.directive:esriLegend
   * @description
   * # esriLegend
   */
  angular.module('esri.map')
    .directive('esriLegend', function($q, esriLoader) {
      return {
        //run last
        priority: -10,
        restrict: 'EA',
        // require the esriMap controller
        // you can access these controllers in the link function
        require: ['?esriLegend', '^esriMap'],
        replace: true,

        scope: {},
        controllerAs: 'legendCtrl',
        bindToController: true,

        controller: function() {},

        // now we can link our directive to the scope, but we can also add it to the map
        link: function(scope, element, attrs, controllers) {

          // controllers is now an array of the controllers from the 'require' option
          // var legendController = controllers[0];
          var mapController = controllers[1];
          var targetId = attrs.targetId || attrs.id;
          var legendDeferred = $q.defer();

          esriLoader.require(['esri/dijit/Legend'], function(Legend) {
            mapController.getMap().then(function(map) {
              var legend;

              var options = {
                map: map
              };

              var layerInfos = mapController.getLayerInfos();
              if (layerInfos) {
                options.layerInfos = layerInfos;
              }

              legend = new Legend(options, targetId);
              legend.startup();

              scope.$watchCollection(function() {
                return mapController.getLayerInfos();
              }, function(newValue /*, oldValue, scope*/ ) {
                legend.refresh(newValue);
              });

              legendDeferred.resolve(legend);

              scope.$on('$destroy', function() {
                legend.destroy();
              });
            });
          });
        }
      };
    });

})(angular);
<|endoftext|>


<commit_before>import * as _  from 'underscore';

import {Dryad} from 'dryadic';
import Group from './Group';
import {
  synthNew,
  AddActions
} from '../server/osc/msg';
import {
  loopedEventListIterator,
  eventListIterator
} from './utils/iterators';

/**
 * Takes a list of synth event objects with relative times and schedules them.
 *
 * ## properties
 *
 * __events:__ Array
 *
 * The event values should be simple JavaScript objects:
 *
 *     {
 *       defName: 'synthDefName',
 *       args: {
 *         out: 0,
 *         freq: 440
 *       },
 *       time: 0.3
 *     }
 *
 *  Where time is seconds relative to the epoch. The epoch is the start time of
 *  the dryadic tree, unless a parent Dryad has set a new epoch into context.
 *
 *    epoch: number|Date|undefined
 *      Optional epoch that the event times in the list are relative to.
 *      Can also be updated by the updateStream
 *      default: context.epoch or now
 *
 * __updateStream:__ Bacon stream to push updated event lists of the form:
 *
 *      {
 *        events: [{time: msgs: []}...],
 *        epoch: 123456789
 *      }

 *     .events Array
 *     .epoch  number|Date
 *
 * Deprecated: will be replaced with live updating and setting of
 * Any value in a dryadic document from the player or remote client.
 *
 * Pushing a new event list cancels previous events and schedules new events.
 *
 * Note that by default the epoch will be unchanged: relative times
 * are still relative to when the Dryad tree started playing or when any parent
 * Dryad set an epoch in context. This means you update the currently playing score
 * but it doesn't restart from the beginning, it keeps playing.
 *
 * Optionally you may push an .epoch with the updateStream. This can be a date or timestamp
 * slightly in the future. If you pass "now" then any events at `0.0` will be too late to play.
 *
 * __defaultParams:__ a fixed object into which the event value is merged.
 *
 * __loopTime:__ Play the events continuously in a loop.
 */
export default class SynthEventList extends Dryad {

  /**
   * @param  {DryadPlayer} player
   * @return {Object}      Command object
   */
  add(player) {
    let commands = {
      scserver: {
        schedLoop: (context) => {
          // temporary: we need to know the play time of the whole document
          const epoch = context.epoch || (_.now() + 200);
          if (epoch !== context.epoch) {
            context = player.updateContext(context, {epoch});
          }

          return this._makeSchedLoop(this.properties.events || [], this.properties.loopTime, epoch, context);
        }
      }
    };

    if (this.properties.updateStream) {
      commands.run = (context) => {
        let subscription = this.properties.updateStream.subscribe((streamEvent) => {
          let ee = streamEvent.value();
          const loopTime = _.isUndefined(ee.loopTime) ? this.properties.loopTime : ee.loopTime;

          let epoch = ee.epoch || context.epoch || (_.now() + 200);
          if (epoch !== context.epoch) {
            context = player.updateContext(context, {
              epoch
            });
          }

          player.callCommand(context.id, {
            scserver: {
              // need to set epoch as well because OSCSched uses that for relative times
              schedLoop: (ctx) => this._makeSchedLoop(ee.events || [], loopTime, epoch, ctx)
            }
          });
        });

        player.updateContext(context, {subscription});
      };
    }

    return commands;
  }

  _makeSchedLoop(events, loopTime, epoch, context) {
    const synthEvents = this._makeMsgs(events, context);
    return loopTime ? loopedEventListIterator(synthEvents, loopTime) : eventListIterator(synthEvents);
  }

  _makeMsgs(events, context) {
    const defaultParams = this.properties.defaultParams || {};
    return events.map((event) => {
      // TODO: do this a jit time in the schedLoop
      const defName = event.defName || defaultParams.defName;
      const args = _.assign({out: context.out || 0}, defaultParams.args, event.args);
      const msg = synthNew(defName, -1, AddActions.TAIL, context.group, args);
      return {
        time: event.time,
        msgs: [msg]
      };
    });
  }

  /**
   * @return {Object}  command object
   */
  remove() {
    return {
      run: (context) => {
        if (context.subscription) {
          if (_.isFunction(context.subscription)) {
            // baconjs style
            context.subscription();
          } else {
            // Rx style
            context.subscription.dispose();
          }
        }
      },
      scserver: {
        sched: (context) => {
          // unschedAll
          return this._makeSchedLoop([], context.epoch, context);
        }
      }
    };
  }

  /**
   * @return {Dryad}  Wraps itself in a Group so all child Synth events will be removed on removal of the Group.
   */
  subgraph() {
    return new Group({}, [this]);
  }
}
<commit_msg>remove unused epoch arg<commit_after>import * as _  from 'underscore';

import {Dryad} from 'dryadic';
import Group from './Group';
import {
  synthNew,
  AddActions
} from '../server/osc/msg';
import {
  loopedEventListIterator,
  eventListIterator
} from './utils/iterators';

/**
 * Takes a list of synth event objects with relative times and schedules them.
 *
 * ## properties
 *
 * __events:__ Array
 *
 * The event values should be simple JavaScript objects:
 *
 *     {
 *       defName: 'synthDefName',
 *       args: {
 *         out: 0,
 *         freq: 440
 *       },
 *       time: 0.3
 *     }
 *
 *  Where time is seconds relative to the epoch. The epoch is the start time of
 *  the dryadic tree, unless a parent Dryad has set a new epoch into context.
 *
 *    epoch: number|Date|undefined
 *      Optional epoch that the event times in the list are relative to.
 *      Can also be updated by the updateStream
 *      default: context.epoch or now
 *
 * __updateStream:__ Bacon stream to push updated event lists of the form:
 *
 *      {
 *        events: [{time: msgs: []}...],
 *        epoch: 123456789
 *      }

 *     .events Array
 *     .epoch  number|Date
 *
 * Deprecated: will be replaced with live updating and setting of
 * Any value in a dryadic document from the player or remote client.
 *
 * Pushing a new event list cancels previous events and schedules new events.
 *
 * Note that by default the epoch will be unchanged: relative times
 * are still relative to when the Dryad tree started playing or when any parent
 * Dryad set an epoch in context. This means you update the currently playing score
 * but it doesn't restart from the beginning, it keeps playing.
 *
 * Optionally you may push an .epoch with the updateStream. This can be a date or timestamp
 * slightly in the future. If you pass "now" then any events at `0.0` will be too late to play.
 *
 * __defaultParams:__ a fixed object into which the event value is merged.
 *
 * __loopTime:__ Play the events continuously in a loop.
 */
export default class SynthEventList extends Dryad {

  /**
   * @param  {DryadPlayer} player
   * @return {Object}      Command object
   */
  add(player) {
    let commands = {
      scserver: {
        schedLoop: (context) => {
          // temporary: we need to know the play time of the whole document
          const epoch = context.epoch || (_.now() + 200);
          if (epoch !== context.epoch) {
            context = player.updateContext(context, {epoch});
          }

          return this._makeSchedLoop(this.properties.events || [], this.properties.loopTime, epoch, context);
        }
      }
    };

    if (this.properties.updateStream) {
      commands.run = (context) => {
        let subscription = this.properties.updateStream.subscribe((streamEvent) => {
          let ee = streamEvent.value();
          const loopTime = _.isUndefined(ee.loopTime) ? this.properties.loopTime : ee.loopTime;
          let epoch = ee.epoch || context.epoch || (_.now() + 200);
          if (epoch !== context.epoch) {
            context = player.updateContext(context, {
              epoch
            });
          }

          player.callCommand(context.id, {
            scserver: {
              // need to set epoch as well because OSCSched uses that for relative times
              schedLoop: (ctx) => this._makeSchedLoop(ee.events || [], loopTime, ctx)
            }
          });
        });

        player.updateContext(context, {subscription});
      };
    }

    return commands;
  }

  _makeSchedLoop(events, loopTime, context) {
    const synthEvents = this._makeMsgs(events, context);
    return loopTime ? loopedEventListIterator(synthEvents, loopTime) : eventListIterator(synthEvents);
  }

  _makeMsgs(events, context) {
    const defaultParams = this.properties.defaultParams || {};
    return events.map((event) => {
      // TODO: do this a jit time in the schedLoop
      const defName = event.defName || defaultParams.defName;
      const args = _.assign({out: context.out || 0}, defaultParams.args, event.args);
      const msg = synthNew(defName, -1, AddActions.TAIL, context.group, args);
      return {
        time: event.time,
        msgs: [msg]
      };
    });
  }

  /**
   * @return {Object}  command object
   */
  remove() {
    return {
      run: (context) => {
        if (context.subscription) {
          if (_.isFunction(context.subscription)) {
            // baconjs style
            context.subscription();
          } else {
            // Rx style
            context.subscription.dispose();
          }
        }
      },
      scserver: {
        sched: (context) => {
          // unschedAll
          return this._makeSchedLoop([], context.epoch, context);
        }
      }
    };
  }

  /**
   * @return {Dryad}  Wraps itself in a Group so all child Synth events will be removed on removal of the Group.
   */
  subgraph() {
    return new Group({}, [this]);
  }
}
<|endoftext|>


<commit_before>var stop_at = new function()
{

  /**
  * two layers are needed.
  * stop_at script must be enabled allways to be able to reasign breakpoints.
  */

  var stop_at_settings =
  {
    script: 1,
    exception: 0,
    error: 0,
    abort: 0,
  }

  // replace with settings['js-source'].get(key)
  var stop_at_user_settings =
  {
    script: 0,
    exception: 0,
    error: 0,
    abort: 0,
  }

  var stopAt = {}; // there can be only one stop at at the time

  var runtime_id = '';

  var callstack = [];

  var __controls_enabled = false;

  var __stopAtId = 1;

  var getStopAtId = function()
  {
    return __stopAtId++;
  }

  this.getStopAts = function()
  {
    return stop_at_user_settings; // should be  copied
  }

  var onSettingChange = function(msg)
  {
    if(msg.id == 'js_source' )
    {
      var key = msg.key, value = settings['js_source'].get(key);
      if( key == 'script' )
      {

      }
      else
      {
        stop_at_settings[key] = value;
        services['ecmascript-debugger'].setConfiguration(key, value ? 'yes' : 'no');
      }
    }
  }

  this.setUserStopAt = function(key, value)
  {
    //stop_at_user_settings[key] = value; // true or false;
    opera.postError('clean up. this should no longer be called. stop_at.setUserStopAt');

  }

  this.getRuntimeId = function()
  {
    return runtime_id;
  }

  this.getControlsEnabled = function()
  {
    return __controls_enabled;
  }

  this.getFrames = function()
  {
    return callstack; // should be copied
  }

  this.getFrame = function(id)
  {
    return callstack[id];
  }

  var parseBacktrace = function(xml, runtime_id)
  {
    var _frames = xml.getElementsByTagName('frame'), frame = null, i = 0;
    var fn_name = '', line = '', script_id = '', argument_id = '', scope_id = '';
    var _frames_length = _frames.length;

    var is_all_frames = _frames_length <= ini.max_frames;
    callstack = [];
    for( ; frame  = _frames[i]; i++ )
    {
      if( is_all_frames && i == _frames_length - 1 )
      {
        callstack[i] =
        {
          fn_name : 'global scope',
          line : '',
          script_id : '',
          argument_id : frame.getNodeData('argument-object'),
          scope_id : frame.getNodeData('variable-object'),
          this_id : frame.getNodeData('this-object'),
          id: i
        }
      }
      else
      {
        callstack[i] =
        {
          fn_name : frame.getNodeData('function-name'),
          line : frame.getNodeData('line-number'),
          script_id : frame.getNodeData('script-id'),
          argument_id : frame.getNodeData('argument-object'),
          scope_id : frame.getNodeData('variable-object'),
          this_id : frame.getNodeData('this-object'),
          id: i
        }
      }
      // fake a click event on the top frame in the stack
      if( i == 0 )
      {
        action_handler.post('show-frame', {'target': { 'ref-id': 0 } });
      }
    }
    views.callstack.update();
  }

  this.setInitialSettings = function()
  {
    var config_arr = [], prop = '';
    for ( prop in stop_at_settings )
    {
      config_arr[config_arr.length] = prop;
      config_arr[config_arr.length] = stop_at_settings[prop] ? 'yes' : 'no';
    }
    services['ecmascript-debugger'].setConfiguration.apply(services['ecmascript-debugger'], config_arr);
  }

  this.__continue = function (mode) //
  {
    __controls_enabled = false;

    runtimes.setObserve(stopAt['runtime-id'], mode != 'run');

    services['ecmascript-debugger'].__continue(stopAt, mode);
    toolbars.js_source.disableButtons('continue');
    messages.post('host-state', {state: 'ready'});
  }

  this.handle = function(stop_at_event)
  {
    stopAt = {};
    var id = getStopAtId();
    var children = stop_at_event.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      if(child.firstChild)
      {
        stopAt[child.nodeName] = child.firstChild.nodeValue;
      }
      else
      {
        opera.postError( "empty element in <thread-stopped-at> event");
        stopAt[child.nodeName] = null
      }
    }
    var line = parseInt( stopAt['line-number'] );
    if( typeof line == 'number' )
    {
      /**
      * This event is enabled by default to reassign breakpoints.
      * Here it must be checked if the user likes actually to stop or not.
      * At the moment this is a hack because the stop reason is not set for that case.
      * The check is if the stop reason is 'unknown' ( should be 'new script')
      */
      if(stopAt['stopped-reason'] == 'unknown')
      {

        runtime_id = stopAt['runtime-id'];
        if(  settings['js_source'].get('script') || runtimes.getObserve(runtime_id))
        {
          if( runtimes.getSelectedRuntimeId() != runtime_id )
          {
            runtimes.setSelectedRuntimeId(runtime_id);
          }
          // the runtime id can be different for each frame.
          var tag = tagManager.setCB(null, parseBacktrace, [stopAt['runtime-id']]);
          services['ecmascript-debugger'].backtrace(tag, stopAt);
          if( views.js_source.showLine( stopAt['script-id'], line - 10 ) )
          {
            views.js_source.showLinePointer( line, true );
          }
          __controls_enabled = true;
          toolbars.js_source.enableButtons('continue');
          messages.post('host-state', {state: 'waiting'});
        }
        else
        {
          this.__continue('run');
        }
      }
      else
      {
        runtime_id = stopAt['runtime-id'];

        // the runtime id can be different for each frame.
        var tag = tagManager.setCB(null, parseBacktrace, [stopAt['runtime-id']]);
        services['ecmascript-debugger'].backtrace(tag, stopAt);
        if( views.js_source.showLine( stopAt['script-id'], line - 10 ) )
        {
          views.js_source.showLinePointer( line, true );
        }
        __controls_enabled = true;
        toolbars.js_source.enableButtons('continue');
      }
    }
    else
    {
      throw 'not a line number: '+stopAt['line-number'];
    }
  }

  messages.addListener('setting-changed', onSettingChange);
}<commit_msg>Remove trailing comma in js code (linear_b doesn't like it)<commit_after>var stop_at = new function()
{

  /**
  * two layers are needed.
  * stop_at script must be enabled allways to be able to reasign breakpoints.
  */

  var stop_at_settings =
  {
    script: 1,
    exception: 0,
    error: 0,
    abort: 0
  }

  // replace with settings['js-source'].get(key)
  var stop_at_user_settings =
  {
    script: 0,
    exception: 0,
    error: 0,
    abort: 0
  }

  var stopAt = {}; // there can be only one stop at at the time

  var runtime_id = '';

  var callstack = [];

  var __controls_enabled = false;

  var __stopAtId = 1;

  var getStopAtId = function()
  {
    return __stopAtId++;
  }

  this.getStopAts = function()
  {
    return stop_at_user_settings; // should be  copied
  }

  var onSettingChange = function(msg)
  {
    if(msg.id == 'js_source' )
    {
      var key = msg.key, value = settings['js_source'].get(key);
      if( key == 'script' )
      {

      }
      else
      {
        stop_at_settings[key] = value;
        services['ecmascript-debugger'].setConfiguration(key, value ? 'yes' : 'no');
      }
    }
  }

  this.setUserStopAt = function(key, value)
  {
    //stop_at_user_settings[key] = value; // true or false;
    opera.postError('clean up. this should no longer be called. stop_at.setUserStopAt');

  }

  this.getRuntimeId = function()
  {
    return runtime_id;
  }

  this.getControlsEnabled = function()
  {
    return __controls_enabled;
  }

  this.getFrames = function()
  {
    return callstack; // should be copied
  }

  this.getFrame = function(id)
  {
    return callstack[id];
  }

  var parseBacktrace = function(xml, runtime_id)
  {
    var _frames = xml.getElementsByTagName('frame'), frame = null, i = 0;
    var fn_name = '', line = '', script_id = '', argument_id = '', scope_id = '';
    var _frames_length = _frames.length;

    var is_all_frames = _frames_length <= ini.max_frames;
    callstack = [];
    for( ; frame  = _frames[i]; i++ )
    {
      if( is_all_frames && i == _frames_length - 1 )
      {
        callstack[i] =
        {
          fn_name : 'global scope',
          line : '',
          script_id : '',
          argument_id : frame.getNodeData('argument-object'),
          scope_id : frame.getNodeData('variable-object'),
          this_id : frame.getNodeData('this-object'),
          id: i
        }
      }
      else
      {
        callstack[i] =
        {
          fn_name : frame.getNodeData('function-name'),
          line : frame.getNodeData('line-number'),
          script_id : frame.getNodeData('script-id'),
          argument_id : frame.getNodeData('argument-object'),
          scope_id : frame.getNodeData('variable-object'),
          this_id : frame.getNodeData('this-object'),
          id: i
        }
      }
      // fake a click event on the top frame in the stack
      if( i == 0 )
      {
        action_handler.post('show-frame', {'target': { 'ref-id': 0 } });
      }
    }
    views.callstack.update();
  }

  this.setInitialSettings = function()
  {
    var config_arr = [], prop = '';
    for ( prop in stop_at_settings )
    {
      config_arr[config_arr.length] = prop;
      config_arr[config_arr.length] = stop_at_settings[prop] ? 'yes' : 'no';
    }
    services['ecmascript-debugger'].setConfiguration.apply(services['ecmascript-debugger'], config_arr);
  }

  this.__continue = function (mode) //
  {
    __controls_enabled = false;

    runtimes.setObserve(stopAt['runtime-id'], mode != 'run');

    services['ecmascript-debugger'].__continue(stopAt, mode);
    toolbars.js_source.disableButtons('continue');
    messages.post('host-state', {state: 'ready'});
  }

  this.handle = function(stop_at_event)
  {
    stopAt = {};
    var id = getStopAtId();
    var children = stop_at_event.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      if(child.firstChild)
      {
        stopAt[child.nodeName] = child.firstChild.nodeValue;
      }
      else
      {
        opera.postError( "empty element in <thread-stopped-at> event");
        stopAt[child.nodeName] = null
      }
    }
    var line = parseInt( stopAt['line-number'] );
    if( typeof line == 'number' )
    {
      /**
      * This event is enabled by default to reassign breakpoints.
      * Here it must be checked if the user likes actually to stop or not.
      * At the moment this is a hack because the stop reason is not set for that case.
      * The check is if the stop reason is 'unknown' ( should be 'new script')
      */
      if(stopAt['stopped-reason'] == 'unknown')
      {

        runtime_id = stopAt['runtime-id'];
        if(  settings['js_source'].get('script') || runtimes.getObserve(runtime_id))
        {
          if( runtimes.getSelectedRuntimeId() != runtime_id )
          {
            runtimes.setSelectedRuntimeId(runtime_id);
          }
          // the runtime id can be different for each frame.
          var tag = tagManager.setCB(null, parseBacktrace, [stopAt['runtime-id']]);
          services['ecmascript-debugger'].backtrace(tag, stopAt);
          if( views.js_source.showLine( stopAt['script-id'], line - 10 ) )
          {
            views.js_source.showLinePointer( line, true );
          }
          __controls_enabled = true;
          toolbars.js_source.enableButtons('continue');
          messages.post('host-state', {state: 'waiting'});
        }
        else
        {
          this.__continue('run');
        }
      }
      else
      {
        runtime_id = stopAt['runtime-id'];

        // the runtime id can be different for each frame.
        var tag = tagManager.setCB(null, parseBacktrace, [stopAt['runtime-id']]);
        services['ecmascript-debugger'].backtrace(tag, stopAt);
        if( views.js_source.showLine( stopAt['script-id'], line - 10 ) )
        {
          views.js_source.showLinePointer( line, true );
        }
        __controls_enabled = true;
        toolbars.js_source.enableButtons('continue');
      }
    }
    else
    {
      throw 'not a line number: '+stopAt['line-number'];
    }
  }

  messages.addListener('setting-changed', onSettingChange);
}<|endoftext|>


<commit_before>/**
 * Element containing a label.
 *
 * @abstract
 * @class
 *
 * @constructor
 * @param {Object} [config] Configuration options
 * @cfg {jQuery} [$label] Label node, assigned to #$label, omit to use a generated `<span>`
 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
 */
OO.ui.LabelElement = function OoUiLabelElement( config ) {
	// Configuration initialization
	config = config || {};

	// Properties
	this.$label = null;
	this.label = null;
	this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;

	// Initialization
	this.setLabel( config.label || this.constructor.static.label );
	this.setLabelElement( config.$label || $( '<span>' ) );
};

/* Setup */

OO.initClass( OO.ui.LabelElement );

/* Events */

/**
 * @event labelChange
 * @param {string} value
 */

/* Static Properties */

/**
 * Label.
 *
 * @static
 * @inheritable
 * @property {string|Function|null} Label text; a function that returns nodes or text; or null for
 *  no label
 */
OO.ui.LabelElement.static.label = null;

/* Methods */

/**
 * Set the label element.
 *
 * If an element is already set, it will be cleaned up before setting up the new element.
 *
 * @param {jQuery} $label Element to use as label
 */
OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
	if ( this.$label ) {
		this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
	}

	this.$label = $label.addClass( 'oo-ui-labelElement-label' );
	this.setLabelContent( this.label );
};

/**
 * Set the label.
 *
 * An empty string will result in the label being hidden. A string containing only whitespace will
 * be converted to a single ` `.
 *
 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
 *  text; or null for no label
 * @chainable
 */
OO.ui.LabelElement.prototype.setLabel = function ( label ) {
	label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
	label = ( typeof label === 'string' && label.length ) || label instanceof jQuery ? label : null;

	this.$element.toggleClass( 'oo-ui-labelElement', !!label );

	if ( this.label !== label ) {
		if ( this.$label ) {
			this.setLabelContent( label );
		}
		this.label = label;
		this.emit( 'labelChange' );
	}

	return this;
};

/**
 * Get the label.
 *
 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
 *  text; or null for no label
 */
OO.ui.LabelElement.prototype.getLabel = function () {
	return this.label;
};

/**
 * Fit the label.
 *
 * @chainable
 */
OO.ui.LabelElement.prototype.fitLabel = function () {
	if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
		this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
	}

	return this;
};

/**
 * Set the content of the label.
 *
 * Do not call this method until after the label element has been set by #setLabelElement.
 *
 * @private
 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
 *  text; or null for no label
 */
OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
	if ( typeof label === 'string' ) {
		if ( label.match( /^\s*$/ ) ) {
			// Convert whitespace only string to a single non-breaking space
			this.$label.html( ' ' );
		} else {
			this.$label.text( label );
		}
	} else if ( label instanceof jQuery ) {
		this.$label.empty().append( label );
	} else {
		this.$label.empty();
	}
};
<commit_msg>LabelElement: Add description, config description, static property description<commit_after>/**
 * LabelElement is often mixed into other classes to generate a label, which
 * helps identify the function of an interface element.
 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
 *
 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
 *
 * @abstract
 * @class
 *
 * @constructor
 * @param {Object} [config] Configuration options
 * @cfg {jQuery} [$label] The label element created by the class. If this
 *  configuration is omitted, the label element will use a generated `<span>`.
 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
 *  a jQuery selection of elements, or a function that will produce a string in the future. See the
 *  [OOjs UI documentation on MediaWiki] [2] for examples.
 *  [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
 *  The label will be truncated to fit if necessary.
 */
OO.ui.LabelElement = function OoUiLabelElement( config ) {
	// Configuration initialization
	config = config || {};

	// Properties
	this.$label = null;
	this.label = null;
	this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;

	// Initialization
	this.setLabel( config.label || this.constructor.static.label );
	this.setLabelElement( config.$label || $( '<span>' ) );
};

/* Setup */

OO.initClass( OO.ui.LabelElement );

/* Events */

/**
 * @event labelChange
 * @param {string} value
 */

/* Static Properties */

/**
 * The label text. The label can be specified as a plaintext string, a function that will
 * produce a string in the future, or `null` for no label. The static value will
 * be overridden if a label is specified with the #label config option.
 *
 * @static
 * @inheritable
 * @property {string|Function|null}
 */
OO.ui.LabelElement.static.label = null;

/* Methods */

/**
 * Set the label element.
 *
 * If an element is already set, it will be cleaned up before setting up the new element.
 *
 * @param {jQuery} $label Element to use as label
 */
OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
	if ( this.$label ) {
		this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
	}

	this.$label = $label.addClass( 'oo-ui-labelElement-label' );
	this.setLabelContent( this.label );
};

/**
 * Set the label.
 *
 * An empty string will result in the label being hidden. A string containing only whitespace will
 * be converted to a single ` `.
 *
 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
 *  text; or null for no label
 * @chainable
 */
OO.ui.LabelElement.prototype.setLabel = function ( label ) {
	label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
	label = ( typeof label === 'string' && label.length ) || label instanceof jQuery ? label : null;

	this.$element.toggleClass( 'oo-ui-labelElement', !!label );

	if ( this.label !== label ) {
		if ( this.$label ) {
			this.setLabelContent( label );
		}
		this.label = label;
		this.emit( 'labelChange' );
	}

	return this;
};

/**
 * Get the label.
 *
 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
 *  text; or null for no label
 */
OO.ui.LabelElement.prototype.getLabel = function () {
	return this.label;
};

/**
 * Fit the label.
 *
 * @chainable
 */
OO.ui.LabelElement.prototype.fitLabel = function () {
	if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
		this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
	}

	return this;
};

/**
 * Set the content of the label.
 *
 * Do not call this method until after the label element has been set by #setLabelElement.
 *
 * @private
 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
 *  text; or null for no label
 */
OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
	if ( typeof label === 'string' ) {
		if ( label.match( /^\s*$/ ) ) {
			// Convert whitespace only string to a single non-breaking space
			this.$label.html( ' ' );
		} else {
			this.$label.text( label );
		}
	} else if ( label instanceof jQuery ) {
		this.$label.empty().append( label );
	} else {
		this.$label.empty();
	}
};
<|endoftext|>


<commit_before><commit_msg>Update cities-ats.js<commit_after><|endoftext|>