<commit_before>
angular.module('openspecimen')
  .directive('osFileUpload', function($timeout, $q, $http, Alerts) {
    return {
      restrict: 'A',
      replace: true,
      scope: {
        ctrl: '='
      },
      controller: function() {
        this.data = null;
        this.q = null;

        this.isFileSelected = function() {
          return !!this.data
        }

        this.submit = function() {
          this.q = $q.defer();
          if (this.data) {
            this.data.submit();
          } else {
            Alerts.error('common.no_file_selected');
            this.q.reject();
          }

          return this.q.promise;
        };

        this.done = function(resp) {
          this.q.resolve(resp.result);
        };

        this.fail = function(resp) {
          var xhr = resp.xhr('responseText');
          var status = Math.floor(xhr.status / 100);

          var responses = eval(xhr.response);
          var errMsgs = [];
          angular.forEach(responses, function(err) {
            errMsgs.push(err.message + "(" + err.code + ")");
          });

          if (errMsgs.length > 0) {
            Alerts.errorText(errMsgs);
          } else if (status == 4) {
            Alerts.error('common.ui_error');
          } else if (status == 5) {
            Alerts.error('common.server_error');
          }

          this.q.reject(resp);
        }
      },
      link: function(scope, element, attrs, ctrl) {
        attrs.$observe('disabled', function() {
          if (attrs.disabled == true) {
            element.find('input').attr('disabled', 'disabled');
          } else {
            element.find('input').removeAttr('disabled');
          }
        });

        $timeout(function() {
          scope.ctrl = ctrl;

          element.find('input').fileupload({
            dataType: 'json',
            beforeSend: function(xhr) {
              xhr.setRequestHeader('X-OS-API-TOKEN', $http.defaults.headers.common['X-OS-API-TOKEN']);
            },
            add: function (e, data) {
              element.find('span').text(data.files[0].name);
              ctrl.data = data;
            },
            done: function(e, data) {
              ctrl.done(data);
            },
            fail: function(e, data) {
              ctrl.fail(data);
            }
          });

          element.find('input').bind('change', function() { $timeout(angular.noop); });
        });
      },
      template:
        '
' +
          '<input class="form-control" name="file" type="file">' +
          '' +
             'No File Selected' +
          '' +
        '
'
    };
  });
<commit_msg>OPSMN-4613: Fixed the file uploader widget to not send "undefined" auth token string. This happens when SAML based login is used in which case only the cookie is used.<commit_after>
angular.module('openspecimen')
  .directive('osFileUpload', function($timeout, $q, $http, Alerts) {
    return {
      restrict: 'A',
      replace: true,
      scope: {
        ctrl: '='
      },
      controller: function() {
        this.data = null;
        this.q = null;

        this.isFileSelected = function() {
          return !!this.data
        }

        this.submit = function() {
          this.q = $q.defer();
          if (this.data) {
            this.data.submit();
          } else {
            Alerts.error('common.no_file_selected');
            this.q.reject();
          }

          return this.q.promise;
        };

        this.done = function(resp) {
          this.q.resolve(resp.result);
        };

        this.fail = function(resp) {
          var xhr = resp.xhr('responseText');
          var status = Math.floor(xhr.status / 100);

          var responses = eval(xhr.response);
          var errMsgs = [];
          angular.forEach(responses, function(err) {
            errMsgs.push(err.message + "(" + err.code + ")");
          });

          if (errMsgs.length > 0) {
            Alerts.errorText(errMsgs);
          } else if (status == 4) {
            Alerts.error('common.ui_error');
          } else if (status == 5) {
            Alerts.error('common.server_error');
          }

          this.q.reject(resp);
        }
      },
      link: function(scope, element, attrs, ctrl) {
        attrs.$observe('disabled', function() {
          if (attrs.disabled == true) {
            element.find('input').attr('disabled', 'disabled');
          } else {
            element.find('input').removeAttr('disabled');
          }
        });

        $timeout(function() {
          scope.ctrl = ctrl;

          element.find('input').fileupload({
            dataType: 'json',
            beforeSend: function(xhr) {
              if ($http.defaults.headers.common["X-OS-API-TOKEN"]) {
                xhr.setRequestHeader('X-OS-API-TOKEN', $http.defaults.headers.common['X-OS-API-TOKEN']);
              }
            },
            add: function (e, data) {
              element.find('span').text(data.files[0].name);
              ctrl.data = data;
            },
            done: function(e, data) {
              ctrl.done(data);
            },
            fail: function(e, data) {
              ctrl.fail(data);
            }
          });

          element.find('input').bind('change', function() { $timeout(angular.noop); });
        });
      },
      template:
        '
' +
          '<input class="form-control" name="file" type="file">' +
          '' +
             'No File Selected' +
          '' +
        '
'
    };
  });
<|endoftext|>


<commit_before>/* source: http://inspirationalpixels.com/tutorials/creating-tabs-with-html-css-and-jquery */

jQuery(document).ready(function() {
    jQuery('.tabs .tab-links a').on('click', function(e)  {
        var currentAttrValue = jQuery(this).attr('href');

        // Show/Hide Tabs
        jQuery('.tabs ' + currentAttrValue).show().siblings().hide();

        // Change/remove current tab to active
        jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

        e.preventDefault();
    });
});<commit_msg>js update<commit_after>/* source: http://inspirationalpixels.com/tutorials/creating-tabs-with-html-css-and-jquery */

jQuery(document).ready(function() {
    jQuery('.tabs .tab-links a').on('click', function(e)  {
        var currentAttrValue = jQuery(this).attr('href');

        // Show/Hide Tabs
        jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();

        // Change/remove current tab to active
        jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

        e.preventDefault();
    });
});<|endoftext|>


<commit_before>document.addEventListener( 'DOMContentLoaded', function( event ) {
    // Do something

});
<commit_msg>Update util.js<commit_after>document.addEventListener( 'DOMContentLoaded', function( event ) {
    var util = (function(){
        'use strict';

        // Private variables for the Module
        //var people = ['Will', 'Steve'];

        // Variables cached from the DOM
        var $el = $('#peopleModule');
        var $button = $el.find('button');
        var $input = $el.find('input');
        var $ul = $el.find('ul');
        var template = $el.find('#people-template').html();

        //bind events
        $button.on('click', addPerson);
        $ul.delegate('i.del', 'click', deletePerson);

        // General AJAX error handler to log the exception and set a message in DIV tags with a ajaxError class
        $(document).ajaxError(function(e, xhr, settings, exception) {
            console.log("ajax exception = "+exception);
            console.log("ajax exception xhr.responseText = "+xhr.responseText);
            $(".ajaxError").html("An Error has occurred (see console log)");
        });

        // This is what is exposed from this Module
        return {
            //addPerson: addPerson,
            //deletePerson: deletePerson
        };

    })(); // var util = (function(){
}); // document.addEventListener( 'DOMContentLoaded', function( event ) {
//people.addPerson("Jake");
//people.deletePerson(0);

function sleep(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
	    if ((new Date().getTime() - start) > milliseconds){
	      break;
	    }
	}
}

$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}
/*
example.com?param1=name&param2=&id=6
		$.urlParam('param1'); // name
		$.urlParam('id');        // 6
		$.urlParam('param2');   // null
*/

var validEmailAddrRegExStr = "^((\"([ !#$%&'()*+,\\-./0-9:;<=>?@A-Z[\\]^_`a-z{|}~]|\\\\[ !\"#$%&'()*+,\\-./0-9:;<=>?@A-Z[\\\\\\]^_`a-z{|}~])*\"|([!#$%&'*+\\-/0-9=?A-Z^_`a-z{|}~]|\\\\[ !\"#$%&'()*+,\\-./0-9:;<=>?@A-Z[\\\\\\]^_`a-z{|}~])+)(\\.(\"([ !#$%&'()*+,\\-./0-9:;<=>?@A-Z[\\]^_`a-z{|}~]|\\\\[ !\"#$%&'()*+,\\-./0-9:;<=>?@A-Z[\\\\\\]^_`a-z{|}~])*\"|([!#$%&'*+\\-/0-9=?A-Z^_`a-z{|}~]|\\\\[ !\"#$%&'()*+,\\-./0-9:;<=>?@A-Z[\\\\\\]^_`a-z{|}~])+))*)@([a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?)*\\.(?![0-9]*\\.?$)[a-zA-Z0-9]{2,}\\.?)$";
var validEmailAddr = new RegExp(validEmailAddrRegExStr,"g");
/*
if (validEmailAddr.test(inStr)) {
	resultStr = 'VALID';
} else {
	resultStr = 'INVALID';
}
*/

//Non-Printable characters - Hex 01 to 1F, and 7F
var nonPrintableCharsStr = "[\x01-\x1F\x7F]";
//"g" global so it does more than 1 substitution
var regexNonPrintableChars = new RegExp(nonPrintableCharsStr,"g");

function cleanStr(inStr) {
	return inStr.replace(regexNonPrintableChars,'');
}

var commaHexStr = "[\x2C]";
var regexCommaHexStr = new RegExp(commaHexStr,"g");
function csvFilter(inVal) {
	return inVal.toString().replace(regexCommaHexStr,'');
}

