<commit_before>
function showHide(elementid){
if (document.getElementById(elementid).style.display == 'none'){
document.getElementById(elementid).style.display = '';
} else {
document.getElementById(elementid).style.display = 'none';
}
}

function onCoordinatorChange()
{
	var submittedForValue = document.forms[0].submittedFor.value;
	var action = "Site.do?"+"operation="+document.forms[0].operation.value+"&pageOf=pageOfSite&isOnChange=true&coordinatorId="+document.getElementById("coordinatorId").value+"&submittedFor="+submittedForValue;
	document.forms[0].action = action;
	document.forms[0].submit();
}

function enableLastCheckbox()
{
	var lastRowNo = document.forms[0].counter.value;
	var chkBox = document.getElementById("chk_"+lastRowNo);
	if(lastRowNo>1)
		chkBox.disabled = false;
}

function enablePreviousCheckBox(element)
{
   	var elementName = element.name;
   	var index = elementName.indexOf('_');
   	var previousRowNo = parseInt(elementName.substring(index+1))-1;
    if (element.checked == true)
    {
      	if(previousRowNo > 1)
      	{
			var previousElement = document.getElementById("chk_"+previousRowNo);
			previousElement.disabled = false;
		}
    }
    else if(element.checked == false)
    {
      	for(var i=previousRowNo;i>=1;i--)
      	{
			var previousElement = document.getElementById("chk_"+i);
			previousElement.checked = false;
			previousElement.disabled = true;
		}
	}
}

function changeMenuStyle(obj, new_style) {
if (objclick != obj)
  obj.className = new_style;
}

function showCursor(){
	document.body.style.cursor='hand';
}

function hideCursor(){
	document.body.style.cursor='default';
}

function waitCursor(){
	document.body.style.cursor='wait';
}

function confirmDelete(){
  if (confirm('Are you sure you want to delete?'))
  {
    return true;
  }
  else
  {
    return false;
  }
}

function setFormAction(formAction)
{
	document.forms[0].action=formAction;
}

function setOperation(operation)
{
	document.forms[0].operation.value=operation;
}

function enableAll()
{
	document.forms[0].loginName.disabled="false";
}

function CheckAll(chk)
{
	for (var i=0;i < document.forms[0].elements.length;i++)
    {
    	var e = document.forms[0].elements[i];
        if (e.type == "checkbox")
        {
        	e.checked = chk.checked;
        }
    }
}

function showdatecontrol(strFormname,strElementName,strElementName2)
{
	var calWnd=window.open("cal.asp?WCI=cal&caltype=0&formname="+strFormname+
						   "&elementname="+strElementName+"&elementname2="+
						   strElementName2,"strFormname","toolbar=no,location=no,directories=no,status=yes,width="+
						   screen.availWidth/4.2 +",height="+ screen.availHeight/2.8+
						   ",menubar=no,scrollbars=no,top=0,left=0, resizable=no, border=thin");
}

function send(pageNum,numResultsPerPage,prevPage,pageName)
{
	document.forms[0].action = pageName+'?pageNum='+pageNum+'&numResultsPerPage='+numResultsPerPage;
	document.forms[0].submit();
}

function changeRecordPerPage(pageNum,element,pageName)
{
	document.forms[0].action = pageName+'?pageNum=1&numResultsPerPage='+element.value;
	document.forms[0].submit();
}

// function for mouse click
var objclick;
function changeMenuSelected(obj, new_style) {

	objclick = obj;
	window.location.reload
  obj.className = new_style;
  obj.onmouseout="";
}

function changeUrl(element,str)
{
			var redirectTo1 = "redirectTo=" + str;

			var redirectTo = replaceAll("&","_",redirectTo1);
			var url = element.href + "&" + redirectTo;
			//alert(redirectTo);
			//alert(url);
			element.href = url;
}

		function replaceAll(oldStr,newStr,fromStr)
		{
			var i = fromStr.indexOf(oldStr);
			while(i != -1)
			{
				var s = fromStr.replace(oldStr,newStr);
				fromStr = s;
				i = fromStr.indexOf(oldStr);
			}
			return fromStr;
		}

		function getURL(str)
		{
			var ind = str.lastIndexOf("/");
			var s = str.substring(ind);
			return s;
		}

		function checkActivityStatus(element,url)
		{
		  var str;
		  if (element.type!=null && element.type == "text") {
		      str = element.value;
		  }
		   else
		   {
		       str = element.options[element.selectedIndex].text;
	       }
			if(str == "Disabled")
			{
				document.forms[0].onSubmit.value=url;
			}
		}

		function changeSubmitTo(url)
		{
			var str = document.forms[0].onSubmit.value;
	//		alert(str);
			if(str == null || str == "")
			{
				document.forms[0].onSubmit.value=url;
			}
		}

		var win = null;
		function StorageMapWindow(mypage,myname,w,h,scroll)
		{
			LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
			TopPosition = (screen.height) ? (screen.height-h)/2 : 0;

			// Sri: Added position one and two as parameters
            // with format positionOne:positionTwo
			mypage=mypage+document.forms[0].typeId.value +
					"&storageToBeSelected="+ document.forms[0].customListBox_1_0.value +  //parentContainerId.value +
					"&position=" + document.forms[0].customListBox_1_1.value +   //positionDimensionOne.value +
					":" + document.forms[0].customListBox_1_2.value;

		   var storageContainer = document.getElementById('selectedContainerName').value;
		   mypage+="&storageContainerName="+storageContainer;
					// alert(mypage);
			settings =
				'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
			win = open(mypage,myname,settings)
			if (win.opener == null)
				win.opener = self;
		}

		function NewWindow(mypage,myname,w,h,scroll)
		{
			LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
			TopPosition = (screen.height) ? (screen.height-h)/2 : 0;

			settings =
				'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
			win = open(mypage,myname,settings)
			if (win.opener == null)
				win.opener = self;
		}

//This function submits JSP page to AddNewAction with passed action
function addNewAction(action)
{
	var action = action;

	document.forms[0].action = action;

	document.forms[0].submit();
}

//This function sets value of submittedFor attribute of JSP form object
function setSubmittedFor(submittedFor,forwardTo)
{
	document.forms[0].submittedFor.value = submittedFor;
	document.forms[0].forwardTo.value    = forwardTo;
}
//Falguni
//This function sets value of submittedFor Print attribute of JSP form object
function setSubmittedForPrint(submittedFor,forwardTo,nextForwardTo)
{

	document.forms[0].submittedFor.value = submittedFor;
	document.forms[0].forwardTo.value    = forwardTo;
	document.forms[0].nextForwardTo.value   = nextForwardTo;

}

//this function is used in Specimen and Events page for non functional tabs
function featureNotSupported()
{
	alert("This feature is not supported in version 1.2 and will be supported in the next release of caTissue.");
}

function validateAny(element)
{

	var len = element.length;
	var anySelected=false;
	if(len>0 && element[0].selected)
	{
		anySelected=true;

	}
	for (var i = 1; i < len; i++)
	{

		if (element[i].selected && anySelected==true)
		{
			return false;
		}
	}
	return true;
}
// Name : Prafull_kadam
// Bug ID: 3624
// Patch ID: 3624_2
// Description: Added code to handle hyperlinks String sorting in dhtml grid.

// TO check whether the given String is Hyperlink or not.
function isHyperLink(str)
{
	 var reg = new RegExp("^<[aA][ ].*</[aA]>$");
	 return reg.test(str);
}
// TO get the Lable of the Hyperlink for the given hyperlink string, returns same string if its not hyperlink.
function getHyperlinkLable(link)
{
	if (isHyperLink(link)==true)
	{
		var index = link.indexOf('>');
		var lastIndex = link.lastIndexOf('</');
		link = link.substring(index+1, lastIndex);
	}
	return link;
}

// methods of simple query interface
function onObjectChange(element,action)
{
	var index = element.name.indexOf("(");
	var lastIndex = element.name.lastIndexOf(")");

	var saveObject = document.getElementById("objectChanged");
	saveObject.value = element.name.substring(index+1,lastIndex);

	callSerachAction(action);
}

function setPropertyValue(propertyName, value)
{
	for (var i=0;i < document.forms[0].elements.length;i++)
    {
    	var e = document.forms[0].elements[i];
        if (e.name == propertyName)
        {
        	document.forms[0].elements[i].value = value;
		}
    }
}

function callSerachAction(action)
{
	document.forms[0].action = action;
	document.forms[0].submit();
}

function incrementCounter()
{
	document.forms[0].counter.value = parseInt(document.forms[0].counter.value) + 1;
}
function decrementCounter()
{
	document.forms[0].counter.value = parseInt(document.forms[0].counter.value) - 1;
}
<commit_msg>showHide method is changed.<commit_after>
function showHide(elementid)
{
	var switchImg = document.getElementById('imgArrow_'+elementid);
	if (document.getElementById(elementid).style.display == 'none'){
		document.getElementById(elementid).style.display = '';
		switchImg.innerHTML = '';

	} else {
		document.getElementById(elementid).style.display = 'none';
		switchImg.innerHTML = '';

	}
}

function onCoordinatorChange()
{
	var submittedForValue = document.forms[0].submittedFor.value;
	var action = "Site.do?"+"operation="+document.forms[0].operation.value+"&pageOf=pageOfSite&isOnChange=true&coordinatorId="+document.getElementById("coordinatorId").value+"&submittedFor="+submittedForValue;
	document.forms[0].action = action;
	document.forms[0].submit();
}

function enableLastCheckbox()
{
	var lastRowNo = document.forms[0].counter.value;
	var chkBox = document.getElementById("chk_"+lastRowNo);
	if(lastRowNo>1)
		chkBox.disabled = false;
}

function enablePreviousCheckBox(element)
{
   	var elementName = element.name;
   	var index = elementName.indexOf('_');
   	var previousRowNo = parseInt(elementName.substring(index+1))-1;
    if (element.checked == true)
    {
      	if(previousRowNo > 1)
      	{
			var previousElement = document.getElementById("chk_"+previousRowNo);
			previousElement.disabled = false;
		}
    }
    else if(element.checked == false)
    {
      	for(var i=previousRowNo;i>=1;i--)
      	{
			var previousElement = document.getElementById("chk_"+i);
			previousElement.checked = false;
			previousElement.disabled = true;
		}
	}
}