//var.replace(/[^0-9]+\\.?[0-9]*/g, '');
/*
parseFloat()
//Non-Printable characters - Hex 01 to 1F, and 7F
var nonPrintableCharsStr = "[\x01-\x2D \x2F \x3A-\x7F]";
//"g" global so it does more than 1 substitution
var regexNonPrintableChars = new RegExp(nonPrintableCharsStr,"g");
function cleanStr(inStr) {
	return inStr.replace(regexNonPrintableChars,'');
}
*/

//Replace every ascii character except decimal and digits with a null, and round to 2 decimal places
var nonMoneyCharsStr = "[\x01-\x2D\x2F\x3A-\x7F]";
//"g" global so it does more than 1 substitution
var regexNonMoneyChars = new RegExp(nonMoneyCharsStr,"g");
function stringToMoney(inAmount) {
	var inAmountStr = ''+inAmount;
	inAmountStr = inAmountStr.replace(regexNonMoneyChars,'');
	return parseFloat(inAmountStr).toFixed(2);
}

function formatDate(inDate) {
	var tempDate = inDate;
	if (tempDate == null) {
		tempDate = new Date();
	}
	var tempMonth = tempDate.getMonth() + 1;
	if (tempDate.getMonth() < 9) {
		tempMonth = '0' + (tempDate.getMonth() + 1);
	}
	var tempDay = tempDate.getDate();
	if (tempDate.getDate() < 10) {
		tempDay = '0' + tempDate.getDate();
	}
	return tempDate.getFullYear()+'-'+tempMonth+'-'+tempDay;
}

function waitCursor() {
    $('*').css('cursor', 'progress');
    $(".ajaxError").html("");
}

/*
commented out because it messed up the cursor in other functions - put it individually around JSON services
$(document).ajaxComplete(function(event, request, settings) {
    $('*').css('cursor', 'default');
});
*/

// Helper functions for setting UI components from data
function setBoolText(inBool) {
	var outBoolStr = "NO";
	if (inBool) {
		outBoolStr = "YES";
	}
	return outBoolStr;
}
function setCheckbox(checkVal){
	var checkedStr = '';
	if (checkVal == 1) {
		checkedStr = 'checked=true';
	}
	return '<input type="checkbox" '+checkedStr+' disabled="disabled">';
}
function setCheckboxEdit(checkVal,idName){
	var checkedStr = '';
	if (checkVal == 1) {
		checkedStr = 'checked=true';
	}
	return '<input id="'+idName+'" type="checkbox" '+checkedStr+'>';
}
function setInputText(idName,textVal,textSize){
	return '<input id="'+idName+'" type="text" class="form-control input-sm resetval" value="'+textVal+'" size="'+textSize+'" maxlength="'+textSize+'">';
}
function setTextArea(idName,textVal,rows){
	return '<textarea id="'+idName+'" class="form-control input-sm" rows="'+rows+'">'+textVal+'</textarea>';
}
function setInputDate(idName,textVal,textSize){
	return '<input id="'+idName+'" type="text" class="form-control input-sm Date" value="'+textVal+'" size="'+textSize+'" maxlength="'+textSize+'" placeholder="YYYY-MM-DD">';
}
function setSelectOption(optVal,displayVal,selected,bg) {
	var outOpt = '';
	if (selected) {
		outOpt = '<option class="'+bg+'" value="'+optVal+'" selected>'+displayVal+'</option>';
	} else {
		outOpt = '<option class="'+bg+'" value="'+optVal+'">'+displayVal+'</option>';
	}
	return outOpt;
}

    var people = (function(){
    var people = ['Will', 'Steve'];

    //cache DOM
    var $el = $('#peopleModule');
    var $button = $el.find('button');
    var $input = $el.find('input');
    var $ul = $el.find('ul');
    var template = $el.find('#people-template').html();

    //bind events
    $button.on('click', addPerson);
    $ul.delegate('i.del', 'click', deletePerson);

    _render();

    function _render() {
       $ul.html(Mustache.render(template, {people: people}));
    }

    function addPerson(value) {
        var name = (typeof value === "string") ? value : $input.val();
        people.push(name);
        _render();
        $input.val('');
    }

    function deletePerson(event) {
        var i;
        if (typeof event === "number") {
            i = event;
        } else {
            var $remove = $(event.target).closest('li');
            i = $ul.find('li').index($remove);
        }
        people.splice(i, 1);
        _render();
    }

    return {
        addPerson: addPerson,
        deletePerson: deletePerson
    };

})();

<|endoftext|>


<commit_before>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
        // count character on keyup
        function counter(event){
            var maxLength     = 140;
            var currentLength = $("#status_textarea").val().length;
            var remaining = maxLength - currentLength;
            var counter   = $("#counter");
            counter.text(remaining);

            if (remaining <= 0) {
                counter.attr("class", "toomuch");
            } else {
                counter.attr("class", "");
            }
        }

        function submitonreturn(event) {
             if (event.keyCode == 13) {
                  $("#status_form").submit();
                  event.preventDefault();
                  event.stopPropagation();
                  return false;
             }
             return true;
        }

        if ($("#status_textarea").length) {
             $("#status_textarea").bind("keyup", counter);
             $("#status_textarea").bind("keydown", submitonreturn);

            // run once in case there's something in there
            counter();

             // set the focus
             $("#status_textarea").focus();
        }

     // XXX: refactor this code

     var favoptions = {dataType: 'xml',
               success: function(xml) {
                    var new_form = $('form.disfavor', xml).get(0);
                    var dis = new_form.id;
                    var fav = dis.replace('disfavor', 'favor');
                    if (document.importNode) {
                         new_form = document.importNode(new_form);
                    }
                    $('form#'+fav).replaceWith(new_form);
                    $('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
               }};

     var disoptions = {dataType: 'xml',
               success: function(xml) {
                    var new_form = $('form.favor', xml).get(0);
                    var fav = new_form.id;
                    var dis = fav.replace('favor', 'disfavor');
                    if (document.importNode) {
                         new_form = document.importNode(new_form);
                    }
                    $('form#'+dis).replaceWith(new_form);
                    $('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);                    ;
               }};

     function addAjaxHidden() {
          var ajax = document.createElement('input');
          ajax.setAttribute('type', 'hidden');
          ajax.setAttribute('name', 'ajax');
          ajax.setAttribute('value', 1);
          this.appendChild(ajax);
     }

     $("form.favor").ajaxForm(favoptions);
     $("form.disfavor").ajaxForm(disoptions);

     $("form.favor").each(addAjaxHidden);
     $("form.disfavor").each(addAjaxHidden);
});

function doreply(nick,id) {
     rgx_username = /^[0-9a-zA-Z\-_.]*$/;
     if (nick.match(rgx_username)) {
          replyto = "@" + nick + " ";
          if ($("#status_textarea").length) {
               $("#status_textarea").val(replyto);
               $("form#status_form input#inreplyto").val(id);
               $("#status_textarea").focus();
			   return false;
		  }
     }
     return true;
}

<commit_msg>second argument to importNode<commit_after>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
        // count character on keyup
        function counter(event){
            var maxLength     = 140;
            var currentLength = $("#status_textarea").val().length;
            var remaining = maxLength - currentLength;
            var counter   = $("#counter");
            counter.text(remaining);

            if (remaining <= 0) {
                counter.attr("class", "toomuch");
            } else {
                counter.attr("class", "");
            }
        }

        function submitonreturn(event) {
             if (event.keyCode == 13) {
                  $("#status_form").submit();
                  event.preventDefault();
                  event.stopPropagation();
                  return false;
             }
             return true;
        }

        if ($("#status_textarea").length) {
             $("#status_textarea").bind("keyup", counter);
             $("#status_textarea").bind("keydown", submitonreturn);

            // run once in case there's something in there
            counter();

             // set the focus
             $("#status_textarea").focus();
        }

     // XXX: refactor this code

     var favoptions = {dataType: 'xml',
               success: function(xml) {
                    var new_form = $('form.disfavor', xml).get(0);
                    var dis = new_form.id;
                    var fav = dis.replace('disfavor', 'favor');
                    if (document.importNode) {
                         new_form = document.importNode(new_form, true);
                    }
                    $('form#'+fav).replaceWith(new_form);
                    $('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
               }};

     var disoptions = {dataType: 'xml',
               success: function(xml) {
                    var new_form = $('form.favor', xml).get(0);
                    var fav = new_form.id;
                    var dis = fav.replace('favor', 'disfavor');
                    if (document.importNode) {
                         new_form = document.importNode(new_form, true);
                    }
                    $('form#'+dis).replaceWith(new_form);
                    $('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);                    ;
               }};

     function addAjaxHidden() {
          var ajax = document.createElement('input');
          ajax.setAttribute('type', 'hidden');
          ajax.setAttribute('name', 'ajax');
          ajax.setAttribute('value', 1);
          this.appendChild(ajax);
     }

     $("form.favor").ajaxForm(favoptions);
     $("form.disfavor").ajaxForm(disoptions);

     $("form.favor").each(addAjaxHidden);
     $("form.disfavor").each(addAjaxHidden);
});

function doreply(nick,id) {
     rgx_username = /^[0-9a-zA-Z\-_.]*$/;
     if (nick.match(rgx_username)) {
          replyto = "@" + nick + " ";
          if ($("#status_textarea").length) {
               $("#status_textarea").val(replyto);
               $("form#status_form input#inreplyto").val(id);
               $("#status_textarea").focus();
			   return false;
		  }
     }
     return true;
}

<|endoftext|>


<commit_before>/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  UI interaction
 * @package   StatusNet
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

$(document).ready(function(){
    if ($('body.user_in').length > 0) {
        $('.'+SN.C.S.FormNotice).each(function() { SN.U.FormNoticeEnhancements($(this)); });

        $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });

        SN.U.NoticeReply();

        SN.U.NoticeDataAttach();

        SN.U.NewDirectMessage();
    }

    SN.U.NoticeAttachments();
});

var SN = { // StatusNet
    C: { // Config
        I: { // Init
            CounterBlackout: false,
            MaxLength: 140,
            PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
            HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
        },

        S: { // Selector
            Disabled: 'disabled',
            Warning: 'warning',
            Error: 'error',
            Success: 'success',
            Processing: 'processing',
            CommandResult: 'command_result',
            FormNotice: 'form_notice',
            NoticeDataText: 'notice_data-text',
            NoticeTextCount: 'notice_text-count',
            NoticeInReplyTo: 'notice_in-reply-to',
            NoticeDataAttach: 'notice_data-attach',
            NoticeDataAttachSelected: 'notice_data-attach_selected',
            NoticeActionSubmit: 'notice_action-submit'
        }
    },

    U: { // Utils
        FormNoticeEnhancements: function(form) {
            form_id = form.attr('id');
            if (maxLength > 0) {
                $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keyup', function(e) {
                    SN.U.Counter(form);
                });
                // run once in case there's something in there
                SN.U.Counter(form);
            }

            $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keydown', function(e) {
                SN.U.SubmitOnReturn(e, form);
            });

            if($('body')[0].id != 'conversation') {
                $('#'+form_id+' textarea').focus();
            }

            SN.U.FormNoticeXHR(form);
        },

        SubmitOnReturn: function(event, el) {
            if (event.keyCode == 13 || event.keyCode == 10) {
                el.submit();
                event.preventDefault();
                event.stopPropagation();
                $('#'+el[0].id+' #'+SN.U.NoticeDataText).blur();
                $('body').focus();
                return false;
            }
            return true;
        },

        Counter: function(form) {
            SN.C.I.FormNoticeCurrent = form;
            form_id = form.attr('id');
            if (typeof(maxLength) == "undefined") {
                 maxLength = SN.C.I.MaxLength;
            }

            if (maxLength <= 0) {
                return;
            }

            var remaining = maxLength - $('#'+form_id+' #'+SN.C.S.NoticeDataText).val().length;
            var counter = $('#'+form_id+' #'+SN.C.S.NoticeTextCount);

            if (remaining.toString() != counter.text()) {
                if (!SN.C.I.CounterBlackout || remaining == 0) {
                    if (counter.text() != String(remaining)) {
                        counter.text(remaining);
                    }
                    if (remaining < 0) {
                        form.addClass(SN.C.S.Warning);
                    } else {
                        form.removeClass(SN.C.S.Warning);
                    }
                    // Skip updates for the next 500ms.
                    // On slower hardware, updating on every keypress is unpleasant.
                    if (!SN.C.I.CounterBlackout) {
                        SN.C.I.CounterBlackout = true;
                        SN.C.I.FormNoticeCurrent = form;
                        window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
                    }
                }
            }
        },

        ClearCounterBlackout: function(form) {
            // Allow keyup events to poke the counter again
            SN.C.I.CounterBlackout = false;
            // Check if the string changed since we last looked
            SN.U.Counter(form);
        },

        FormXHR: function(f) {
            f.bind('submit', function(e) {
                form_id = $(this)[0].id;
                $.ajax({
                    type: 'POST',
                    dataType: 'xml',
                    url: $(this)[0].action,
                    data: $(this).serialize() + '&ajax=1',
                    beforeSend: function(xhr) {
                        $('#'+form_id).addClass(SN.C.S.Processing);
                        $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
                        $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert(errorThrown || textStatus);
                    },
                    success: function(data, textStatus) {
                        if (typeof($('form', data)[0]) != 'undefined') {
                            form_new = document._importNode($('form', data)[0], true);
                            $('#'+form_id).replaceWith(form_new);
                            $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
                        }
                        else {
                            $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
                        }
                    }
                });
                return false;
            });
        },

        FormNoticeXHR: function(form) {
            form_id = form.attr('id');
            form.append('<input type="hidden" name="ajax" value="1"/>');
            form.ajaxForm({
                dataType: 'xml',
                timeout: '60000',
                beforeSend: function(xhr) {
                    if ($('#'+form_id+' #'+SN.C.S.NoticeDataText)[0].value.length === 0) {
                        form.addClass(SN.C.S.Warning);
                        return false;
                    }
                    form.addClass(SN.C.S.Processing);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    return true;
                },
                error: function (xhr, textStatus, errorThrown) {
                    form.removeClass(SN.C.S.Processing);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
                    if (textStatus == 'timeout') {
                        alert ('Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists');
                    }
                    else {
                        if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
                            form.append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
                        }
                        else {
                            if(jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) < 0) {
                                alert('Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
                            }
                            else {
                                $('#'+form_id+' #'+SN.C.S.NoticeDataText).val('');
                                SN.U.NoticeFormEnhancements($('#'+SN.C.S.FormNotice));
                            }
                        }
                    }
                },
                success: function(data, textStatus) {
                    if ($('#'+SN.C.S.Error, data).length > 0) {
                        var result = document._importNode($('p', data)[0], true);
                        alert(result.textContent || result.innerHTML);
                    }
                    else {
                        if($('body')[0].id == 'bookmarklet') {
                            self.close();
                        }

                        if ($('#'+SN.C.S.CommandResult, data).length > 0) {
                            var result = document._importNode($('p', data)[0], true);
                            alert(result.textContent || result.innerHTML);
                        }
                        else {
                             notice = document._importNode($('li', data)[0], true);
                             if ($('#'+notice.id).length == 0) {
                                var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
                                var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                if($('body')[0].id == 'conversation') {
                                    if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                        $(notice_irt).append('

');
                                    }
                                    $($(notice_irt+' .notices')[0]).append(notice);
                                }
                                else {
                                    $("#notices_primary .notices").prepend(notice);
                                }
                                $('#'+notice.id).css({display:'none'});
                                $('#'+notice.id).fadeIn(2500);
                                SN.U.NoticeAttachments();
                                SN.U.NoticeReply();
                             }
                        }
                        $('#'+form_id+' #'+SN.C.S.NoticeDataText).val('');
                        $('#'+form_id+' #'+SN.C.S.NoticeDataAttach).val('');
                        $('#'+form_id+' #'+SN.C.S.NoticeInReplyTo).val('');
                        $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
                        SN.U.FormNoticeEnhancements(form);
                    }
                },
                complete: function(xhr, textStatus) {
                    form.removeClass(SN.C.S.Processing);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                }
            });
        },

        NoticeReply: function() {
            if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
                $('#content .notice').each(function() {
                    var notice = $(this)[0];
                    $($('.notice_reply', notice)[0]).click(function() {
                        var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
                        SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                        return false;
                    });
                });
            }
        },

        NoticeReplySet: function(nick,id) {
            if (nick.match(SN.C.I.PatternUsername)) {
                var text = $('#'+SN.C.S.NoticeDataText);
                if (text.length) {
                    replyto = '@' + nick + ' ';
                    text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
                    $('#'+SN.C.S.FormNotice+' input#'+SN.C.S.NoticeInReplyTo).val(id);
                    if (text[0].setSelectionRange) {
                        var len = text.val().length;
                        text[0].setSelectionRange(len,len);
                        text[0].focus();
                    }
                    return false;
                }
            }
            return true;
        },

        NoticeAttachments: function() {
            $.fn.jOverlay.options = {
                method : 'GET',
                data : '',
                url : '',
                color : '#000',
                opacity : '0.6',
                zIndex : 99,
                center : false,
                imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
                bgClickToClose : true,
                success : function() {
                    $('#jOverlayContent').append('<button class="close">×</button>');
                    $('#jOverlayContent button').click($.closeOverlay);
                },
                timeout : 0,
                autoHide : true,
                css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
            };

            $('#content .notice a.attachment').click(function() {
                $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
                return false;
            });

            var t;
            $("body:not(#shownotice) #content .notice a.thumbnail").hover(
                function() {
                    var anchor = $(this);
                    $("a.thumbnail").children('img').hide();
                    anchor.closest(".entry-title").addClass('ov');

                    if (anchor.children('img').length == 0) {
                        t = setTimeout(function() {
                            $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                                anchor.append(data);
                            });
                        }, 500);
                    }
                    else {
                        anchor.children('img').show();
                    }
                },
                function() {
                    clearTimeout(t);
                    $("a.thumbnail").children('img').hide();
                    $(this).closest(".entry-title").removeClass('ov');
                }
            );
        },

        NoticeDataAttach: function() {
            NDA = $('#'+SN.C.S.NoticeDataAttach);
            NDA.change(function() {
                S = '
'+$(this).val()+' <button class="close">×</button>
';
                NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
                (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#'+SN.C.S.FormNotice).append(S);
                $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
                    $('#'+SN.C.S.NoticeDataAttachSelected).remove();
                    NDA.val('');
                });
            });
        },

        NewDirectMessage: function() {
            NDM = $('.entity_send-a-message a');
            NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
            NDM.click(function() {
                var NDMF = $('.entity_send-a-message form');
                if (NDMF.length == 0) {
                    $.get(NDM.attr('href'), null, function(data) {
                        $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
                        NDMF = $('.entity_send-a-message .form_notice');
                        SN.U.FormNoticeEnhancements(NDMF);
                        NDMF.append('<button class="close">×</button>');
                        $('.entity_send-a-message button').click(function(){
                            NDMF.hide();
                            return false;
                        });
                    });
                }
                else {
                    NDMF.show();
                    $('.entity_send-a-message textarea').focus();
                }
                return false;
            });
        }
    }
}
<commit_msg>Fixed object string name<commit_after>/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  UI interaction
 * @package   StatusNet
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