function changeMenuStyle(obj, new_style) {
if (objclick != obj)
  obj.className = new_style;
}

function showCursor(){
	document.body.style.cursor='hand';
}

function hideCursor(){
	document.body.style.cursor='default';
}

function waitCursor(){
	document.body.style.cursor='wait';
}

function confirmDelete(){
  if (confirm('Are you sure you want to delete?'))
  {
    return true;
  }
  else
  {
    return false;
  }
}

function setFormAction(formAction)
{
	document.forms[0].action=formAction;
}

function setOperation(operation)
{
	document.forms[0].operation.value=operation;
}

function enableAll()
{
	document.forms[0].loginName.disabled="false";
}

function CheckAll(chk)
{
	for (var i=0;i < document.forms[0].elements.length;i++)
    {
    	var e = document.forms[0].elements[i];
        if (e.type == "checkbox")
        {
        	e.checked = chk.checked;
        }
    }
}

function showdatecontrol(strFormname,strElementName,strElementName2)
{
	var calWnd=window.open("cal.asp?WCI=cal&caltype=0&formname="+strFormname+
						   "&elementname="+strElementName+"&elementname2="+
						   strElementName2,"strFormname","toolbar=no,location=no,directories=no,status=yes,width="+
						   screen.availWidth/4.2 +",height="+ screen.availHeight/2.8+
						   ",menubar=no,scrollbars=no,top=0,left=0, resizable=no, border=thin");
}

function send(pageNum,numResultsPerPage,prevPage,pageName)
{
	document.forms[0].action = pageName+'?pageNum='+pageNum+'&numResultsPerPage='+numResultsPerPage;
	document.forms[0].submit();
}

function changeRecordPerPage(pageNum,element,pageName)
{
	document.forms[0].action = pageName+'?pageNum=1&numResultsPerPage='+element.value;
	document.forms[0].submit();
}

// function for mouse click
var objclick;
function changeMenuSelected(obj, new_style) {

	objclick = obj;
	window.location.reload
  obj.className = new_style;
  obj.onmouseout="";
}

function changeUrl(element,str)
{
			var redirectTo1 = "redirectTo=" + str;

			var redirectTo = replaceAll("&","_",redirectTo1);
			var url = element.href + "&" + redirectTo;
			//alert(redirectTo);
			//alert(url);
			element.href = url;
}

		function replaceAll(oldStr,newStr,fromStr)
		{
			var i = fromStr.indexOf(oldStr);
			while(i != -1)
			{
				var s = fromStr.replace(oldStr,newStr);
				fromStr = s;
				i = fromStr.indexOf(oldStr);
			}
			return fromStr;
		}

		function getURL(str)
		{
			var ind = str.lastIndexOf("/");
			var s = str.substring(ind);
			return s;
		}

		function checkActivityStatus(element,url)
		{
		  var str;
		  if (element.type!=null && element.type == "text") {
		      str = element.value;
		  }
		   else
		   {
		       str = element.options[element.selectedIndex].text;
	       }
			if(str == "Disabled")
			{
				document.forms[0].onSubmit.value=url;
			}
		}

		function changeSubmitTo(url)
		{
			var str = document.forms[0].onSubmit.value;
	//		alert(str);
			if(str == null || str == "")
			{
				document.forms[0].onSubmit.value=url;
			}
		}

		var win = null;
		function StorageMapWindow(mypage,myname,w,h,scroll)
		{
			LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
			TopPosition = (screen.height) ? (screen.height-h)/2 : 0;

			// Sri: Added position one and two as parameters
            // with format positionOne:positionTwo
			mypage=mypage+document.forms[0].typeId.value +
					"&storageToBeSelected="+ document.forms[0].customListBox_1_0.value +  //parentContainerId.value +
					"&position=" + document.forms[0].customListBox_1_1.value +   //positionDimensionOne.value +
					":" + document.forms[0].customListBox_1_2.value;

		   var storageContainer = document.getElementById('selectedContainerName').value;
		   mypage+="&storageContainerName="+storageContainer;
					// alert(mypage);
			settings =
				'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
			win = open(mypage,myname,settings)
			if (win.opener == null)
				win.opener = self;
		}

		function NewWindow(mypage,myname,w,h,scroll)
		{
			LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
			TopPosition = (screen.height) ? (screen.height-h)/2 : 0;

			settings =
				'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
			win = open(mypage,myname,settings)
			if (win.opener == null)
				win.opener = self;
		}

//This function submits JSP page to AddNewAction with passed action
function addNewAction(action)
{
	var action = action;

	document.forms[0].action = action;

	document.forms[0].submit();
}

//This function sets value of submittedFor attribute of JSP form object
function setSubmittedFor(submittedFor,forwardTo)
{
	document.forms[0].submittedFor.value = submittedFor;
	document.forms[0].forwardTo.value    = forwardTo;
}
//Falguni
//This function sets value of submittedFor Print attribute of JSP form object
function setSubmittedForPrint(submittedFor,forwardTo,nextForwardTo)
{

	document.forms[0].submittedFor.value = submittedFor;
	document.forms[0].forwardTo.value    = forwardTo;
	document.forms[0].nextForwardTo.value   = nextForwardTo;

}

//this function is used in Specimen and Events page for non functional tabs
function featureNotSupported()
{
	alert("This feature is not supported in version 1.2 and will be supported in the next release of caTissue.");
}

function validateAny(element)
{

	var len = element.length;
	var anySelected=false;
	if(len>0 && element[0].selected)
	{
		anySelected=true;

	}
	for (var i = 1; i < len; i++)
	{

		if (element[i].selected && anySelected==true)
		{
			return false;
		}
	}
	return true;
}
// Name : Prafull_kadam
// Bug ID: 3624
// Patch ID: 3624_2
// Description: Added code to handle hyperlinks String sorting in dhtml grid.

// TO check whether the given String is Hyperlink or not.
function isHyperLink(str)
{
	 var reg = new RegExp("^<[aA][ ].*</[aA]>$");
	 return reg.test(str);
}
// TO get the Lable of the Hyperlink for the given hyperlink string, returns same string if its not hyperlink.
function getHyperlinkLable(link)
{
	if (isHyperLink(link)==true)
	{
		var index = link.indexOf('>');
		var lastIndex = link.lastIndexOf('</');
		link = link.substring(index+1, lastIndex);
	}
	return link;
}

// methods of simple query interface
function onObjectChange(element,action)
{
	var index = element.name.indexOf("(");
	var lastIndex = element.name.lastIndexOf(")");

	var saveObject = document.getElementById("objectChanged");
	saveObject.value = element.name.substring(index+1,lastIndex);

	callSerachAction(action);
}

function setPropertyValue(propertyName, value)
{
	for (var i=0;i < document.forms[0].elements.length;i++)
    {
    	var e = document.forms[0].elements[i];
        if (e.name == propertyName)
        {
        	document.forms[0].elements[i].value = value;
		}
    }
}

function callSerachAction(action)
{
	document.forms[0].action = action;
	document.forms[0].submit();
}

function incrementCounter()
{
	document.forms[0].counter.value = parseInt(document.forms[0].counter.value) + 1;
}
function decrementCounter()
{
	document.forms[0].counter.value = parseInt(document.forms[0].counter.value) - 1;
}
<|endoftext|>


<commit_before>var VARS_FIELD = typeof Symbol === 'undefined' ? '__vars' + Date.now() : Symbol('vars');
var SUBSCRIPTIONS_FIELD = typeof Symbol === 'undefined' ? '__subs' + Date.now() : Symbol('subscriptions');

function BaseClass() {
  this[VARS_FIELD] = {};
  this[SUBSCRIPTIONS_FIELD] = {};
  this.errorHandler = this.errorHandler.bind(this);

  Object.defineProperty(this, 'hashCode', {
    value: Math.floor(Date.now() * Math.random())
  });
}

BaseClass.prototype = {
  empty: function () {
    var vars = this[VARS_FIELD];

    Object.keys(vars).forEach(function (name) {
      vars[name] = null;
      delete vars[name];
    });
  },

  get: function (key) {
    return this[VARS_FIELD].hasOwnProperty(key) ? this[VARS_FIELD][key] : undefined;
  },

  set: function (key, value, noNotify) {
    var prev = this.get(key);

    this[VARS_FIELD][key] = value;

    if (!noNotify && prev !== value) {
      this.trigger(key + '_changed', prev, value, key);
    }

    return this;
  },

  bindTo: function (key, target, targetKey, noNotify) {
    targetKey = targetKey || key;

    // If `noNotify` is true, prevent `(targetKey)_changed` event occurrs,
    // when bind the value for the first time only.
    // (Same behaviour as Google Maps JavaScript v3)
    target.set(targetKey, target.get(targetKey), noNotify);

    this.on(key + '_changed', function (oldValue, value) {
      target.set(targetKey, value);
    });
  },

  trigger: function (eventName) {
    if (!eventName) {
      return this;
    }

    if (!this[SUBSCRIPTIONS_FIELD][eventName]) {
      return this;
    }

    var listeners = this[SUBSCRIPTIONS_FIELD][eventName];
    var i = listeners.length;
    var args = Array.prototype.slice.call(arguments, 1);
    listeners[i] = listeners[i].filter(function(listener) {
      return !!listener;
    });

    while (i--) {
      listeners[i].apply(this, args);
    }

    return this;
  },

  on: function (eventName, listener) {
    if (!listener || typeof listener !== "function") {
      throw Error('Listener for on()/addEventListener() method is not a function');
    }
    var topic;
    this[SUBSCRIPTIONS_FIELD][eventName] = this[SUBSCRIPTIONS_FIELD][eventName] || [];
    topic = this[SUBSCRIPTIONS_FIELD][eventName];
    topic.push(listener);
    return this;
  },

  off: function (eventName, listener) {
    if (!eventName && !listener) {
      this[SUBSCRIPTIONS_FIELD] = {};
      return this;
    }

    if (eventName && !listener) {
      this[SUBSCRIPTIONS_FIELD][eventName] = null;
    } else if (this[SUBSCRIPTIONS_FIELD][eventName]) {
      var index = this[SUBSCRIPTIONS_FIELD][eventName].indexOf(listener);

      if (index !== -1) {
        this[SUBSCRIPTIONS_FIELD][eventName].splice(index, 1);
      }
    }

    return this;
  },

  one: function (eventName, listener) {
    if (!listener || typeof listener !== "function") {
      throw Error('Listener for one()/addEventListenerOnce() method is not a function');
    }

    var self = this;

    var callback = function () {
      self.off(eventName, arguments.callee);
      listener.apply(self, arguments);
      callback = undefined;
    };
    this.on(eventName, callback);

    return this;
  },

  destroy: function () {
    this.off();
    this.empty();
  },

  errorHandler: function (error) {
    if (error) {
      if (typeof console.error === "function") {
        if (this.id) {
          console.error(this.id, error);
        } else {
          console.error(error);
        }
      } else {
        if (this.id) {
          console.log(this.id, error);
        } else {
          console.log(error);
        }
      }
      this.trigger('error', error instanceof Error ? error : createError(error));
    }

    return false;
  }
};