$(document).ready(function(){
    if ($('body.user_in').length > 0) {
        $('.'+SN.C.S.FormNotice).each(function() { SN.U.FormNoticeEnhancements($(this)); });

        $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });

        SN.U.NoticeReply();

        SN.U.NoticeDataAttach();

        SN.U.NewDirectMessage();
    }

    SN.U.NoticeAttachments();
});

var SN = { // StatusNet
    C: { // Config
        I: { // Init
            CounterBlackout: false,
            MaxLength: 140,
            PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
            HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
        },

        S: { // Selector
            Disabled: 'disabled',
            Warning: 'warning',
            Error: 'error',
            Success: 'success',
            Processing: 'processing',
            CommandResult: 'command_result',
            FormNotice: 'form_notice',
            NoticeDataText: 'notice_data-text',
            NoticeTextCount: 'notice_text-count',
            NoticeInReplyTo: 'notice_in-reply-to',
            NoticeDataAttach: 'notice_data-attach',
            NoticeDataAttachSelected: 'notice_data-attach_selected',
            NoticeActionSubmit: 'notice_action-submit'
        }
    },

    U: { // Utils
        FormNoticeEnhancements: function(form) {
            form_id = form.attr('id');
            if (maxLength > 0) {
                $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keyup', function(e) {
                    SN.U.Counter(form);
                });
                // run once in case there's something in there
                SN.U.Counter(form);
            }

            $('#'+form_id+' #'+SN.C.S.NoticeDataText).bind('keydown', function(e) {
                SN.U.SubmitOnReturn(e, form);
            });

            if($('body')[0].id != 'conversation') {
                $('#'+form_id+' textarea').focus();
            }

            SN.U.FormNoticeXHR(form);
        },

        SubmitOnReturn: function(event, el) {
            if (event.keyCode == 13 || event.keyCode == 10) {
                $('#'+el[0].id+' #'+SN.C.S.NoticeDataText).blur();
                $('body').focus();
                el.submit();
                event.preventDefault();
                event.stopPropagation();
                return false;
            }
            return true;
        },

        Counter: function(form) {
            SN.C.I.FormNoticeCurrent = form;
            form_id = form.attr('id');
            if (typeof(maxLength) == "undefined") {
                 maxLength = SN.C.I.MaxLength;
            }

            if (maxLength <= 0) {
                return;
            }

            var remaining = maxLength - $('#'+form_id+' #'+SN.C.S.NoticeDataText).val().length;
            var counter = $('#'+form_id+' #'+SN.C.S.NoticeTextCount);

            if (remaining.toString() != counter.text()) {
                if (!SN.C.I.CounterBlackout || remaining == 0) {
                    if (counter.text() != String(remaining)) {
                        counter.text(remaining);
                    }
                    if (remaining < 0) {
                        form.addClass(SN.C.S.Warning);
                    } else {
                        form.removeClass(SN.C.S.Warning);
                    }
                    // Skip updates for the next 500ms.
                    // On slower hardware, updating on every keypress is unpleasant.
                    if (!SN.C.I.CounterBlackout) {
                        SN.C.I.CounterBlackout = true;
                        SN.C.I.FormNoticeCurrent = form;
                        window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
                    }
                }
            }
        },

        ClearCounterBlackout: function(form) {
            // Allow keyup events to poke the counter again
            SN.C.I.CounterBlackout = false;
            // Check if the string changed since we last looked
            SN.U.Counter(form);
        },

        FormXHR: function(f) {
            f.bind('submit', function(e) {
                form_id = $(this)[0].id;
                $.ajax({
                    type: 'POST',
                    dataType: 'xml',
                    url: $(this)[0].action,
                    data: $(this).serialize() + '&ajax=1',
                    beforeSend: function(xhr) {
                        $('#'+form_id).addClass(SN.C.S.Processing);
                        $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
                        $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert(errorThrown || textStatus);
                    },
                    success: function(data, textStatus) {
                        if (typeof($('form', data)[0]) != 'undefined') {
                            form_new = document._importNode($('form', data)[0], true);
                            $('#'+form_id).replaceWith(form_new);
                            $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
                        }
                        else {
                            $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
                        }
                    }
                });
                return false;
            });
        },

        FormNoticeXHR: function(form) {
            form_id = form.attr('id');
            form.append('<input type="hidden" name="ajax" value="1"/>');
            form.ajaxForm({
                dataType: 'xml',
                timeout: '60000',
                beforeSend: function(xhr) {
                    if ($('#'+form_id+' #'+SN.C.S.NoticeDataText)[0].value.length === 0) {
                        form.addClass(SN.C.S.Warning);
                        return false;
                    }
                    form.addClass(SN.C.S.Processing);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    return true;
                },
                error: function (xhr, textStatus, errorThrown) {
                    form.removeClass(SN.C.S.Processing);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
                    if (textStatus == 'timeout') {
                        alert ('Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists');
                    }
                    else {
                        if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
                            form.append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
                        }
                        else {
                            if(jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) < 0) {
                                alert('Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
                            }
                            else {
                                $('#'+form_id+' #'+SN.C.S.NoticeDataText).val('');
                                SN.U.NoticeFormEnhancements($('#'+SN.C.S.FormNotice));
                            }
                        }
                    }
                },
                success: function(data, textStatus) {
                    if ($('#'+SN.C.S.Error, data).length > 0) {
                        var result = document._importNode($('p', data)[0], true);
                        alert(result.textContent || result.innerHTML);
                    }
                    else {
                        if($('body')[0].id == 'bookmarklet') {
                            self.close();
                        }

                        if ($('#'+SN.C.S.CommandResult, data).length > 0) {
                            var result = document._importNode($('p', data)[0], true);
                            alert(result.textContent || result.innerHTML);
                        }
                        else {
                             notice = document._importNode($('li', data)[0], true);
                             if ($('#'+notice.id).length == 0) {
                                var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
                                var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                if($('body')[0].id == 'conversation') {
                                    if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                        $(notice_irt).append('

');
                                    }
                                    $($(notice_irt+' .notices')[0]).append(notice);
                                }
                                else {
                                    $("#notices_primary .notices").prepend(notice);
                                }
                                $('#'+notice.id).css({display:'none'});
                                $('#'+notice.id).fadeIn(2500);
                                SN.U.NoticeAttachments();
                                SN.U.NoticeReply();
                             }
                        }
                        $('#'+form_id+' #'+SN.C.S.NoticeDataText).val('');
                        $('#'+form_id+' #'+SN.C.S.NoticeDataAttach).val('');
                        $('#'+form_id+' #'+SN.C.S.NoticeInReplyTo).val('');
                        $('#'+form_id+' #'+SN.C.S.NoticeDataAttachSelected).remove();
                        SN.U.FormNoticeEnhancements(form);
                    }
                },
                complete: function(xhr, textStatus) {
                    form.removeClass(SN.C.S.Processing);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
                    $('#'+form_id+' #'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                }
            });
        },

        NoticeReply: function() {
            if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
                $('#content .notice').each(function() {
                    var notice = $(this)[0];
                    $($('.notice_reply', notice)[0]).click(function() {
                        var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
                        SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                        return false;
                    });
                });
            }
        },

        NoticeReplySet: function(nick,id) {
            if (nick.match(SN.C.I.PatternUsername)) {
                var text = $('#'+SN.C.S.NoticeDataText);
                if (text.length) {
                    replyto = '@' + nick + ' ';
                    text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
                    $('#'+SN.C.S.FormNotice+' input#'+SN.C.S.NoticeInReplyTo).val(id);
                    if (text[0].setSelectionRange) {
                        var len = text.val().length;
                        text[0].setSelectionRange(len,len);
                        text[0].focus();
                    }
                    return false;
                }
            }
            return true;
        },

        NoticeAttachments: function() {
            $.fn.jOverlay.options = {
                method : 'GET',
                data : '',
                url : '',
                color : '#000',
                opacity : '0.6',
                zIndex : 99,
                center : false,
                imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
                bgClickToClose : true,
                success : function() {
                    $('#jOverlayContent').append('<button class="close">×</button>');
                    $('#jOverlayContent button').click($.closeOverlay);
                },
                timeout : 0,
                autoHide : true,
                css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
            };

            $('#content .notice a.attachment').click(function() {
                $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
                return false;
            });

            var t;
            $("body:not(#shownotice) #content .notice a.thumbnail").hover(
                function() {
                    var anchor = $(this);
                    $("a.thumbnail").children('img').hide();
                    anchor.closest(".entry-title").addClass('ov');

                    if (anchor.children('img').length == 0) {
                        t = setTimeout(function() {
                            $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                                anchor.append(data);
                            });
                        }, 500);
                    }
                    else {
                        anchor.children('img').show();
                    }
                },
                function() {
                    clearTimeout(t);
                    $("a.thumbnail").children('img').hide();
                    $(this).closest(".entry-title").removeClass('ov');
                }
            );
        },

        NoticeDataAttach: function() {
            NDA = $('#'+SN.C.S.NoticeDataAttach);
            NDA.change(function() {
                S = '
'+$(this).val()+' <button class="close">×</button>
';
                NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
                (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#'+SN.C.S.FormNotice).append(S);
                $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
                    $('#'+SN.C.S.NoticeDataAttachSelected).remove();
                    NDA.val('');
                });
            });
        },

        NewDirectMessage: function() {
            NDM = $('.entity_send-a-message a');
            NDM.attr({'href':NDM.attr('href')+'&ajax=1'});
            NDM.click(function() {
                var NDMF = $('.entity_send-a-message form');
                if (NDMF.length == 0) {
                    $.get(NDM.attr('href'), null, function(data) {
                        $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
                        NDMF = $('.entity_send-a-message .form_notice');
                        SN.U.FormNoticeEnhancements(NDMF);
                        NDMF.append('<button class="close">×</button>');
                        $('.entity_send-a-message button').click(function(){
                            NDMF.hide();
                            return false;
                        });
                    });
                }
                else {
                    NDMF.show();
                    $('.entity_send-a-message textarea').focus();
                }
                return false;
            });
        }
    }
}
<|endoftext|>