BaseClass.prototype.addEventListener = BaseClass.prototype.on;
BaseClass.prototype.addEventListenerOnce = BaseClass.prototype.one;
BaseClass.prototype.removeEventListener = BaseClass.prototype.off;

function createError(message, methodName, args) {
  var error = new Error(methodName ? [
    'Got error with message: "', message, '" ',
    'after calling "', methodName, '"'
  ].join('') : message);

  Object.defineProperties(error, {
    methodName: {
      value: methodName
    },
    args: {
      value: args
    }
  });

  return error;
}

module.exports = BaseClass;
<commit_msg>Update BaseClass.js<commit_after>var VARS_FIELD = typeof Symbol === 'undefined' ? '__vars' + Date.now() : Symbol('vars');
var SUBSCRIPTIONS_FIELD = typeof Symbol === 'undefined' ? '__subs' + Date.now() : Symbol('subscriptions');

function BaseClass() {
  this[VARS_FIELD] = {};
  this[SUBSCRIPTIONS_FIELD] = {};
  this.errorHandler = this.errorHandler.bind(this);

  Object.defineProperty(this, 'hashCode', {
    value: Math.floor(Date.now() * Math.random())
  });
}

BaseClass.prototype = {
  empty: function () {
    var vars = this[VARS_FIELD];

    Object.keys(vars).forEach(function (name) {
      vars[name] = null;
      delete vars[name];
    });
  },

  get: function (key) {
    return this[VARS_FIELD].hasOwnProperty(key) ? this[VARS_FIELD][key] : undefined;
  },

  set: function (key, value, noNotify) {
    var prev = this.get(key);

    this[VARS_FIELD][key] = value;

    if (!noNotify && prev !== value) {
      this.trigger(key + '_changed', prev, value, key);
    }

    return this;
  },

  bindTo: function (key, target, targetKey, noNotify) {
    targetKey = targetKey || key;

    // If `noNotify` is true, prevent `(targetKey)_changed` event occurrs,
    // when bind the value for the first time only.
    // (Same behaviour as Google Maps JavaScript v3)
    target.set(targetKey, target.get(targetKey), noNotify);

    this.on(key + '_changed', function (oldValue, value) {
      target.set(targetKey, value);
    });
  },

  trigger: function (eventName) {
    if (!eventName) {
      return this;
    }

    if (!this[SUBSCRIPTIONS_FIELD][eventName]) {
      return this;
    }

    var listeners = this[SUBSCRIPTIONS_FIELD][eventName];
    var i = listeners.length;
    var args = Array.prototype.slice.call(arguments, 1);
    listeners = listeners.filter(function(listener) {
      return !!listener;
    });

    while (i--) {
      listeners[i].apply(this, args);
    }

    return this;
  },

  on: function (eventName, listener) {
    if (!listener || typeof listener !== "function") {
      throw Error('Listener for on()/addEventListener() method is not a function');
    }
    var topic;
    this[SUBSCRIPTIONS_FIELD][eventName] = this[SUBSCRIPTIONS_FIELD][eventName] || [];
    topic = this[SUBSCRIPTIONS_FIELD][eventName];
    topic.push(listener);
    return this;
  },

  off: function (eventName, listener) {
    if (!eventName && !listener) {
      this[SUBSCRIPTIONS_FIELD] = {};
      return this;
    }

    if (eventName && !listener) {
      this[SUBSCRIPTIONS_FIELD][eventName] = null;
    } else if (this[SUBSCRIPTIONS_FIELD][eventName]) {
      var index = this[SUBSCRIPTIONS_FIELD][eventName].indexOf(listener);

      if (index !== -1) {
        this[SUBSCRIPTIONS_FIELD][eventName].splice(index, 1);
      }
    }

    return this;
  },

  one: function (eventName, listener) {
    if (!listener || typeof listener !== "function") {
      throw Error('Listener for one()/addEventListenerOnce() method is not a function');
    }

    var self = this;

    var callback = function () {
      self.off(eventName, arguments.callee);
      listener.apply(self, arguments);
      callback = undefined;
    };
    this.on(eventName, callback);

    return this;
  },

  destroy: function () {
    this.off();
    this.empty();
  },

  errorHandler: function (error) {
    if (error) {
      if (typeof console.error === "function") {
        if (this.id) {
          console.error(this.id, error);
        } else {
          console.error(error);
        }
      } else {
        if (this.id) {
          console.log(this.id, error);
        } else {
          console.log(error);
        }
      }
      this.trigger('error', error instanceof Error ? error : createError(error));
    }

    return false;
  }
};

BaseClass.prototype.addEventListener = BaseClass.prototype.on;
BaseClass.prototype.addEventListenerOnce = BaseClass.prototype.one;
BaseClass.prototype.removeEventListener = BaseClass.prototype.off;

function createError(message, methodName, args) {
  var error = new Error(methodName ? [
    'Got error with message: "', message, '" ',
    'after calling "', methodName, '"'
  ].join('') : message);

  Object.defineProperties(error, {
    methodName: {
      value: methodName
    },
    args: {
      value: args
    }
  });

  return error;
}

module.exports = BaseClass;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugflow may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Export('bugflow.ForInSeries')

//@Require('Class')
//@Require('Obj')
//@Require('bugflow.IteratorFlow')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var Class                       = bugpack.require('Class');
    var Obj                         = bugpack.require('Obj');
    var IteratorFlow                = bugpack.require('bugflow.IteratorFlow');

    //-------------------------------------------------------------------------------
    // Declare Class
    //-------------------------------------------------------------------------------

    /**
     * @class
     * @extends {IteratorFlow}
     */
    var ForInSeries = Class.extend(IteratorFlow, {

        _name: "bugflow.ForInSeries",

        //-------------------------------------------------------------------------------
        // Constructor
        //-------------------------------------------------------------------------------

        /**
         * @constructs
         * @param {*} data
         * @param {function(Flow, *)} iteratorMethod
         */
        _constructor: function(data, iteratorMethod) {

            this._super(data, iteratorMethod);

            //-------------------------------------------------------------------------------
            // Private Properties
            //-------------------------------------------------------------------------------

            // NOTE BRN: Because JS does not have an iterator implementation, we have to create a copy of the properties
            // here and use the array as our way of iterating through the properties.

            /**
             * @private
             * @type {Array.<string>}
             */
            this.dataProperties     = Obj.getProperties(data);

            /**
             * @private
             * @type {number}
             */
            this.iteratorIndex      = -1;
        },

        //-------------------------------------------------------------------------------
        // Flow Methods
        //-------------------------------------------------------------------------------

        /**
         * @param {Array<*>} args
         */
        executeFlow: function(args) {
            this._super(args);
            if (this.dataProperties.length > 0) {
                this.next();
            } else {
                this.complete();
            }
        },

        //-------------------------------------------------------------------------------
        // IteratorFlow Methods
        //-------------------------------------------------------------------------------

        /**
         * @protected
         * @param {Array.<*>} args
         * @param {Throwable} throwable
         */
        iterationCallback: function(args, throwable) {
            if (throwable) {
                if (!this.hasErrored()) {
                    this.error(throwable);
                }
            } else {
                if (this.iteratorIndex >= (this.dataProperties.length - 1)) {
                    this.complete();
                } else {
                    this.next();
                }
            }
        },

        //-------------------------------------------------------------------------------
        // Private Methods
        //-------------------------------------------------------------------------------

        /**
         * @private
         */
        next: function() {
            this.iteratorIndex++;
            var nextProperty    = this.dataProperties[this.iteratorIndex];
            var nextValue       = this.getData()[nextProperty];
            this.executeIteration([nextValue, nextProperty]);
        }
    });

    //-------------------------------------------------------------------------------
    // Export
    //-------------------------------------------------------------------------------

    bugpack.export('bugflow.ForInSeries', ForInSeries);
});
<commit_msg>Fix small issue with ForInSeries<commit_after>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugflow may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------

//@Export('bugflow.ForInSeries')

//@Require('Class')
//@Require('Obj')
//@Require('bugflow.IteratorFlow')

//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------

require('bugpack').context("*", function(bugpack) {

    //-------------------------------------------------------------------------------
    // BugPack
    //-------------------------------------------------------------------------------

    var Class                       = bugpack.require('Class');
    var Obj                         = bugpack.require('Obj');
    var IteratorFlow                = bugpack.require('bugflow.IteratorFlow');

    //-------------------------------------------------------------------------------
    // Declare Class
    //-------------------------------------------------------------------------------

    /**
     * @class
     * @extends {IteratorFlow}
     */
    var ForInSeries = Class.extend(IteratorFlow, {

        _name: "bugflow.ForInSeries",

        //-------------------------------------------------------------------------------
        // Constructor
        //-------------------------------------------------------------------------------

        /**
         * @constructs
         * @param {*} data
         * @param {function(Flow, *)} iteratorMethod
         */
        _constructor: function(data, iteratorMethod) {

            this._super(data, iteratorMethod);

            //-------------------------------------------------------------------------------
            // Private Properties
            //-------------------------------------------------------------------------------

            // NOTE BRN: Because JS does not have an iterator implementation, we have to create a copy of the properties
            // here and use the array as our way of iterating through the properties.

            /**
             * @private
             * @type {Array.<string>}
             */
            this.dataProperties     = Obj.getProperties(data);

            /**
             * @private
             * @type {number}
             */
            this.iteratorIndex      = -1;
        },

        //-------------------------------------------------------------------------------
        // Flow Methods
        //-------------------------------------------------------------------------------

        /**
         * @param {Array<*>} args
         */
        executeFlow: function(args) {
            this._super(args);
            if (this.dataProperties.length > 0) {
                this.next();
            } else {
                this.complete();
            }
        },

        //-------------------------------------------------------------------------------
        // IteratorFlow Methods
        //-------------------------------------------------------------------------------

        /**
         * @protected
         * @param {Array.<*>} args
         * @param {Throwable} throwable
         */
        iterationCallback: function(args, throwable) {
            if (throwable) {
                if (!this.hasErrored()) {
                    this.error(throwable);
                }
            } else {
                if (this.iteratorIndex >= (this.dataProperties.length - 1)) {
                    this.complete();
                } else {
                    this.next();
                }
            }
        },

        //-------------------------------------------------------------------------------
        // Private Methods
        //-------------------------------------------------------------------------------

        /**
         * @private
         */
        next: function() {
            this.iteratorIndex++;
            var nextProperty    = this.dataProperties[this.iteratorIndex];
            var nextValue       = this.getData()[nextProperty];
            this.executeIteration([nextProperty, nextValue]);
        }
    });

    //-------------------------------------------------------------------------------
    // Export
    //-------------------------------------------------------------------------------

    bugpack.export('bugflow.ForInSeries', ForInSeries);
});
<|endoftext|>


<commit_before>/******
* !! WARNING: This is a generated file !!
*
* PLEASE DO NOT MODIFY DIRECTLY
*
* => Changes should be done on file 'app/config.json'.
******/

angular.module("cesium.config", [])

.constant("csConfig", {
	"cacheTimeMs": 60000,
	"fallbackLanguage": "en",
	"rememberMe": false,
	"showUDHistory": false,
	"timeout": 10000,
	"timeWarningExpireMembership": 5184000,
	"timeWarningExpire": 7776000,
	"useLocalStorage": true,
	"useRelative": true,
	"initPhase": false,
	"expertMode": false,
	"decimalCount": 4,
	"helptip": {
		"enable": true,
		"installDocUrl": "https://github.com/duniter/duniter/blob/master/doc/install-a-node.md"
	},
	"node": {
		"host": "gtest.duniter.org",
		"port": "10900"
	},
	"plugins": {
		"es": {
			"enable": true,
			"askEnable": false,
			"host": "data.gtest.duniter.fr",
			"port": "80",
			"notifications": {
				"txSent": true,
				"txReceived": true,
				"certSent": true,
				"certReceived": true
			}
		}
	},
	"version": "0.9.17",
	"build": "2017-01-30T15:23:45.911Z",
	"newIssueUrl": "https://github.com/duniter/cesium/issues/new?labels=bug"
})

;<commit_msg>v0.9.17<commit_after>/******
* !! WARNING: This is a generated file !!
*
* PLEASE DO NOT MODIFY DIRECTLY
*
* => Changes should be done on file 'app/config.json'.
******/

angular.module("cesium.config", [])

.constant("csConfig", {
	"cacheTimeMs": 60000,
	"fallbackLanguage": "en",
	"rememberMe": false,
	"showUDHistory": false,
	"timeout": 10000,
	"timeWarningExpireMembership": 5184000,
	"timeWarningExpire": 7776000,
	"useLocalStorage": true,
	"useRelative": true,
	"initPhase": false,
	"expertMode": false,
	"decimalCount": 4,
	"helptip": {
		"enable": true,
		"installDocUrl": "https://github.com/duniter/duniter/blob/master/doc/install-a-node.md"
	},
	"node": {
		"host": "gtest.duniter.org",
		"port": "10900"
	},
	"plugins": {
		"es": {
			"enable": true,
			"askEnable": false,
			"host": "data.gtest.duniter.fr",
			"port": "80",
			"notifications": {
				"txSent": true,
				"txReceived": true,
				"certSent": true,
				"certReceived": true
			}
		}
	},
	"version": "0.9.17",
	"build": "2017-01-30T15:53:57.065Z",
	"newIssueUrl": "https://github.com/duniter/cesium/issues/new?labels=bug"
})

;<|endoftext|>


<commit_before>/******
* !! WARNING: This is a generated file !!
*
* PLEASE DO NOT MODIFY DIRECTLY
*
* => Changes should be done on file 'app/config.json'.
******/

angular.module("cesium.config", [])

.constant("csConfig", {
	"fallbackLanguage": "fr-FR",
	"defaultLanguage": "fr-FR",
	"timeout": 300000,
	"cacheTimeMs": 300000,
	"useLocalStorage": true,
	"rememberMe": true,
	"useRelative": false,
	"decimalCount": 2,
	"shareBaseUrl": "https://gchange.fr",
	"helptip": {
		"enable": false
	},
	"feed": {
		"jsonFeed": {
			"fr-FR": "https://raw.githubusercontent.com/duniter-gchange/gchange-client/master/doc/feed/feed-fr.json",
			"en": "https://raw.githubusercontent.com/duniter-gchange/gchange-client/master/doc/feed/feed-en.json"
		},
		"maxContentLength": 1300
	},
	"node": {
		"host": "data.gchange.fr",
		"port": "443"
	},
	"fallbackNodes": [
		{
			"host": "data.gchange.fr",
			"port": "443"
		},
		{
			"host": "gchange.data.presles.fr",
			"port": "443"
		}
	],
	"share": {
		"mastodonAuthor": "@gchange@framapiaf.org"
	},
	"plugins": {
		"es": {
			"enable": true,
			"maxUploadBodySize": 5242880,
			"defaultCountry": "France"
		},
		"market": {
			"enable": true,
			"defaultSearch": {
				"geoDistance": "50"
			},
			"cesiumApi": {
				"enable": true,
				"baseUrl": "https://demo.cesium.app/api"
			}
		},
		"converse": {
			"enable": true,
			"jid": "anonymous.duniter.org",
			"bosh_service_url": "https://chat.duniter.org/http-bind/",
			"auto_join_rooms": [
				"gchange@muc.duniter.org"
			]
		}
	},
	"version": "1.3.0",
	"build": "2021-06-19T10:21:57.418Z",
	"newIssueUrl": "https://github.com/duniter-gchange/gchange-client/issues/new?labels=bug"
})

;<commit_msg>v1.3.0<commit_after>/******
* !! WARNING: This is a generated file !!
*
* PLEASE DO NOT MODIFY DIRECTLY
*
* => Changes should be done on file 'app/config.json'.
******/

angular.module("cesium.config", [])

.constant("csConfig", {
	"fallbackLanguage": "fr-FR",
	"defaultLanguage": "fr-FR",
	"timeout": 300000,
	"cacheTimeMs": 300000,
	"useLocalStorage": true,
	"rememberMe": true,
	"useRelative": false,
	"decimalCount": 2,
	"shareBaseUrl": "https://gchange.fr",
	"helptip": {
		"enable": false
	},
	"feed": {
		"jsonFeed": {
			"fr-FR": "https://raw.githubusercontent.com/duniter-gchange/gchange-client/master/doc/feed/feed-fr.json",
			"en": "https://raw.githubusercontent.com/duniter-gchange/gchange-client/master/doc/feed/feed-en.json"
		},
		"maxContentLength": 1300
	},
	"node": {
		"host": "data.gchange.fr",
		"port": "443"
	},
	"fallbackNodes": [
		{
			"host": "data.gchange.fr",
			"port": "443"
		},
		{
			"host": "gchange.data.presles.fr",
			"port": "443"
		}
	],
	"share": {
		"mastodonAuthor": "@gchange@framapiaf.org"
	},
	"plugins": {
		"es": {
			"enable": true,
			"maxUploadBodySize": 5242880,
			"defaultCountry": "France"
		},
		"market": {
			"enable": true,
			"defaultSearch": {
				"geoDistance": "50"
			},
			"cesiumApi": {
				"enable": true,
				"baseUrl": "https://demo.cesium.app/api"
			}
		},
		"converse": {
			"enable": true,
			"jid": "anonymous.duniter.org",
			"bosh_service_url": "https://chat.duniter.org/http-bind/",
			"auto_join_rooms": [
				"gchange@muc.duniter.org"
			]
		}
	},
	"version": "1.3.0",
	"build": "2021-06-19T10:28:52.638Z",
	"newIssueUrl": "https://github.com/duniter-gchange/gchange-client/issues/new?labels=bug"
})

;<|endoftext|>


<commit_before><commit_msg>setRemove -> setName<commit_after><|endoftext|>


<commit_before><commit_msg>Account: add firstName + lastName + title<commit_after><|endoftext|>


<commit_before><commit_msg>Changed API response<commit_after><|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");
const dispatcher = require("../../../dispatcher");

module.exports = React.createClass({
    displayName: 'MemberAvatar',

    propTypes: {
        member: React.PropTypes.object.isRequired,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string,
        // Whether the onClick of the avatar should dispatch 'view_user'
        viewUserOnClick: React.PropTypes.boolean,
    },

    getDefaultProps: function() {
        return {
            width: 40,
            height: 40,
            resizeMethod: 'crop',
            viewUserOnClick: false,
        }
    },

    getInitialState: function() {
        return this._getState(this.props);
    },

    componentWillReceiveProps: function(nextProps) {
        this.setState(this._getState(nextProps));
    },

    _getState: function(props) {
        if (!props.member) {
            console.error("MemberAvatar called somehow with null member");
        }
        return {
            name: props.member.name,
            title: props.member.userId,
            imageUrl: Avatar.avatarUrlForMember(props.member,
                                         props.width,
                                         props.height,
                                         props.resizeMethod)
        }
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {member, ...otherProps} = this.props;

        var onClick = null;
        if (this.props.viewUserOnClick) {
            onClick = () => {
                dispatcher.dispatch({
                    action: 'view_user',
                    member: this.props.member,
                });
            }
        }

        return (
            <BaseAvatar {...otherProps} name={this.state.name} title={this.state.title}
                idName={member.userId} url={this.state.imageUrl} onClick={onClick}/>
        );
    }
});
<commit_msg>pass in prop onClick by default<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var Avatar = require('../../../Avatar');
var sdk = require("../../../index");
const dispatcher = require("../../../dispatcher");