<commit_before>/*global suite, test*/ //comment for eslint

// This test uses TDD Mocha. see https://mochajs.org/ for help
// http://ricostacruz.com/cheatsheets/mocha-tdd

// The module 'assert' provides assertion methods from node
const assert = require("assert")

const evals = require("./evaluators")

suite("PythonEvaluator Tests", () => {
    let pyEvaluator = new evals.PythonEvaluator()

    test("sanity check: 1+1=2", () => {
        assert.equal(1+1,2)
    })

    test("PythonEvaluator returns result", function(done){
        pyEvaluator.onResult = (result)=>{
            console.log(result)
            assert.notEqual(result, null)
            done()
        }
        pyEvaluator.execCode({evalCode:"x"})
    })

    test("PythonEvaluator returns error when bad code", function(done){
        pyEvaluator.onResult = (result)=>{
            assert.notEqual(result.ERROR, null)
            assert.notEqual(result.ERROR.trim(), "")
            done()
        }
        pyEvaluator.execCode({evalCode:"x"})
    })

    test("PythonEvaluator returns user variables", function(done){
        pyEvaluator.onResult = (result)=>{
            assert.equal(result.userVariables['x'], 1)
            done()
        }
        pyEvaluator.execCode({evalCode:"x=1"})
    })

    test("PythonEvaluator can print stdout", function(done){
        let hasPrinted = false
        pyEvaluator.onPrint = (stdout)=>{
            assert.equal(stdout, "hello world")
            hasPrinted = true
        }

        pyEvaluator.onResult = () => {
            if(!hasPrinted) assert.fail("program has returned result","program should still be printing")
            else done()
        }

        pyEvaluator.execCode({evalCode:"print('hello world')"})
    })

    test("PythonEvaluator can print multiple lines", function(done){
        let firstPrint = false
        let secondPrint = false

        pyEvaluator.onPrint = (stdout)=>{
            if(firstPrint){
                assert.equal(stdout, '2')
                secondPrint = true
            }
            else{
                assert.equal(stdout, "1")
                firstPrint = true
            }
        }

        pyEvaluator.onResult = () => {
            if(!secondPrint) assert.fail("program has returned result","program should still be printing")
            else done()
        }

        pyEvaluator.execCode({evalCode:"[print(x) for x in [1,2]]"})
    })

    test("PythonEvaluator returns result after print", function(done){
        pyEvaluator.onPrint = (stdout)=>{
            assert.equal(stdout, "hello world")
            assert.equal(pyEvaluator.running, true)
        }

        pyEvaluator.onResult = () => {
            assert.equal(pyEvaluator.running, false)
            done()
        }

        pyEvaluator.execCode({evalCode:"print('hello world')"})
    })

})<commit_msg>updated unit tests (all tests passing now)<commit_after>/*global suite, test*/ //comment for eslint

// This test uses TDD Mocha. see https://mochajs.org/ for help
// http://ricostacruz.com/cheatsheets/mocha-tdd

// The module 'assert' provides assertion methods from node
const assert = require("assert")

const evals = require("./evaluators")