module.exports = React.createClass({
    displayName: 'MemberAvatar',

    propTypes: {
        member: React.PropTypes.object.isRequired,
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        resizeMethod: React.PropTypes.string,
        // The onClick to give the avatar
        onClick: React.PropTypes.function,
        // Whether the onClick of the avatar should be overriden to dispatch 'view_user'
        viewUserOnClick: React.PropTypes.boolean,
    },

    getDefaultProps: function() {
        return {
            width: 40,
            height: 40,
            resizeMethod: 'crop',
            viewUserOnClick: false,
        }
    },

    getInitialState: function() {
        return this._getState(this.props);
    },

    componentWillReceiveProps: function(nextProps) {
        this.setState(this._getState(nextProps));
    },

    _getState: function(props) {
        if (!props.member) {
            console.error("MemberAvatar called somehow with null member");
        }
        return {
            name: props.member.name,
            title: props.member.userId,
            imageUrl: Avatar.avatarUrlForMember(props.member,
                                         props.width,
                                         props.height,
                                         props.resizeMethod)
        }
    },

    render: function() {
        var BaseAvatar = sdk.getComponent("avatars.BaseAvatar");

        var {member, onClick, ...otherProps} = this.props;

        if (this.props.viewUserOnClick) {
            onClick = () => {
                dispatcher.dispatch({
                    action: 'view_user',
                    member: this.props.member,
                });
            }
        }

        return (
            <BaseAvatar {...otherProps} name={this.state.name} title={this.state.title}
                idName={member.userId} url={this.state.imageUrl} onClick={onClick}/>
        );
    }
});
<|endoftext|>


<commit_before><commit_msg>Change comment styling<commit_after><|endoftext|>


<commit_before>/**
 * Test environment settings
 * @description :: This section overrides all other config values ONLY in test environment
 */

module.exports = {

  /***************************************************************************
   * Set the default database connection for models in the development       *
   * environment (see config/connections.js and config/models.js )           *
   ***************************************************************************/

  policies: {
    '*': true
  }

};
<commit_msg>add unit test env<commit_after>/**
 * Test environment settings
 * @description :: This section overrides all other config values ONLY in test environment
 */

module.exports = {

  /***************************************************************************
  * Set the default database connection for models in the development       *
  * environment (see config/connections.js and config/models.js )           *
  ***************************************************************************/

  models: {
    connection: 'memory',
    migrate: 'drop'
  },

  //pass all policies
  policies: {
    '*': true
  },

  port: 8012,

  globals:{
    sails:true
  },

  log: {
    level: 'error'
  }

};
<|endoftext|>


<commit_before><commit_msg>Remove unused code & comments<commit_after><|endoftext|>


<commit_before>;(function($, yl) {
    yl.forwardHandlerRegistry = yl.forwardHandlerRegistry || {};

    yl.registerForwardHandler = function(name, handler) {
        yl.forwardHandlerRegistry[name] = handler;
    };

    yl.getForwardHandler = function(name) {
        return yl.forwardHandlerRegistry[name];
    };

    function getForwardStrategy(element) {
        var checkForCheckboxes = function() {
            var all = true;
            $.each(element, function(ix, e) {
                if ($(e).attr("type") !== "checkbox") {
                    all = false;
                }
            });
            return all;
        };

        if (element.length === 1 &&
                element.attr("type") === "checkbox" &&
                element.attr("value") === undefined) {
            // Single checkbox without 'value' attribute
            // Boolean field
            return "exists";
        } else if (element.length === 1 &&
                element.attr("multiple") !== undefined) {
            // Multiple by HTML semantics. E. g. multiple select
            // Multiple choice field
            return "multiple";
        } else if (checkForCheckboxes()) {
            // Multiple checkboxes or one checkbox with 'value' attribute.
            // Multiple choice field represented by checkboxes
            return "multiple";
        } else {
            // Other cases
            return "single";
        }
    }

    /**
     * Get fields with name `name` relative to `element` with considering form
     * prefixes.
     * @param element the element
     * @param name name of the field
     * @returns jQuery object with found fields or empty jQuery object if no
     * field was found
     */
    yl.getFieldRelativeTo = function(element, name) {
        var prefixes = $(element).getFormPrefixes();

        for (var i = 0; i < prefixes.length; i++) {
            var fieldSelector = "[name=" + prefixes[i] + name + "]";
            var field = $(fieldSelector);

            if (field.length) {
                return field;
            }
        }

        return $();
    };

    /**
     * Get field value which is put to forwarded dictionary
     * @param field the field
     * @returns forwarded value
     */
    yl.getValueFromField = function(field) {
        var strategy = getForwardStrategy(field);
        var serializedField = $(field).serializeArray();

        if ((serializedField == false) && ($(field).prop('disabled'))) {
            $(field).prop('disabled', false);
            serializedField = $(field).serializeArray();
            $(field).prop('disabled', true);
        }

        var getSerializedFieldElementAt = function (index) {
            // Return serializedField[index]
            // or null if something went wrong
            if (serializedField.length > index) {
                return serializedField[index];
            } else {
                return null;
            }
        };

        var getValueOf = function (elem) {
            // Return elem.value
            // or null if something went wrong
            if (elem.hasOwnProperty("value") &&
                elem.value !== undefined
            ) {
                return elem.value;
            } else {
                return null;
            }
        };

        var getSerializedFieldValueAt = function (index) {
            // Return serializedField[index].value
            // or null if something went wrong
            var elem = getSerializedFieldElementAt(index);
            if (elem !== null) {
                return getValueOf(elem);
            } else {
                return null;
            }
        };

        if (strategy === "multiple") {
            return serializedField.map(
                function (item) {
                    return getValueOf(item);
                }
            );
        } else if (strategy === "exists") {
            return serializedField.length > 0;
        } else {
            return getSerializedFieldValueAt(0);
        }
    };

    yl.getForwards = function(element) {
        var forwardElem,
            forwardList,
            forwardedData,
            divSelector,
            form;
        divSelector = "div.dal-forward-conf#dal-forward-conf-for_" +
                element.attr("id");
        form = element.length > 0 ? $(element[0].form) : $();

        forwardElem =
            form.find(divSelector).find('script');
        if (forwardElem.length === 0) {
            return;
        }
        try {
            forwardList = JSON.parse(forwardElem.text());
        } catch (e) {
            return;
        }

        if (!Array.isArray(forwardList)) {
            return;
        }

        forwardedData = {};

        $.each(forwardList, function(ix, field) {
            var srcName, dstName;
            if (field.type === "const") {
                forwardedData[field.dst] = field.val;
            } else if (field.type === "self") {
                if (field.hasOwnProperty("dst")) {
                    dstName = field.dst;
                } else {
                    dstName = "self";
                }
                forwardedData[dstName] = yl.getValueFromField(element);
            } else if (field.type === "field") {
                srcName = field.src;
                if (field.hasOwnProperty("dst")) {
                    dstName = field.dst;
                } else {
                    dstName = srcName;
                }
                var forwardedField = yl.getFieldRelativeTo(element, srcName);

                if (!forwardedField.length) {
                    return;
                }

                forwardedData[dstName] = yl.getValueFromField(forwardedField);
            } else if (field.type === "javascript") {
                var handler = yl.getForwardHandler(field.handler);
                forwardedData[field.dst || field.handler] = handler(element);
            }

        });
        return JSON.stringify(forwardedData);
    };

})(yl.jQuery, yl);
<commit_msg>backward compatibility<commit_after>;(function($, yl) {
    yl.forwardHandlerRegistry = yl.forwardHandlerRegistry || {};

    yl.registerForwardHandler = function(name, handler) {
        yl.forwardHandlerRegistry[name] = handler;
    };

    yl.getForwardHandler = function(name) {
        return yl.forwardHandlerRegistry[name];
    };

    function getForwardStrategy(element) {
        var checkForCheckboxes = function() {
            var all = true;
            $.each(element, function(ix, e) {
                if ($(e).attr("type") !== "checkbox") {
                    all = false;
                }
            });
            return all;
        };

        if (element.length === 1 &&
                element.attr("type") === "checkbox" &&
                element.attr("value") === undefined) {
            // Single checkbox without 'value' attribute
            // Boolean field
            return "exists";
        } else if (element.length === 1 &&
                element.attr("multiple") !== undefined) {
            // Multiple by HTML semantics. E. g. multiple select
            // Multiple choice field
            return "multiple";
        } else if (checkForCheckboxes()) {
            // Multiple checkboxes or one checkbox with 'value' attribute.
            // Multiple choice field represented by checkboxes
            return "multiple";
        } else {
            // Other cases
            return "single";
        }
    }

    /**
     * Get fields with name `name` relative to `element` with considering form
     * prefixes.
     * @param element the element
     * @param name name of the field
     * @returns jQuery object with found fields or empty jQuery object if no
     * field was found
     */
    yl.getFieldRelativeTo = function(element, name) {
        var prefixes = $(element).getFormPrefixes();

        for (var i = 0; i < prefixes.length; i++) {
            var fieldSelector = "[name=" + prefixes[i] + name + "]";
            var field = $(fieldSelector);

            if (field.length) {
                return field;
            }
        }

        return $();
    };

    /**
     * Get field value which is put to forwarded dictionary
     * @param field the field
     * @returns forwarded value
     */
    yl.getValueFromField = function(field) {
        var strategy = getForwardStrategy(field);
        var serializedField = $(field).serializeArray();

        if ((serializedField == false) && ($(field).prop('disabled'))) {
            $(field).prop('disabled', false);
            serializedField = $(field).serializeArray();
            $(field).prop('disabled', true);
        }

        var getSerializedFieldElementAt = function (index) {
            // Return serializedField[index]
            // or null if something went wrong
            if (serializedField.length > index) {
                return serializedField[index];
            } else {
                return null;
            }
        };

        var getValueOf = function (elem) {
            // Return elem.value
            // or null if something went wrong
            if (elem.hasOwnProperty("value") &&
                elem.value !== undefined
            ) {
                return elem.value;
            } else {
                return null;
            }
        };

        var getSerializedFieldValueAt = function (index) {
            // Return serializedField[index].value
            // or null if something went wrong
            var elem = getSerializedFieldElementAt(index);
            if (elem !== null) {
                return getValueOf(elem);
            } else {
                return null;
            }
        };

        if (strategy === "multiple") {
            return serializedField.map(
                function (item) {
                    return getValueOf(item);
                }
            );
        } else if (strategy === "exists") {
            return serializedField.length > 0;
        } else {
            return getSerializedFieldValueAt(0);
        }
    };

    yl.getForwards = function(element) {
        var forwardElem,
            forwardList,
            forwardedData,
            divSelector,
            form;
        divSelector = "div.dal-forward-conf#dal-forward-conf-for-" +
                element.attr("id") + ", " +
                "div.dal-forward-conf#dal-forward-conf-for_" +
                element.attr("id");
        form = element.length > 0 ? $(element[0].form) : $();

        forwardElem =
            form.find(divSelector).find('script');
        if (forwardElem.length === 0) {
            return;
        }
        try {
            forwardList = JSON.parse(forwardElem.text());
        } catch (e) {
            return;
        }

        if (!Array.isArray(forwardList)) {
            return;
        }

        forwardedData = {};

        $.each(forwardList, function(ix, field) {
            var srcName, dstName;
            if (field.type === "const") {
                forwardedData[field.dst] = field.val;
            } else if (field.type === "self") {
                if (field.hasOwnProperty("dst")) {
                    dstName = field.dst;
                } else {
                    dstName = "self";
                }
                forwardedData[dstName] = yl.getValueFromField(element);
            } else if (field.type === "field") {
                srcName = field.src;
                if (field.hasOwnProperty("dst")) {
                    dstName = field.dst;
                } else {
                    dstName = srcName;
                }
                var forwardedField = yl.getFieldRelativeTo(element, srcName);

                if (!forwardedField.length) {
                    return;
                }

                forwardedData[dstName] = yl.getValueFromField(forwardedField);
            } else if (field.type === "javascript") {
                var handler = yl.getForwardHandler(field.handler);
                forwardedData[field.dst || field.handler] = handler(element);
            }

        });
        return JSON.stringify(forwardedData);
    };

})(yl.jQuery, yl);
<|endoftext|>


<commit_before>/**
 * Unlike other predefined token patterns, keywords are dynamic during runtime and may change
 * the factory will produce tokenHandlers for a provided array of keywords
 * */

export default function factory(keyword, type = 'KEYWORD') {
  return {
    pattern: new RegExp(`${keyword}`, 'gi'),
    onMatch: function onMatch(match) {
      return {
        type,
        content: match[0],
        index: match.index,
      };
    }
  };
}
<commit_msg>allow string or regex into keyword factory<commit_after>/**
 * Unlike other predefined token patterns, keywords are dynamic during runtime and may change
 * the factory will produce tokenHandlers for a provided array of keywords
 * */

export default function factory(token, type = 'KEYWORD') {
  let pattern;
  if (token instanceof RegExp) pattern = token;
  if (typeof token === 'string') pattern = new RegExp(`${token}`, 'gi');
  if (!pattern) return {};
  return {
    pattern,
    onMatch: function onMatch(match) {
      return {
        type,
        content: match[0],
        index: match.index,
      };
    }
  };
}
<|endoftext|>


<commit_before>/* Vim: set ts=8 sts=2 et sw=2 tw=80: */

/*
 * Syntax highlighting addition/removal handlers (content scripts).
 *
 * First we need to decide whether we do or undo highlight.
 *
 * To do it, we have to add a CSS stylesheet and to enclose

 blocks
 * content to highlight with  tags so that it looks like
 *
 int a = 3 + b;
 (see highlightjs doc).
 * We perform a backup of original document by putting it in a hidden div.
 *
 * Undoing highlight consists in getting saved document back from the div.
 */

/*
 * Execute this at startup
 */
var enlight = function () {
  /*
   * If there is no

 HTML block, there's nothing to work on: get
   * out of here.
   */
  if (!document.body ||
       document.body.getElementsByTagName("pre").item(0) === null) {
    self.port.emit('toggle_off', 1);
    return;
  }

  var initDocumentDiv = document.getElementById("enlightInitDocument");
  /*
   * If div is found, we already got syntax highlighting: let's undo it.
   * Else, launch highlighting.
   */
  initDocumentDiv === null ? dohl() : undohl(initDocumentDiv.firstChild);
} ();

function dohl() {
  var preList = document.getElementsByTagName("pre");
  /*
   * If self.options is undefined we shouldn't be there. Page has probably been
   * changed since a former highlight: get out as well.
   */
  if (self.options === undefined) {
    return;
  }

  /*
   * Add link to CSS stylesheet
   */
  var css = document.createElement("link");
  var style = self.options.stylesheet;
  css.setAttribute("href",  style != undefined ? style : "");
  css.setAttribute("rel",  "stylesheet");
  css.setAttribute("type", "text/css");
  css.setAttribute("id",   "enlightStylesheet");
  document.head.appendChild(css);

  /*
   * Back up initial document
   */
  var clone = document.documentElement.cloneNode(true);
  var idoc  = document.createElement("div");
  idoc.style.display = "none";
  idoc.setAttribute("id", "enlightInitDocument");
  idoc.appendChild(clone);

  /*
   * Deal with language
   */
  var setLanguage = (self.options.language != "" &&
                     self.options.language != "auto") ?
    function(element){element.setAttribute("class", self.options.language);} :
    function(element){};

  /*
   * Enclose

 blocks content in  blocks
   */
  for (var pre of preList) {
    var firstChild = pre.firstChild;
    var code = document.createElement("code");
    setLanguage(code);
    if (self.options.bgColor) {
      code.style = "padding: 0;";
    }
    code.appendChild(firstChild);
    pre.appendChild(code);
  }

  hljs.initHighlighting(); // from highlight.min.js or highlight.pack.js

  /*
   * Add line numbers if option is set
   */
  var lineNodes = self.options.lineNumbers;
  if (lineNodes) {
  for (pre of preList) {
      /*
       * Enclose each line of highlighted content into a "line" span.
       * Text has already been highlighted at this point (it's a mix of text
       * and of spans for coloring), so I can't see any easy way to do this
       * without assigning to innerHTML.
       */
      var lines = pre.firstChild.innerHTML
        .replace(/^.*?(\n|$)(?=.|\n)/gm, '$&');
      pre.firstChild.innerHTML = lines;

      /*
       * Numbering is performed with CSS. We add it to head of document. From
       * https://github.com/isagalaev/highlight.js/compare/master...line-numbers
       */
      var styleContent = " \
        pre { \
          counter-reset: lines; \
        } \
        pre .line { \
          counter-increment: lines; \
        } \
        pre .line::before { \
          -moz-user-select: none; \
          \
          content: counter(lines); text-align: right; \
          display: inline-block; min-width: 2.5em; \
          padding-right: 0.5em; margin-right: 0.5em; \
          font-weight: bold; \
          border-right: solid 1px; \
        }";
      var style = document.createElement("style");
      style.setAttribute("type", "text/css");
      var styleTextNode = document.createTextNode(styleContent);
      style.appendChild(styleTextNode);
      document.head.appendChild(style);
    }
  }

  /*
   * There's a white border remaining because of document.background.
   * If option is set, remove it.
   */
  if (self.options.bgColor) {
    setTimeout(function () { // Wait for CSS to be computed
      let codeBG = getComputedStyle(code)["background-color"];
      if (codeBG && codeBG!="white" && codeBG!="#FFFFFF" && codeBG!="#ffffff") {
          document.body.style.backgroundColor = codeBG;
      }
    }, 50);
  }

  /*
   * If we launched language auto-detection, tell main script about detected
   * language
   */
  if (self.options.language == "" || self.options.language == "auto") {
    let languageClass = document.querySelectorAll('pre code')[0].className;
    let languageId = languageClass.slice("hljs ".length);
    self.port.emit('detected_language', languageId);
  }

  /*
   * Save previous document in a hidden div to restore it on undohl()
   */
  document.body.appendChild(idoc);
}

function undohl(idoc) {
  document.replaceChild(idoc, document.documentElement);
  /*
   * Another solution:
   * window.location.reload(false);
   */
}
<commit_msg>Add “Go to line” functionality through URL<commit_after>/* Vim: set ts=8 sts=2 et sw=2 tw=80: */

/*
 * Syntax highlighting addition/removal handlers (content scripts).
 *
 * First we need to decide whether we do or undo highlight.
 *
 * To do it, we have to add a CSS stylesheet and to enclose

 blocks
 * content to highlight with  tags so that it looks like
 *
 int a = 3 + b;
 (see highlightjs doc).
 * We perform a backup of original document by putting it in a hidden div.
 *
 * Undoing highlight consists in getting saved document back from the div.
 */

/*
 * Execute this at startup
 */
var enlight = function () {
  /*
   * If there is no

 HTML block, there's nothing to work on: get
   * out of here.
   */
  if (!document.body ||
       document.body.getElementsByTagName("pre").item(0) === null) {
    self.port.emit('toggle_off', 1);
    return;
  }

  var initDocumentDiv = document.getElementById("enlightInitDocument");
  /*
   * If div is found, we already got syntax highlighting: let's undo it.
   * Else, launch highlighting.
   */
  initDocumentDiv === null ? dohl() : undohl(initDocumentDiv.firstChild);
  gotoline();
} ();