suite("PythonEvaluator Tests", () => {
    let pyEvaluator = new evals.PythonEvaluator()

    test("sanity check: 1+1=2", () => {
        assert.equal(1+1,2)
    })

    test("PythonEvaluator returns result", function(done){
        pyEvaluator.onResult = (result)=>{
            console.log(result)
            assert.notEqual(result, null)
            done()
        }
        pyEvaluator.execCode({evalCode:"x"})
    })

    test("PythonEvaluator returns error when bad code", function(done){
        pyEvaluator.onResult = (result)=>{
            assert.notEqual(result.ERROR, null)
            assert.notEqual(result.ERROR.trim(), "")
            done()
        }
        pyEvaluator.execCode({evalCode:"x"})
    })

    test("PythonEvaluator returns user variables", function(done){
        pyEvaluator.onResult = (result)=>{
            assert.equal(result.userVariables['x'], 1)
            done()
        }
        pyEvaluator.execCode({evalCode:"x=1", savedCode: ""})
    })

    test("PythonEvaluator can print stdout", function(done){
        let hasPrinted = false
        pyEvaluator.onPrint = (stdout)=>{
            assert.equal(stdout, "hello world")
            hasPrinted = true
        }

        pyEvaluator.onResult = () => {
            if(!hasPrinted) assert.fail("program has returned result","program should still be printing")
            else done()
        }

        pyEvaluator.execCode({evalCode:"print('hello world')", savedCode: ""})
    })

    test("PythonEvaluator can print multiple lines", function(done){
        let firstPrint = false
        let secondPrint = false

        pyEvaluator.onPrint = (stdout)=>{
            if(firstPrint){
                assert.equal(stdout, '2')
                secondPrint = true
            }
            else{
                assert.equal(stdout, "1")
                firstPrint = true
            }
        }

        pyEvaluator.onResult = () => {
            if(!secondPrint) assert.fail("program has returned result","program should still be printing")
            else done()
        }

        pyEvaluator.execCode({evalCode:"[print(x) for x in [1,2]]", savedCode: ""})
    })

    test("PythonEvaluator returns result after print", function(done){
        pyEvaluator.onPrint = (stdout)=>{
            assert.equal(stdout, "hello world")
            assert.equal(pyEvaluator.running, true)
        }

        pyEvaluator.onResult = () => {
            assert.equal(pyEvaluator.running, false)
            done()
        }

        pyEvaluator.execCode({evalCode:"print('hello world')"})
    })

})<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone', 'data', 'ui', 'nouislider', 'LZString', 'bootstrap', 'bootstrap-select', 'jquery.unveil'], function ($, _, Backbone, Data, Ui, noUiSlider, LZString, BitSet, skillDescTemplate) {
    var activeMenu = "";
    var runeList = [];
    var runeCheckList = [];
    var classId = 0;
    var minX = 0;
    var maxX = 0;
    var minY = 0;
    var maxY = 0;
    var scale = 0.2;
    var disableEvo3 = false;

    var initUiLanguage = function () {
        $('[data-lang]').each(function () {
            var $this = $(this);
            var key = $this.data("lang");
            var value = Ui.getText(key);
            $this.text(value);
        });
    };
    var getActiveMenu = function () {
        return activeMenu;
    }
    var setActiveMenu = function (id) {
        activeMenu = id;
        $("nav.navbar .active").removeClass('active');
        //$("body>div[data-tab]").hide();
        var current = $("nav.navbar [data-class-id=" + id + "]");
        current.parents('li').addClass('active');
    };
    var init = function (id, savedata) {
        clear();
        initControl();
        render(id, savedata);
    };
    var clear = function () {
        runeList = [];
        runeCheckList = [];
    };
    var initControl = function () {
        $('#btnSearch').click(function () {
            var text = $('#txtSearch').val();
            $('.rune[data-original-title*="' + text + '"]').popover('show');
        });
        $('#btnClear').click(function () {
            $('[data-toggle="popover"]').popover('hide');
        });

        $('#btnReset').click(function () {
            if (confirm("是否重置本次选择？")) {
                _.each(runeCheckList, function (o, i) {
                    var $rune = $("#rune" + o);
                    $rune.data('status', 0)
                        .removeClass('rune-checked')
                });
                runeCheckList = [];

                renderRuneLink();
                renderCost();
            }
        });
        $('#btnSave').click(function () {
            save();
        });
        $('input[name="evo3"]').change(function () {
            if (this.value == "true") {
                disableEvo3 = false;
            }
            else {
                disableEvo3 = true;
            }
            render(classId);
        });
        $('.rune-panel-switch').click(function(){
$('.rune-panel-main').toggle();
        });
    };
    var render = function (id, savedata) {
        console.log("render", id, savedata);
        var self = this;
        if (id == 0) {
            return;
        }
        classId = id;
        setActiveMenu(id);
        //clear main
        $('#main').find("img").attr('src', ''); //stop image loading when doPage
        $('#main').empty();
        //get data
        var astrolabe = Data.getAstrolabe();

        minX = _.min(astrolabe, function (o) { return o.X }).X;
        maxX = _.max(astrolabe, function (o) { return o.X }).X;
        minY = _.min(astrolabe, function (o) { return o.Y }).Y;
        maxY = _.max(astrolabe, function (o) { return o.Y }).Y;

        var $div = $("
").addClass("rune-container");

        _.each(astrolabe, function (o, i) {
            //debugger;
            var cost = Data.getRuneCost(o.Id);
            var desc = Data.getRuneDesc(o.Id, classId);
            var $rune = $("")
                .css("left", (o.X - minX) * scale)
                .css("top", (maxY - o.Y) * scale)
                .addClass("rune")
                .attr("id", "rune" + o.Id)
                .attr("data-id", o.Id)
                .data("rune", o)
                .data("cost", cost)
                .data("desc", desc)
                .data("status", 0)  //0:unchecked,1:checked,2:saved
                .attr("data-toggle", "popover")
                .attr("title", desc.Name)
                .attr("data-content", (desc.Desc || "")
                + "
" + _.reduce(cost, function (result, current) {
                    return result + current.Name + "*" + current.Count + " ";
                }, ""))
                .click(function () {
                    runeClick(o);
                });
            if (o.Id == 10000) {
                //set default rune as saved
                runeList.push(10000);
                $rune.addClass("rune-center")
                    .data("status", 2)
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (disableEvo3 && o.Evo == 3) {
                $rune.addClass("rune-not-available")
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (_.any(cost, function (o) { return o.Id == 5261; })) {
                $rune.addClass("rune-special");
            }
            $div.append($rune);
        });
        $('#main').append($div);

        $('[data-toggle="popover"]').popover({
            //container: 'body',
            html: true,
            trigger: 'hover focus'
        });

        if (savedata) {
            runeList = parseCondition(savedata);
        }
        _.each(runeList, function (o, i) {
            checkRune(o, true, true);
        });
        renderRuneLink();
        renderCost();

        setTimeout(function () {
            //a little delay to unveil for better unveil effect
            $('#main').find("img").unveil();
        }, 100);
    };

    var renderRuneLink = function () {
        $(".rune-link-container").remove();
        var $runeLink = $("<canvas>")
            .css("left", 0)
            .css("top", 0)
            .attr("width", (maxX - minX + 10) * scale)
            .attr("height", (maxY - minY + 10) * scale)
            .addClass("rune-link-container");
        $('.rune-container').append($runeLink);
        var linkcontext = $runeLink[0].getContext('2d');
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            _.each(runeData.Link, function (o, i) {
                var $runeTo = $(".rune[data-id=" + o + "]");
                var runeToData = $runeTo.data("rune");
                if ($runeTo.length > 0) {
                    linkcontext.beginPath();
                    linkcontext.moveTo($rune.position().left + 5, $rune.position().top + 5);
                    linkcontext.lineTo($runeTo.position().left + 5, $runeTo.position().top + 5);
                    linkcontext.lineWidth = 3;
                    if (disableEvo3 && (runeData.Evo == 3 || runeToData.Evo == 3)) {
                        linkcontext.strokeStyle = 'rgba(233, 233, 233, 0.15)';
                    }
                    else if ($rune.data('status') == 0 || $runeTo.data('status') == 0) {
                        linkcontext.strokeStyle = '#aaa';
                    }
                    else {
                        linkcontext.strokeStyle = 'skyblue';
                    }
                    linkcontext.stroke();
                }
            });
        });
    };
    var renderCost = function () {
        var runeCost = [];
        var runeCheckCost = [];
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            var status = $rune.data('status');
            var cost = $rune.data('cost');
            switch (status) {
                case 0: break;
                case 1: runeCheckCost.push(cost); break;
                case 2: runeCost.push(cost); break;
                default: break;
            }
        });
        runeCheckCost = _.reduce(runeCheckCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        runeCost = _.reduce(runeCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        var runeCheckCostText = "";
        _.each(runeCheckCost, function (o, i) {
            runeCheckCostText += i + "*" + o + " ";
        })
        $('#runeCheckCost').text(runeCheckCostText);
        var runeCostText = "";
        _.each(runeCost, function (o, i) {
            runeCostText += i + "*" + o + " ";
        })
        $('#runeCost').text(runeCostText);
    };

    var runeClick = function (rune) {
        var $rune = $("#rune" + rune.Id);
        var status = $rune.data('status');
        switch (status) {
            case 0: checkRune(rune.Id); break;
            case 1: uncheckRune(rune.Id); break;
            case 2: uncheckRuneWithConfirm(rune.Id); break;
            default: break;
        }
        renderRuneLink();
        renderCost();
    };

    var checkRune = function (runeId, noRecursion, isSaved) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if (disableEvo3 && $rune.data('rune').evo == 3) {
            return;
        }
        if (!noRecursion) {
            var path = Data.getPath(runeList.concat(runeCheckList), runeId);
            console.log("getPath", path);
            if (!path.length) {
                alert("无路径！")
                return;
            }
            _.each(path, function (o, i) {
                checkRune(o, true);
            });
        }
        else {
            if (isSaved) {
                $rune.data('status', 2)
                    .addClass('rune-saved');
            }
            else {
                $rune.data('status', 1)
                    .addClass('rune-checked');
                runeCheckList.push(runeId);
            }
        }
    };
    var uncheckRuneWithConfirm = function (runeId) {
        if (confirm("是否取消选中该符文？")) {
            uncheckRune(runeId);
        }
    };
    var uncheckRune = function (runeId, noRecursion) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if (disableEvo3 && $rune.data('rune').evo == 3) {
            return;
        }
        $rune.data('status', 0)
            .removeClass('rune-checked')
            .removeClass('rune-saved');
        runeList = _.without(runeList, runeId);
        runeCheckList = _.without(runeCheckList, runeId);
        if (!noRecursion) {
            var components = Data.getConnectedComponent(runeList.concat(runeCheckList));
            _.each(components, function (o, i) {
                if (_.contains(o, 10000) == false) {
                    _.each(o, function (p, j) {
                        uncheckRune(p, true);
                    });
                }
            });
        }
    };

    var save = function () {
        runeList = _.unique(runeList.concat(runeCheckList));
        runeCheckList = [];
        _.each(runeList, function (o, i) {
            var $rune = $("#rune" + o);
            $rune.data('status', 2)
                .removeClass('rune-checked')
                .addClass('rune-saved');
        });
        renderCost();

        var data = stringifyCondition(runeList);
        Backbone.history.navigate("class/" + classId + "/share/" + data, { trigger: false });
    };

    function stringifyCondition(condition) {
        return LZString.compressToEncodedURIComponent(JSON.stringify(condition));
    }

    function parseCondition(conditionJson) {
        return JSON.parse(LZString.decompressFromEncodedURIComponent(conditionJson));
    }

    return {
        initUiLanguage: initUiLanguage,
        getActiveMenu: getActiveMenu,
        setActiveMenu: setActiveMenu,
        init: init,
    };
});<commit_msg>code cleanup<commit_after>define(['jquery', 'underscore', 'backbone', 'data', 'ui', 'nouislider', 'LZString', 'bootstrap', 'bootstrap-select', 'jquery.unveil'], function ($, _, Backbone, Data, Ui, noUiSlider, LZString, BitSet, skillDescTemplate) {
    var activeMenu = "";
    var runeList = [];
    var runeCheckList = [];
    var classId = 0;
    var minX = 0;
    var maxX = 0;
    var minY = 0;
    var maxY = 0;
    var scale = 0.2;
    var disableEvo3 = false;

    var initUiLanguage = function () {
        $('[data-lang]').each(function () {
            var $this = $(this);
            var key = $this.data("lang");
            var value = Ui.getText(key);
            $this.text(value);
        });
    };
    var getActiveMenu = function () {
        return activeMenu;
    }
    var setActiveMenu = function (id) {
        activeMenu = id;
        $("nav.navbar .active").removeClass('active');
        //$("body>div[data-tab]").hide();
        var current = $("nav.navbar [data-class-id=" + id + "]");
        current.parents('li').addClass('active');
    };
    var init = function (id, savedata) {
        clear();
        initControl();
        render(id, savedata);
    };
    var clear = function () {
        runeList = [];
        runeCheckList = [];
    };
    var initControl = function () {
        $('#btnSearch').click(function () {
            var text = $('#txtSearch').val();
            $('.rune[data-original-title*="' + text + '"]').popover('show');
        });
        $('#btnClear').click(function () {
            $('[data-toggle="popover"]').popover('hide');
        });

        $('#btnReset').click(function () {
            if (confirm("是否重置本次选择？")) {
                _.each(runeCheckList, function (o, i) {
                    var $rune = $("#rune" + o);
                    $rune.data('status', 0)
                        .removeClass('rune-checked')
                });
                runeCheckList = [];

                renderRuneLink();
                renderCost();
            }
        });
        $('#btnSave').click(function () {
            save();
        });
        $('input[name="evo3"]').change(function () {
            if (this.value == "true") {
                disableEvo3 = false;
            }
            else {
                disableEvo3 = true;
            }
            render(classId);
        });
        $('.rune-panel-switch').click(function () {
            $('.rune-panel-main').toggle();
        });
    };
    var render = function (id, savedata) {
        console.log("render", id, savedata);
        var self = this;
        if (id == 0) {
            return;
        }
        classId = id;
        setActiveMenu(id);
        //clear main
        $('#main').find("img").attr('src', ''); //stop image loading when doPage
        $('#main').empty();
        //get data
        var astrolabe = Data.getAstrolabe();

        minX = _.min(astrolabe, function (o) { return o.X }).X;
        maxX = _.max(astrolabe, function (o) { return o.X }).X;
        minY = _.min(astrolabe, function (o) { return o.Y }).Y;
        maxY = _.max(astrolabe, function (o) { return o.Y }).Y;

        var $div = $("
").addClass("rune-container");

        _.each(astrolabe, function (o, i) {
            //debugger;
            var cost = Data.getRuneCost(o.Id);
            var desc = Data.getRuneDesc(o.Id, classId);
            var $rune = $("")
                .css("left", (o.X - minX) * scale)
                .css("top", (maxY - o.Y) * scale)
                .addClass("rune")
                .attr("id", "rune" + o.Id)
                .attr("data-id", o.Id)
                .data("rune", o)
                .data("cost", cost)
                .data("desc", desc)
                .data("status", 0)  //0:unchecked,1:checked,2:saved
                .attr("data-toggle", "popover")
                .attr("title", desc.Name)
                .attr("data-content", (desc.Desc || "")
                + "
" + _.reduce(cost, function (result, current) {
                    return result + current.Name + "*" + current.Count + " ";
                }, ""))
                .click(function () {
                    runeClick(o);
                });
            if (o.Id == 10000) {
                //set default rune as saved
                runeList.push(10000);
                $rune.addClass("rune-center")
                    .data("status", 2)
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (disableEvo3 && o.Evo == 3) {
                $rune.addClass("rune-not-available")
                    .attr("title", "")
                    .attr("data-toggle", "")
                    .off('click');
            }
            if (_.any(cost, function (o) { return o.Id == 5261; })) {
                $rune.addClass("rune-special");
            }
            $div.append($rune);
        });
        $('#main').append($div);

        $('[data-toggle="popover"]').popover({
            //container: 'body',
            html: true,
            trigger: 'hover focus'
        });

        if (savedata) {
            runeList = parseCondition(savedata);
        }
        _.each(runeList, function (o, i) {
            checkRune(o, true, true);
        });
        renderRuneLink();
        renderCost();

        setTimeout(function () {
            //a little delay to unveil for better unveil effect
            $('#main').find("img").unveil();
        }, 100);
    };

    var renderRuneLink = function () {
        $(".rune-link-container").remove();
        var $runeLink = $("<canvas>")
            .css("left", 0)
            .css("top", 0)
            .attr("width", (maxX - minX + 10) * scale)
            .attr("height", (maxY - minY + 10) * scale)
            .addClass("rune-link-container");
        $('.rune-container').append($runeLink);
        var linkcontext = $runeLink[0].getContext('2d');
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            _.each(runeData.Link, function (o, i) {
                var $runeTo = $(".rune[data-id=" + o + "]");
                var runeToData = $runeTo.data("rune");
                if ($runeTo.length > 0) {
                    linkcontext.beginPath();
                    linkcontext.moveTo($rune.position().left + 5, $rune.position().top + 5);
                    linkcontext.lineTo($runeTo.position().left + 5, $runeTo.position().top + 5);
                    linkcontext.lineWidth = 3;
                    if (disableEvo3 && (runeData.Evo == 3 || runeToData.Evo == 3)) {
                        linkcontext.strokeStyle = 'rgba(233, 233, 233, 0.15)';
                    }
                    else if ($rune.data('status') == 0 || $runeTo.data('status') == 0) {
                        linkcontext.strokeStyle = '#aaa';
                    }
                    else {
                        linkcontext.strokeStyle = 'skyblue';
                    }
                    linkcontext.stroke();
                }
            });
        });
    };
    var renderCost = function () {
        var runeCost = [];
        var runeCheckCost = [];
        $(".rune").each(function (i, o) {
            var $rune = $(o);
            var runeData = $rune.data("rune")
            var status = $rune.data('status');
            var cost = $rune.data('cost');
            switch (status) {
                case 0: break;
                case 1: runeCheckCost.push(cost); break;
                case 2: runeCost.push(cost); break;
                default: break;
            }
        });
        runeCheckCost = _.reduce(runeCheckCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        runeCost = _.reduce(runeCost, function (memo, item) {
            _.each(item, function (o, i) {
                memo[o.Name] = (memo[o.Name] || 0) + o.Count;
            })
            return memo;
        }, {});
        var runeCheckCostText = "";
        _.each(runeCheckCost, function (o, i) {
            runeCheckCostText += i + "*" + o + " ";
        })
        $('#runeCheckCost').text(runeCheckCostText);
        var runeCostText = "";
        _.each(runeCost, function (o, i) {
            runeCostText += i + "*" + o + " ";
        })
        $('#runeCost').text(runeCostText);
    };

    var runeClick = function (rune) {
        var $rune = $("#rune" + rune.Id);
        var status = $rune.data('status');
        switch (status) {
            case 0: checkRune(rune.Id); break;
            case 1: uncheckRune(rune.Id); break;
            case 2: uncheckRuneWithConfirm(rune.Id); break;
            default: break;
        }
        renderRuneLink();
        renderCost();
    };

    var checkRune = function (runeId, noRecursion, isSaved) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if (disableEvo3 && $rune.data('rune').evo == 3) {
            return;
        }
        if (!noRecursion) {
            var path = Data.getPath(runeList.concat(runeCheckList), runeId);
            console.log("getPath", path);
            if (!path.length) {
                alert("无路径！")
                return;
            }
            _.each(path, function (o, i) {
                checkRune(o, true);
            });
        }
        else {
            if (isSaved) {
                $rune.data('status', 2)
                    .addClass('rune-saved');
            }
            else {
                $rune.data('status', 1)
                    .addClass('rune-checked');
                runeCheckList.push(runeId);
            }
        }
    };
    var uncheckRuneWithConfirm = function (runeId) {
        if (confirm("是否取消选中该符文？")) {
            uncheckRune(runeId);
        }
    };
    var uncheckRune = function (runeId, noRecursion) {
        if (runeId == 10000) {
            return;
        }
        var $rune = $("#rune" + runeId);
        if (disableEvo3 && $rune.data('rune').evo == 3) {
            return;
        }
        $rune.data('status', 0)
            .removeClass('rune-checked')
            .removeClass('rune-saved');
        runeList = _.without(runeList, runeId);
        runeCheckList = _.without(runeCheckList, runeId);
        if (!noRecursion) {
            var components = Data.getConnectedComponent(runeList.concat(runeCheckList));
            _.each(components, function (o, i) {
                if (_.contains(o, 10000) == false) {
                    _.each(o, function (p, j) {
                        uncheckRune(p, true);
                    });
                }
            });
        }
    };

    var save = function () {
        runeList = _.unique(runeList.concat(runeCheckList));
        runeCheckList = [];
        _.each(runeList, function (o, i) {
            var $rune = $("#rune" + o);
            $rune.data('status', 2)
                .removeClass('rune-checked')
                .addClass('rune-saved');
        });
        renderCost();

        var data = stringifyCondition(runeList);
        Backbone.history.navigate("class/" + classId + "/share/" + data, { trigger: false });
    };

    function stringifyCondition(condition) {
        return LZString.compressToEncodedURIComponent(JSON.stringify(condition));
    }

    function parseCondition(conditionJson) {
        return JSON.parse(LZString.decompressFromEncodedURIComponent(conditionJson));
    }

    return {
        initUiLanguage: initUiLanguage,
        getActiveMenu: getActiveMenu,
        setActiveMenu: setActiveMenu,
        init: init,
    };
});<|endoftext|>