function dohl() {
  var preList = document.getElementsByTagName("pre");
  /*
   * If self.options is undefined we shouldn't be there. Page has probably been
   * changed since a former highlight: get out as well.
   */
  if (self.options === undefined) {
    return;
  }

  /*
   * Add link to CSS stylesheet
   */
  var css = document.createElement("link");
  var style = self.options.stylesheet;
  css.setAttribute("href",  style != undefined ? style : "");
  css.setAttribute("rel",  "stylesheet");
  css.setAttribute("type", "text/css");
  css.setAttribute("id",   "enlightStylesheet");
  document.head.appendChild(css);

  /*
   * Back up initial document
   */
  var clone = document.documentElement.cloneNode(true);
  var idoc  = document.createElement("div");
  idoc.style.display = "none";
  idoc.setAttribute("id", "enlightInitDocument");
  idoc.appendChild(clone);

  /*
   * Deal with language
   */
  var setLanguage = (self.options.language != "" &&
                     self.options.language != "auto") ?
    function(element){element.setAttribute("class", self.options.language);} :
    function(element){};

  /*
   * Enclose

 blocks content in  blocks
   */
  for (var pre of preList) {
    var firstChild = pre.firstChild;
    var code = document.createElement("code");
    setLanguage(code);
    if (self.options.bgColor) {
      code.style = "padding: 0;";
    }
    code.appendChild(firstChild);
    pre.appendChild(code);
  }

  hljs.initHighlighting(); // from highlight.min.js or highlight.pack.js

  /*
   * Add line numbers if option is set
   */
  var lineNodes = self.options.lineNumbers;
  if (lineNodes) {
  for (pre of preList) {
      /*
       * Enclose each line of highlighted content into a "line" span.
       * Text has already been highlighted at this point (it's a mix of text
       * and of spans for coloring), so I can't see any easy way to do this
       * without assigning to innerHTML.
       */
      var lines = pre.firstChild.innerHTML
        .replace(/^.*?(\n|$)(?=.|\n)/gm, '$&');
      pre.firstChild.innerHTML = lines;

      /*
       * Numbering is performed with CSS. We add it to head of document. From
       * https://github.com/isagalaev/highlight.js/compare/master...line-numbers
       */
      var styleContent = " \
        pre { \
          counter-reset: lines; \
        } \
        pre .line { \
          counter-increment: lines; \
        } \
        pre .line::before { \
          -moz-user-select: none; \
          \
          content: counter(lines); text-align: right; \
          display: inline-block; min-width: 2.5em; \
          padding-right: 0.5em; margin-right: 0.5em; \
          font-weight: bold; \
          border-right: solid 1px; \
        }";
      var style = document.createElement("style");
      style.setAttribute("type", "text/css");
      var styleTextNode = document.createTextNode(styleContent);
      style.appendChild(styleTextNode);
      document.head.appendChild(style);
    }
  }

  /*
   * There's a white border remaining because of document.background.
   * If option is set, remove it.
   */
  if (self.options.bgColor) {
    setTimeout(function () { // Wait for CSS to be computed
      let codeBG = getComputedStyle(code)["background-color"];
      if (codeBG && codeBG!="white" && codeBG!="#FFFFFF" && codeBG!="#ffffff") {
          document.body.style.backgroundColor = codeBG;
      }
    }, 50);
  }

  /*
   * If we launched language auto-detection, tell main script about detected
   * language
   */
  if (self.options.language == "" || self.options.language == "auto") {
    let languageClass = document.querySelectorAll('pre code')[0].className;
    let languageId = languageClass.slice("hljs ".length);
    self.port.emit('detected_language', languageId);
  }

  /*
   * Save previous document in a hidden div to restore it on undohl()
   */
  document.body.appendChild(idoc);
}

/*
 * If user added an anchor to the URL, go to line number and select this line.
 * NOTE: there is no event triggered by URL edit that we could listen to, so
 * the anchor must be present when the script loads. If user adds it afterward,
 * they should manually reload the script (or the page if using autodetection).
 */
function gotoline() {
  /*
   * Get "#line27" or "#Line27" or "#L27" or "#l27" -like sequence from URL
   */
  let nb = (window.location + '').match(/#(?:[Ll](?:ine)?)?(\d+)/i)
  if (nb === null) {
    return;
  }

  /*
   * Fetch associated line. Note that we fetch the “absolute” nth line of
   * highlighted code in the file, which is not necessarily the nth line of its
   * block if there are several highlighted blocks of code.
   */
  let target = document.getElementsByClassName('line')[nb[1]-1]
  if (target === undefined) {
    return;
  }

  /*
   * Scroll to that line
   */
  target.scrollIntoView();

  /*
   * Select this line
   */
  let next = target.nextSibling;
  while (next.nextSibling !== null
         && (next.nextSibling.className === undefined
             || next.nextSibling.className.search(/\bline\b/) == -1)) {
    let selection = window.getSelection();
    let range = document.createRange();
    range.selectNodeContents(next);
    selection.addRange(range);
    next = next.nextSibling;
  }
}

function undohl(idoc) {
  document.replaceChild(idoc, document.documentElement);
  /*
   * Another solution:
   * window.location.reload(false);
   */
}
<|endoftext|>


<commit_before>Kwf.FrontendForm.Cards = Ext.extend(Kwf.FrontendForm.Field, {
    initField: function() {
        var config = this.form.getFieldConfig(this.getFieldName());
        var combobox = this.form.findField(config.combobox);
        combobox.el.child('input.submit').remove(); //remove non-js fallback
        combobox.on('change', function(value) {
            this.el.select('.kwfFormContainerCard .kwfFormCard').addClass('inactive');
            this.el.select('.kwfFormContainerCard.'+value+' .kwfFormCard').removeClass('inactive');
        }, this);
    },
    getFieldName: function() {
        var classNames = this.el.dom.className.split(' ');
        return classNames[classNames.length-1];
    },
    getValue: function() {
        return null;
    },
    clearValue: function() {
    },
    setValue: function(value) {
    }
});

Kwf.FrontendForm.fields['kwfFormContainerCards'] = Kwf.FrontendForm.Cards;
<commit_msg>only remove submit if exists<commit_after>Kwf.FrontendForm.Cards = Ext.extend(Kwf.FrontendForm.Field, {
    initField: function() {
        var config = this.form.getFieldConfig(this.getFieldName());
        var combobox = this.form.findField(config.combobox);
        combobox.el.select('input.submit').remove(); //remove non-js fallback
        combobox.on('change', function(value) {
            this.el.select('.kwfFormContainerCard .kwfFormCard').addClass('inactive');
            this.el.select('.kwfFormContainerCard.'+value+' .kwfFormCard').removeClass('inactive');
        }, this);
    },
    getFieldName: function() {
        var classNames = this.el.dom.className.split(' ');
        return classNames[classNames.length-1];
    },
    getValue: function() {
        return null;
    },
    clearValue: function() {
    },
    setValue: function(value) {
    }
});

Kwf.FrontendForm.fields['kwfFormContainerCards'] = Kwf.FrontendForm.Cards;
<|endoftext|>


<commit_before><commit_msg>Add chart functionality in user statistics<commit_after><|endoftext|>


<commit_before>// ==UserScript==
// @name        Chatzy+
// @namespace   https://rakutiki.tv/
// @author      Raku
// @description Adds extra functionality to chatzy
// @include     /https?://us1[1-9]|2[1-9]\.chatzy\.(com|org)/*/
// @include     http://us*.chatzy.*/*
// @version     1.2.2.2
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_deleteValue
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
// ==/UserScript==
// dust
//Vars for stuff
var framelink = document.getElementById('X457').href.replace('default', 'frame');
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)ChatzySkin\s*\=\s*([^;]*).*$)|^.*$/, '$1');
var lastHtml = $('#X294').text();
//First run init

if (GM_getValue('firstrun', '0') == '0') {
  if (confirm('Welcome to chatzy+ version ' + GM_info.script.version + '!\nThis script adds several new functions to chatzy in the form of input line commands, click OK to learn more about the available commands and features, otherwise you can run !help to bring up the menu later.\nBy continuing to use this script you agree that the author and any contributors are not responsible for anything that may happen.')) {
    helpdialog();
    if (window.chrome == true) {
      alert('This script is known to have issues working right on chrome. Don\'t say I didn\'t warn you, mmkay?' )
    }
    GM_setValue('firstrun', '1');
  } else {
    GM_setValue('firstrun', '1');
  }
}
//Command hooks