<commit_before>var Immutable = require('immutable')
var toImmutable = require('./immutable-helpers').toImmutable
var hashCode = require('./hash-code')
var isEqual = require('./is-equal')
var getComputeFn = require('./getter').getComputeFn
var getDeps = require('./getter').getDeps
var isKeyPath = require('./key-path').isKeyPath
var isGetter = require('./getter').isGetter

// Keep track of whether we are currently executing a Getter's computeFn
var __applyingComputeFn = false;

class Evaluator {
  constructor() {
    /**
     * {
     *   <hashCode>: {
     *     stateHashCode: number,
     *     args: Immutable.List,
     *     value: any,
     *   }
     * }
     */
    this.__cachedGetters = Immutable.Map({})
  }

  /**
   * Takes either a KeyPath or Getter and evaluates
   *
   * KeyPath form:
   * ['foo', 'bar'] => state.getIn(['foo', 'bar'])
   *
   * Getter form:
   * [<KeyPath>, <KeyPath>, ..., <function>]
   *
   * @param {Immutable.Map} state
   * @param {string|array} getter
   * @return {any}
   */
  evaluate(state, keyPathOrGetter) {
    if (isKeyPath(keyPathOrGetter)) {
      // if its a keyPath simply return
      return state.getIn(keyPathOrGetter)
    } else if (!isGetter(keyPathOrGetter)) {
      throw new Error("evaluate must be passed a keyPath or Getter")
    }

    // Must be a Getter
    var code = hashCode(keyPathOrGetter)

    // if the value is cached for this dispatch cycle, return the cached value
    if (this.__isCached(state, keyPathOrGetter)) {
      // Cache hit
      return this.__cachedGetters.getIn([code, 'value'])

    }

    // evaluate dependencies
    var args = getDeps(keyPathOrGetter).map(dep => this.evaluate(state, dep))

    if (this.__hasStaleValue(state, keyPathOrGetter)) {
      // getter deps could still be unchanged since we only looked at the unwrapped (keypath, bottom level) deps
      var prevArgs = this.__cachedGetters.getIn([code, 'args'])

      // since Getter is a pure functions if the args are the same its a cache hit
      if (isEqual(prevArgs, args)) {
        var prevValue = this.__cachedGetters.getIn([code, 'value'])
        this.__cacheValue(state, keyPathOrGetter, prevArgs, prevValue)
        return prevValue
      }
    }

    // This indicates that we have called evaluate within the body of a computeFn.
    // Throw an error as this will lead to inconsistent caching
    if (__applyingComputeFn === true) {
      __applyingComputeFn = false
      throw new Error("Evaluate may not be called within a Getters computeFn")
    }

    __applyingComputeFn = true
    var evaluatedValue = getComputeFn(keyPathOrGetter).apply(null, args)
    __applyingComputeFn = false

    this.__cacheValue(state, keyPathOrGetter, args, evaluatedValue)

    return evaluatedValue
  }