$('#X91').on('keydown', function (e) {
  var input = $('#X91').val();
  if (e.keyCode == 13) {
    if (input.substr(0, 5) === '!ref ') {
      $('#X91').val(GM_getValue('ref' + input.split(' ') [1]));
    }
    if (input.substr(0, 9) === '!ref add ') {
      GM_setValue('ref' + input.split(' ') [2], input.split(' ') [3]);
      $('#X91').val(' ');
      alert('Ref URL added, post with !ref ' + input.split(' ') [2]);
    }
    if (input == '!help') {
      $('#X91').val(' ');
      helpdialog();
    }
    if (input == '!help font') {
      alert('To set a custom font(outside of the websafe ones you are limited normally), run !font set <url> and substitute <url> for a url to a google font from here https://www.google.com/fonts for example if you wanted this font https://fonts.googleapis.com/css?family=Oswald you would run !font set https://fonts.googleapis.com/css?family=Oswald\nThe next step is to go in to your account settings and set your font to a custom one(last radial button, should have a text field next to it) and clear whatever is there, and replace it with your font name in single quotes, using the same example as earlier, you would type \'Oswald\' and then click OK and save your prefrences');
      $('#X91').val(' ');
    }
    if (input.substr(0, 7) == '!short ') {
      if (input.split(' ') [1] == 'on') {
        GM_setValue('short', 'on');
      }
      if (input.split(' ') [1] == 'off') {
        GM_setValue('short', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 8) == '!unaway ') {
      if (input.substr(8) == 'on') {
        GM_setValue('away', 'on');
      }
      if (input.substr(8) == 'off') {
        GM_setValue('away', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 7) == '!frame ') {
      if (input.substr(7) == 'on') {
        GM_setValue('frame', 'on');
      }
      if (input.substr(7) == 'off') {
        GM_setValue('frame', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 6) == '!skin ') {
      if (input.substr(6) == 'on') {
        GM_setValue('skin', 'on');
      }
      if (input.substr(6) == 'off') {
        GM_setValue('skin', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 6) == '!skin ') {
      if (input.substr(6) == 'on') {
        GM_setValue('skin', 'on');
      }
      if (input.substr(6) == 'off') {
        GM_setValue('skin', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 6) == '!font ') {
      if (input.split(' ') [1] == 'set') {
        GM_setValue('font', input.split(' ') [2]);
      }
      if (input.split(' ') [1] == 'off') {
        GM_deleteValue('font');
      }
      $('#X91').val(' ');
    }
    if (input == '!history') {
      if (GM_getValue('history') !== undefined) {
      alert(GM_getValue('history'));
      } else {
        alert('None yet :<');
        $('#X91').val(' ');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 9) == '!history ') {
      if (input.substr(9) == 'on') {
        GM_setValue('msg', 'on');
      }
      if (input.substr(9) == 'off') {
        GM_setValue('msg', 'off')
      }
      if (input.substr(9) == 'clear') {
        if (confirm('Are you sure you want to clear local PM storage? (IRREVERSIBLE)')) {
          GM_deleteValue('history');
          alert('Local PM storage cleared.');
        } else {
          alert('Local PM storage not cleared.');
          $('#X91').val(' ');
        }
        $('#X91').val(' ');
      }
      $('#X91').val(' ');
    }
    if (GM_getValue('short') == 'on') {
      this.value = this.value.replace(/\*([^*]+?)\*/g, '[b]$1[/b]');
      this.value = this.value.replace(/\_([^*]+?)\_/g, '[u]$1[/u]');
      this.value = this.value.replace(/\^([^*]+?)\^/g, '[i]$1[/i]');
    }
  }
});
//Function to show help dialog
function helpdialog() {
  alert('Command listing, things wrapped in <> should not be typed with the <> surrounding them\n!ref add <name> <url> - Stores the specified url under the specified name.\n!ref <name> - Posts the stored ref with that name.\n!short on/off - Turns shorthands on or off, shorthands are as follows:\nWrap text in ^("^the quick brown fox^") for italics, wrap text in * for bold, and wrap text in _ for underline\n!unaway on/off - Turns auto-unsetting of your away on or off\n!skin on/off - Makes your skin you set in account setting apply globaly(all rooms), it will override any rooms with their own skin set as well however\n!frame on/off - Makes chatzy use the stylesheet they use when the chat is embedded in an iframe, might not look pretty\n!font set <url>/off - refer to !help font\n!history on/off/clear - Turns PM logging locally on or off, or clears your local PM storage, run without any arguments to get your local PM logs');
}
//Other various functions I'm too lazy to mark

window.setInterval(function () {
  if (GM_getValue('away') == 'on') {
    if ($('input[value="I am here!"]').is(':visible')) {
      $('input[value="I am here!"]').trigger('click');
      $('form#X114').submit();
    }
  }
  if (GM_getValue('frame') == 'on') {
    if (document.getElementById('X457').href != framelink) {
      document.getElementById('X457').href = document.getElementById('X457').href.replace('default', 'frame');
    }
  }
  if (GM_getValue('skin') == 'on') {
    if (document.getElementById('X457').href.split(':') [4] != cookieValue) {
      document.getElementById('X457').href = document.getElementById('X457').href.replace(document.getElementById('X457').href.split(':') [4], cookieValue);
    }
  }
  if ($('#X294').is(':visible')) {
    var time = $('#X93 .X724').html();
    var newHtml = $('#X294').text();
    var name = $('#X93 em').html();
    if (GM_getValue('msg') == 'on') {
      if (newHtml != lastHtml) {
        lastHtml = newHtml;
        if (GM_getValue('history') !== undefined) {
          GM_setValue('history', GM_getValue('history') + '\n' + name + ' ' + newHtml + ' ' + time);
        } else {
          GM_setValue('history', '\n' + name + ' ' + newHtml + ' ' + time);
        }
      }
    }
  }
}, 150);
if (GM_getValue('font')) {
  $('head').append('<link href="' + GM_getValue('font') + '" rel="stylesheet" type="text/css">');
}
console.log(GM_getValue('msg'));
<commit_msg>Chrome stuff<commit_after>// ==UserScript==
// @name        Chatzy+
// @namespace   https://rakutiki.tv/
// @author      Raku
// @description Adds extra functionality to chatzy
// @include     /https?://us1[1-9]|2[1-9]\.chatzy\.(com|org)/*/
// @include     http://us*.chatzy.*/*
// @version     1.2.2.3
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_deleteValue
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js
// ==/UserScript==
// dust
//Vars for stuff
var framelink = document.getElementById('X457').href.replace('default', 'frame');
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)ChatzySkin\s*\=\s*([^;]*).*$)|^.*$/, '$1');
var lastHtml = $('#X294').text();
//First run init
if (GM_getValue('firstrun', '0') == '0') {
  if (confirm('Welcome to chatzy+ version ' + GM_info.script.version + '!\nThis script adds several new functions to chatzy in the form of input line commands, click OK to learn more about the available commands and features, otherwise you can run !help to bring up the menu later.\nBy continuing to use this script you agree that the author and any contributors are not responsible for anything that may happen.')) {
    helpdialog();
    GM_setValue('firstrun', '1');
  } else {
    GM_setValue('firstrun', '1');
  }
  if (window.chrome) {
    alert('This script is known to have issues working right on chrome. Don\'t say I didn\'t warn you, mmkay?')
  }
}
//Command hooks

$('#X91').on('keydown', function (e) {
  var input = $('#X91').val();
  if (e.keyCode == 13) {
    if (input.substr(0, 5) === '!ref ') {
      $('#X91').val(GM_getValue('ref' + input.split(' ') [1]));
    }
    if (input.substr(0, 9) === '!ref add ') {
      GM_setValue('ref' + input.split(' ') [2], input.split(' ') [3]);
      $('#X91').val(' ');
      alert('Ref URL added, post with !ref ' + input.split(' ') [2]);
    }
    if (input == '!help') {
      $('#X91').val(' ');
      helpdialog();
    }
    if (input == '!help font') {
      alert('To set a custom font(outside of the websafe ones you are limited normally), run !font set <url> and substitute <url> for a url to a google font from here https://www.google.com/fonts for example if you wanted this font https://fonts.googleapis.com/css?family=Oswald you would run !font set https://fonts.googleapis.com/css?family=Oswald\nThe next step is to go in to your account settings and set your font to a custom one(last radial button, should have a text field next to it) and clear whatever is there, and replace it with your font name in single quotes, using the same example as earlier, you would type \'Oswald\' and then click OK and save your prefrences');
      $('#X91').val(' ');
    }
    if (input.substr(0, 7) == '!short ') {
      if (input.split(' ') [1] == 'on') {
        GM_setValue('short', 'on');
      }
      if (input.split(' ') [1] == 'off') {
        GM_setValue('short', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 8) == '!unaway ') {
      if (input.substr(8) == 'on') {
        GM_setValue('away', 'on');
      }
      if (input.substr(8) == 'off') {
        GM_setValue('away', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 7) == '!frame ') {
      if (input.substr(7) == 'on') {
        GM_setValue('frame', 'on');
      }
      if (input.substr(7) == 'off') {
        GM_setValue('frame', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 6) == '!skin ') {
      if (input.substr(6) == 'on') {
        GM_setValue('skin', 'on');
      }
      if (input.substr(6) == 'off') {
        GM_setValue('skin', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 6) == '!skin ') {
      if (input.substr(6) == 'on') {
        GM_setValue('skin', 'on');
      }
      if (input.substr(6) == 'off') {
        GM_setValue('skin', 'off');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 6) == '!font ') {
      if (input.split(' ') [1] == 'set') {
        GM_setValue('font', input.split(' ') [2]);
      }
      if (input.split(' ') [1] == 'off') {
        GM_deleteValue('font');
      }
      $('#X91').val(' ');
    }
    if (input == '!history') {
      if (GM_getValue('history') !== undefined) {
        alert(GM_getValue('history'));
      } else {
        alert('None yet :<');
        $('#X91').val(' ');
      }
      $('#X91').val(' ');
    }
    if (input.substr(0, 9) == '!history ') {
      if (input.substr(9) == 'on') {
        GM_setValue('msg', 'on');
      }
      if (input.substr(9) == 'off') {
        GM_setValue('msg', 'off')
      }
      if (input.substr(9) == 'clear') {
        if (confirm('Are you sure you want to clear local PM storage? (IRREVERSIBLE)')) {
          GM_deleteValue('history');
          alert('Local PM storage cleared.');
        } else {
          alert('Local PM storage not cleared.');
          $('#X91').val(' ');
        }
        $('#X91').val(' ');
      }
      $('#X91').val(' ');
    }
    if (GM_getValue('short') == 'on') {
      this.value = this.value.replace(/\*([^*]+?)\*/g, '[b]$1[/b]');
      this.value = this.value.replace(/\_([^*]+?)\_/g, '[u]$1[/u]');
      this.value = this.value.replace(/\^([^*]+?)\^/g, '[i]$1[/i]');
    }
  }
});
//Function to show help dialog
function helpdialog() {
  alert('Command listing, things wrapped in <> should not be typed with the <> surrounding them\n!ref add <name> <url> - Stores the specified url under the specified name.\n!ref <name> - Posts the stored ref with that name.\n!short on/off - Turns shorthands on or off, shorthands are as follows:\nWrap text in ^("^the quick brown fox^") for italics, wrap text in * for bold, and wrap text in _ for underline\n!unaway on/off - Turns auto-unsetting of your away on or off\n!skin on/off - Makes your skin you set in account setting apply globaly(all rooms), it will override any rooms with their own skin set as well however\n!frame on/off - Makes chatzy use the stylesheet they use when the chat is embedded in an iframe, might not look pretty\n!font set <url>/off - refer to !help font\n!history on/off/clear - Turns PM logging locally on or off, or clears your local PM storage, run without any arguments to get your local PM logs');
}
//Other various functions I'm too lazy to mark

window.setInterval(function () {
  if (GM_getValue('away') == 'on') {
    if ($('input[value="I am here!"]').is(':visible')) {
      $('input[value="I am here!"]').trigger('click');
      $('form#X114').submit();
    }
  }
  if (GM_getValue('frame') == 'on') {
    if (document.getElementById('X457').href != framelink) {
      document.getElementById('X457').href = document.getElementById('X457').href.replace('default', 'frame');
    }
  }
  if (GM_getValue('skin') == 'on') {
    if (document.getElementById('X457').href.split(':') [4] != cookieValue) {
      document.getElementById('X457').href = document.getElementById('X457').href.replace(document.getElementById('X457').href.split(':') [4], cookieValue);
    }
  }
  if ($('#X294').is(':visible')) {
    var time = $('#X93 .X724').html();
    var newHtml = $('#X294').text();
    var name = $('#X93 em').html();
    if (GM_getValue('msg') == 'on') {
      if (newHtml != lastHtml) {
        lastHtml = newHtml;
        if (GM_getValue('history') !== undefined) {
          GM_setValue('history', GM_getValue('history') + '\n' + name + ' ' + newHtml + ' ' + time);
        } else {
          GM_setValue('history', '\n' + name + ' ' + newHtml + ' ' + time);
        }
      }
    }
  }
}, 150);
if (GM_getValue('font')) {
  $('head').append('<link href="' + GM_getValue('font') + '" rel="stylesheet" type="text/css">');
}
console.log(GM_getValue('msg'));
<|endoftext|>