  /**
   * @param {Immutable.Map} state
   * @param {Getter} getter
   */
  __hasStaleValue(state, getter) {
    var code = hashCode(getter)
    var cache = this.__cachedGetters
    return (
      cache.has(code) &&
      cache.getIn([code, 'stateHashCode']) !== state.hashCode()
    )
  }

  /**
   * Caches the value of a getter given state, getter, args, value
   * @param {Immutable.Map} state
   * @param {Getter} getter
   * @param {Array} args
   * @param {any} value
   */
  __cacheValue(state, getter, args, value) {
    var code = hashCode(getter)
    this.__cachedGetters = this.__cachedGetters.set(code, Immutable.Map({
      value: value,
      args: toImmutable(args),
      stateHashCode: state.hashCode(),
    }))
  }

  /**
   * Returns boolean whether the supplied getter is cached for a given state
   * @param {Immutable.Map} state
   * @param {Getter} getter
   * @return {boolean}
   */
  __isCached(state, getter) {
    var code = hashCode(getter)
    return (
      this.__cachedGetters.hasIn([code, 'value']) &&
      this.__cachedGetters.getIn([code, 'stateHashCode']) === state.hashCode()
    )
  }

  /**
   * Removes all caching about a getter
   * @param {Getter}
   */
  untrack(getter) {
    // TODO untrack all depedencies
  }

  reset() {
    this.__cachedGetters = Immutable.Map({})
  }
}

module.exports = Evaluator
<commit_msg>Fix evaluator's deps comparison: use Immutable val<commit_after>var Immutable = require('immutable')
var toImmutable = require('./immutable-helpers').toImmutable
var hashCode = require('./hash-code')
var isEqual = require('./is-equal')
var getComputeFn = require('./getter').getComputeFn
var getDeps = require('./getter').getDeps
var isKeyPath = require('./key-path').isKeyPath
var isGetter = require('./getter').isGetter

// Keep track of whether we are currently executing a Getter's computeFn
var __applyingComputeFn = false;

class Evaluator {
  constructor() {
    /**
     * {
     *   <hashCode>: {
     *     stateHashCode: number,
     *     args: Immutable.List,
     *     value: any,
     *   }
     * }
     */
    this.__cachedGetters = Immutable.Map({})
  }

  /**
   * Takes either a KeyPath or Getter and evaluates
   *
   * KeyPath form:
   * ['foo', 'bar'] => state.getIn(['foo', 'bar'])
   *
   * Getter form:
   * [<KeyPath>, <KeyPath>, ..., <function>]
   *
   * @param {Immutable.Map} state
   * @param {string|array} getter
   * @return {any}
   */
  evaluate(state, keyPathOrGetter) {
    if (isKeyPath(keyPathOrGetter)) {
      // if its a keyPath simply return
      return state.getIn(keyPathOrGetter)
    } else if (!isGetter(keyPathOrGetter)) {
      throw new Error("evaluate must be passed a keyPath or Getter")
    }

    // Must be a Getter
    var code = hashCode(keyPathOrGetter)

    // if the value is cached for this dispatch cycle, return the cached value
    if (this.__isCached(state, keyPathOrGetter)) {
      // Cache hit
      return this.__cachedGetters.getIn([code, 'value'])

    }

    // evaluate dependencies
    var args = getDeps(keyPathOrGetter).map(dep => this.evaluate(state, dep))

    if (this.__hasStaleValue(state, keyPathOrGetter)) {
      // getter deps could still be unchanged since we only looked at the unwrapped (keypath, bottom level) deps
      var prevArgs = this.__cachedGetters.getIn([code, 'args'])

      // since Getter is a pure functions if the args are the same its a cache hit
      if (isEqual(prevArgs, toImmutable(args))) {
        var prevValue = this.__cachedGetters.getIn([code, 'value'])
        this.__cacheValue(state, keyPathOrGetter, prevArgs, prevValue)
        return prevValue
      }
    }

    // This indicates that we have called evaluate within the body of a computeFn.
    // Throw an error as this will lead to inconsistent caching
    if (__applyingComputeFn === true) {
      __applyingComputeFn = false
      throw new Error("Evaluate may not be called within a Getters computeFn")
    }

    __applyingComputeFn = true
    var evaluatedValue = getComputeFn(keyPathOrGetter).apply(null, args)
    __applyingComputeFn = false

    this.__cacheValue(state, keyPathOrGetter, args, evaluatedValue)

    return evaluatedValue
  }

  /**
   * @param {Immutable.Map} state
   * @param {Getter} getter
   */
  __hasStaleValue(state, getter) {
    var code = hashCode(getter)
    var cache = this.__cachedGetters
    return (
      cache.has(code) &&
      cache.getIn([code, 'stateHashCode']) !== state.hashCode()
    )
  }

  /**
   * Caches the value of a getter given state, getter, args, value
   * @param {Immutable.Map} state
   * @param {Getter} getter
   * @param {Array} args
   * @param {any} value
   */
  __cacheValue(state, getter, args, value) {
    var code = hashCode(getter)
    this.__cachedGetters = this.__cachedGetters.set(code, Immutable.Map({
      value: value,
      args: toImmutable(args),
      stateHashCode: state.hashCode(),
    }))
  }

  /**
   * Returns boolean whether the supplied getter is cached for a given state
   * @param {Immutable.Map} state
   * @param {Getter} getter
   * @return {boolean}
   */
  __isCached(state, getter) {
    var code = hashCode(getter)
    return (
      this.__cachedGetters.hasIn([code, 'value']) &&
      this.__cachedGetters.getIn([code, 'stateHashCode']) === state.hashCode()
    )
  }

  /**
   * Removes all caching about a getter
   * @param {Getter}
   */
  untrack(getter) {
    // TODO untrack all depedencies
  }

  reset() {
    this.__cachedGetters = Immutable.Map({})
  }
}

module.exports = Evaluator
<|endoftext|>


<commit_before><commit_msg>remove newlines from text output<commit_after><|endoftext|>


<commit_before><commit_msg>Simplicy `Calc.compareTypes()`<commit_after><|endoftext|>