<commit_before>
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;
}
<commit_msg>alt for image is added in showHide method<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>// Copyright 2011 Google Inc. All Rights Reserved.

/**
 * @fileoverview ChromeOS Chinese Input Method in JavaScript Extension
 * @author hungte@google.com (Hung-Te Lin)
 */

/**
 * The root namespace.
 */

var croscin = {};

/**
 * Chinese IME class.
 * @constructor
 */
croscin.IME = function() {
  var self = this;
  self.kOptionsPage = "options";

  // TODO(hungte) support multiple im's
  self.imctx = {};
  // self.default_input_method = 'array30';
  // self.default_input_method = 'liu57b';
  self.im = jscin.create_input_method(jscin.default_input_method, self.imctx);
  self.current_input_method = jscin.default_input_method;

  self.engineID = null;
  self.context = null;

  // TODO(hungte) remove this workaround: "onActivate is not called if user is
  // already using extension and then reload..
  self.engineID = jscin.ENGINE_ID;

  self.registerEventHandlers();

  // Standard utilities
  self.GetBaseArg = function() {
    var arg = {};
    arg.contextID = this.context.contextID;
    return arg;
  }

  self.log = function(s) {
    jscin.log(s);
  }

  // Core functions
  self.Commit = function(text) {
    // TODO(hungte) fixme when gen_inp has fixed this.
    if (typeof(text) != typeof('')) {
      text = text[0];
      self.log("croscin.Commit: WARNING: input text is not a simple string.");
    }

    if (text) {
      var arg = self.GetBaseArg();
      arg.text = text;
      self.ime_api.commitText(arg);
      self.log("croscin.Commit: value: " + text);
    } else {
      self.log("croscin.Commmit: warning: called with empty string.");
    }
  }

  self.ProcessKeyEvent = function(keyData) {
    self.log("ProcessKeyEvent: " + keyData.key);

    // Currently all of the modules uses key down.
    if (keyData.type != 'keydown') {
      return false;
    }

    var ret = self.im.onKeystroke(self.imctx, keyData);
    self.log(dump_inpinfo(self.imctx));

    switch (ret) {
      case jscin.IMKEY_COMMIT:
        self.log("im.onKeystroke: return IMKEY_COMMIT");
        self.Commit(self.imctx.cch);
        self.UpdateUI();
        return true;

      case jscin.IMKEY_ABSORB:
        self.log("im.onKeystroke: return IMKEY_ABSORB");
        self.UpdateUI();
        return true;

      case jscin.IMKEY_IGNORE:
        self.log("im.onKeystroke: return IMKEY_IGNORE");
        self.UpdateUI();
        return false;
    }

    // default: Unknown return value.
    self.log("croscin.ProcessKeyEvent: Unknown return value: " + ret);
    return false;
  }

  self.SimulateKeyDown = function(key) {
    var keyEvent = {
      'type': 'keydown',
      'key': key,
      'altKey': false,
      'ctrlKey': false,
      'shiftKey': false,
    };
    return self.ProcessKeyEvent(keyEvent);
  }

  self.SetCanditesWindowProperty = function(name, value) {
    self.log("croscin.SetCanditesWindowProperty: set " + name + ": " + value);
    var prop = {};
    var arg = { engineID: self.engineID,
                properties: prop };
    prop[name] = value;
    self.ime_api.setCandidateWindowProperties(arg);
  }

  self.InitializeUI = function() {
    // Vertical candidates window looks better on ChromeOS.
    self.SetCanditesWindowProperty('vertical', true);
    // CIN tables don't expect cursor in candidates window.
    self.SetCanditesWindowProperty('cursorVisible', false);
    self.SetCanditesWindowProperty('visible', false);

    // Setup menu
    self.UpdateMenu();
  }

  self.UpdateComposition = function(text) {
    var arg = self.GetBaseArg();
    self.log("croscin.UpdateComposition: " + text);
    if (text) {
      arg.text = text;
      // Select everything in composition.
      arg.selectionStart = 0;
      arg.selectionEnd = text.length;
      arg.cursor = text.length;
      self.ime_api.setComposition(arg);
    } else {
      self.ime_api.clearComposition(arg);
    }
  }

  self.UpdateCandidates = function(candidate_list, labels) {
    self.log("croscin.UpdateCandidates: elements = " + candidate_list.length +
             ", labels = " + labels);
    // TODO(hungte) set more properties:
    //  auxiliaryText, auxiliaryTextVisible.
    if (candidate_list.length > 0) {
      var arg = self.GetBaseArg();
      var candidates = [];
      for (var i = 0; i < candidate_list.length; i++) {
        // TODO(hungte) fix label, annotation
        candidates.push({
          'candidate': candidate_list[i],
          'id': i,
          'label': labels.charAt(i),
        });
      }
      self.log('candidates:');
      self.log(candidates);
      arg.candidates = candidates;
      self.ime_api.setCandidates(arg);
      self.SetCanditesWindowProperty('pageSize', candidate_list.length);
      self.SetCanditesWindowProperty('visible', true);
    } else {
      self.SetCanditesWindowProperty('visible', false);
    }
  }

  self.UpdateUI = function() {
    var imctx = self.imctx;
    // process:
    //  - keystroke
    //  - suggest_skeystroke
    self.UpdateComposition(imctx.keystroke);
    //  - selkey
    //  - mcch
    self.UpdateCandidates(imctx.mcch, imctx.selkey);
    //  - lcch
    //  - cch_publish
  }

  self.ActivateInputMethod = function(name) {
    if (name in jscin.input_methods) {
      self.log("croscin.onMenuItemActivated: Selected: " + name);
      // TODO(hungte) Create new instance only if required.
      self.imctx = {};
      self.im = jscin.create_input_method(name, self.imctx);
      self.current_input_method = name;
      self.InitializeUI();
    } else {
      self.log("croscin.onMenuItemActivated: Invalid item: " + name);
    }
  }

  self.SetMenuItems = function() {
    var menu_items = [];

    for (var i in jscin.input_methods) {
      var label = jscin.input_methods[i]["label"];
      if (!label)
        label = i;
      menu_items.push({
        "id": "ime:" + i,
        "label": label,
        "style": "radio"
      });
    }
    self.log("croscin.UpdateMenu: " + menu_items.length + " items.");

    // Add a separator and options  (Separator does not work yet).
    menu_items.push({"id": "",
                     "style": "separator"});
    menu_items.push({"id": self.kOptionsPage,
                     "label": "Options"});
    self.ime_api.setMenuItems({
      "engineID": jscin.ENGINE_ID,
      "items": menu_items}
    );
  }

  self.UpdateMenu = function() {
    var menu_items = [];
    for (var i in jscin.input_methods) {
      menu_items.push({
        "id": "ime:" + i,
        "checked": i == self.current_input_method
      });
    }
    self.ime_api.updateMenuItems({
      "engineID": jscin.ENGINE_ID,
      "items": menu_items});
  }

  self.SetMenuItems();
};

/**
 * Registers event handlers to the browser.
 */
croscin.IME.prototype.registerEventHandlers = function() {
  /* find out proper ime_api: chrome.input.ime or chrome.experimental.input */
  var ime_api = null;
  if ("input" in chrome && "ime" in chrome.input)
    ime_api = chrome.input.ime;
  else
    ime_api = chrome.experimental.input;
  if ("ime" in ime_api)
    ime_api = ime_api.ime;

  var self = this;
  self.ime_api = ime_api;

  ime_api.onActivate.addListener(function(engineID) {
    self.engineID = engineID;
    self.InitializeUI();
  });

  ime_api.onDeactivated.addListener(function(engineID) {
    self.context = null;
  });

  ime_api.onFocus.addListener(function(context) {
    self.context = context;
    // TODO(hungte) remove this workaround: "onActivate is not called if user
    // reloads extension.
    self.InitializeUI();

    // Calling updateUI here is to carry unfinished composition (preedit) into
    // the new input element.
    self.UpdateUI();
  });

  ime_api.onBlur.addListener(function(contextID) {
    if (!self.context) {
      self.log("croscin.onBlur: WARNING: no existing context.");
      return;
    }
    if (self.context.contextID != contextID) {
      self.log("croscin.onBlur: WARNING: incompatible context.");
      return;
    }
    // TODO(hungte) Uncomment this if we don't want context to be carried when
    // input focus changes.
    // self.SimulateKeyDown('Esc');
    self.context = null;
  });

  ime_api.onKeyEvent.addListener(function(engine, keyData) {
    return self.ProcessKeyEvent(keyData);
  });

  ime_api.onInputContextUpdate.addListener(function(context) {
  });

  ime_api.onCandidateClicked.addListener(
      function(engineID, candidateID, button) {
        self.log("onCandidateClicked: " + candidateID + ", " + button);
        if (button == "left") {
          self.SimulateKeyDown(self.imctx.selkey.charAt(candidateID));
        }
  });

  ime_api.onMenuItemActivated.addListener(function(engineID, name) {
    self.log("croscin.onMenuItemActivated: name=" + name);

    if (name == self.kOptionsPage) {
      var options_url = chrome.extension.getURL("options/options.html");
      chrome.tabs.create({"url": options_url});
    } else if (name.match(/^ime:/)) {
      self.ActivateInputMethod(name.replace(/^ime:/, ''));
    }
  });

  window.on_config_changed = function() {
    // TODO: Reload config
    self.SetMenuItems();
    self.UpdateUI();
  }
};

// Browser loader entry
document.addEventListener(
    'readystatechange',
    function() {
      if (document.readyState === 'complete') {
        new croscin.IME;
      }
    }
)
<commit_msg>clean up menu processing<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.

/**
 * @fileoverview ChromeOS Chinese Input Method in JavaScript Extension
 * @author hungte@google.com (Hung-Te Lin)
 */

/**
 * The root namespace.
 */

var croscin = {};

/**
 * Chinese IME class.
 * @constructor
 */
croscin.IME = function() {
  var self = this;
  self.kOptionsPage = "options";

  // TODO(hungte) support multiple im's
  self.imctx = {};
  // self.default_input_method = 'array30';
  // self.default_input_method = 'liu57b';
  self.im = jscin.create_input_method(jscin.default_input_method, self.imctx);
  self.current_input_method = jscin.default_input_method;

  self.engineID = null;
  self.context = null;

  // TODO(hungte) remove this workaround: "onActivate is not called if user is
  // already using extension and then reload..
  self.engineID = jscin.ENGINE_ID;

  self.registerEventHandlers();

  // Standard utilities
  self.GetContextArg = function() {
    return {'contextID': this.context.contextID};
  }

  self.GetEngineArg = function() {
    return {'engineID': jscin.ENGINE_ID};
  }

  self.log = function(s) {
    jscin.log(s);
  }

  // Core functions
  self.Commit = function(text) {
    // TODO(hungte) fixme when gen_inp has fixed this.
    if (typeof(text) != typeof('')) {
      text = text[0];
      self.log("croscin.Commit: WARNING: input text is not a simple string.");
    }

    if (text) {
      var arg = self.GetContextArg();
      arg.text = text;
      self.ime_api.commitText(arg);
      self.log("croscin.Commit: value: " + text);
    } else {
      self.log("croscin.Commmit: warning: called with empty string.");
    }
  }

  self.ProcessKeyEvent = function(keyData) {
    self.log("ProcessKeyEvent: " + keyData.key);

    // Currently all of the modules uses key down.
    if (keyData.type != 'keydown') {
      return false;
    }

    var ret = self.im.onKeystroke(self.imctx, keyData);
    self.log(dump_inpinfo(self.imctx));

    switch (ret) {
      case jscin.IMKEY_COMMIT:
        self.log("im.onKeystroke: return IMKEY_COMMIT");
        self.Commit(self.imctx.cch);
        self.UpdateUI();
        return true;

      case jscin.IMKEY_ABSORB:
        self.log("im.onKeystroke: return IMKEY_ABSORB");
        self.UpdateUI();
        return true;

      case jscin.IMKEY_IGNORE:
        self.log("im.onKeystroke: return IMKEY_IGNORE");
        self.UpdateUI();
        return false;
    }

    // default: Unknown return value.
    self.log("croscin.ProcessKeyEvent: Unknown return value: " + ret);
    return false;
  }

  self.SimulateKeyDown = function(key) {
    var keyEvent = {
      'type': 'keydown',
      'key': key,
      'altKey': false,
      'ctrlKey': false,
      'shiftKey': false,
    };
    return self.ProcessKeyEvent(keyEvent);
  }

  self.SetCanditesWindowProperty = function(name, value) {
    self.log("croscin.SetCanditesWindowProperty: set " + name + ": " + value);
    var prop = {};
    var arg = self.GetEngineArg();
    arg['properties'] = prop;
    prop[name] = value;
    self.ime_api.setCandidateWindowProperties(arg);
  }

  self.InitializeUI = function() {
    // Vertical candidates window looks better on ChromeOS.
    self.SetCanditesWindowProperty('vertical', true);
    // CIN tables don't expect cursor in candidates window.
    self.SetCanditesWindowProperty('cursorVisible', false);
    self.SetCanditesWindowProperty('visible', false);

    // Setup menu
    self.InitializeMenu();
  }

  self.UpdateComposition = function(text) {
    var arg = self.GetContextArg();
    self.log("croscin.UpdateComposition: " + text);
    if (text) {
      arg.text = text;
      // Select everything in composition.
      arg.selectionStart = 0;
      arg.selectionEnd = text.length;
      arg.cursor = text.length;
      self.ime_api.setComposition(arg);
    } else {
      self.ime_api.clearComposition(arg);
    }
  }

  self.UpdateCandidates = function(candidate_list, labels) {
    self.log("croscin.UpdateCandidates: elements = " + candidate_list.length +
             ", labels = " + labels);
    // TODO(hungte) set more properties:
    //  auxiliaryText, auxiliaryTextVisible.
    if (candidate_list.length > 0) {
      var arg = self.GetContextArg();
      var candidates = [];
      for (var i = 0; i < candidate_list.length; i++) {
        // TODO(hungte) fix label, annotation
        candidates.push({
          'candidate': candidate_list[i],
          'id': i,
          'label': labels.charAt(i),
        });
      }
      self.log('candidates:');
      self.log(candidates);
      arg.candidates = candidates;
      self.ime_api.setCandidates(arg);
      self.SetCanditesWindowProperty('pageSize', candidate_list.length);
      self.SetCanditesWindowProperty('visible', true);
    } else {
      self.SetCanditesWindowProperty('visible', false);
    }
  }

  self.UpdateUI = function() {
    var imctx = self.imctx;
    // process:
    //  - keystroke
    //  - suggest_skeystroke
    self.UpdateComposition(imctx.keystroke);
    //  - selkey
    //  - mcch
    self.UpdateCandidates(imctx.mcch, imctx.selkey);
    //  - lcch
    //  - cch_publish
  }

  self.ActivateInputMethod = function(name) {
    if (name in jscin.input_methods) {
      self.log("croscin.onMenuItemActivated: Selected: " + name);
      // TODO(hungte) Create new instance only if required.
      self.imctx = {};
      self.im = jscin.create_input_method(name, self.imctx);
      self.current_input_method = name;
      self.InitializeUI();
    } else {
      self.log("croscin.onMenuItemActivated: Invalid item: " + name);
    }
  }

  self.UpdateMenu = function() {
    var menu_items = [];
    for (var i in jscin.input_methods) {
      menu_items.push({
        "id": "ime:" + i,
        "checked": i == self.current_input_method
      });
    }
    var arg = self.GetEngineArg();
    arg['items'] = menu_items;
    self.ime_api.updateMenuItems(arg);
  }

  self.InitializeMenu = function() {
    var menu_items = [];

    for (var i in jscin.input_methods) {
      var label = jscin.input_methods[i]["label"];
      if (!label)
        label = i;
      menu_items.push({
        "id": "ime:" + i,
        "label": label,
        "style": "radio"
      });
    }
    self.log("croscin.InitializeMenu: " + menu_items.length + " items.");

    // Add a separator and options  (Separator does not work yet).
    menu_items.push({"id": "",
                     "style": "separator"});
    menu_items.push({"id": self.kOptionsPage,
                     "label": "Options"});
    var arg = self.GetEngineArg();
    arg['items'] = menu_items;
    self.ime_api.setMenuItems(arg);

    self.UpdateMenu();
  }
};

/**
 * Registers event handlers to the browser.
 */
croscin.IME.prototype.registerEventHandlers = function() {
  /* find out proper ime_api: chrome.input.ime or chrome.experimental.input */
  var ime_api = null;
  if ("input" in chrome && "ime" in chrome.input)
    ime_api = chrome.input.ime;
  else
    ime_api = chrome.experimental.input;
  if ("ime" in ime_api)
    ime_api = ime_api.ime;

  var self = this;
  self.ime_api = ime_api;

  ime_api.onActivate.addListener(function(engineID) {
    self.engineID = engineID;
    self.InitializeUI();
  });

  ime_api.onDeactivated.addListener(function(engineID) {
    self.context = null;
  });

  ime_api.onFocus.addListener(function(context) {
    self.context = context;
    // TODO(hungte) remove this workaround: "onActivate is not called if user
    // reloads extension.
    self.InitializeUI();

    // Calling updateUI here is to carry unfinished composition (preedit) into
    // the new input element.
    self.UpdateUI();
  });

  ime_api.onBlur.addListener(function(contextID) {
    if (!self.context) {
      self.log("croscin.onBlur: WARNING: no existing context.");
      return;
    }
    if (self.context.contextID != contextID) {
      self.log("croscin.onBlur: WARNING: incompatible context.");
      return;
    }
    // TODO(hungte) Uncomment this if we don't want context to be carried when
    // input focus changes.
    // self.SimulateKeyDown('Esc');
    self.context = null;
  });

  ime_api.onKeyEvent.addListener(function(engine, keyData) {
    return self.ProcessKeyEvent(keyData);
  });

  ime_api.onInputContextUpdate.addListener(function(context) {
  });

  ime_api.onCandidateClicked.addListener(
      function(engineID, candidateID, button) {
        self.log("onCandidateClicked: " + candidateID + ", " + button);
        if (button == "left") {
          self.SimulateKeyDown(self.imctx.selkey.charAt(candidateID));
        }
  });

  ime_api.onMenuItemActivated.addListener(function(engineID, name) {
    self.log("croscin.onMenuItemActivated: name=" + name);

    if (name == self.kOptionsPage) {
      var options_url = chrome.extension.getURL("options/options.html");
      chrome.tabs.create({"url": options_url});
    } else if (name.match(/^ime:/)) {
      self.ActivateInputMethod(name.replace(/^ime:/, ''));
    }
  });

  window.on_config_changed = function() {
    // TODO: Reload config
    self.InitializeUI();
  }
};

// Browser loader entry
document.addEventListener(
    'readystatechange',
    function() {
      if (document.readyState === 'complete') {
        new croscin.IME;
      }
    }
)
<|endoftext|>


<commit_before>describe('the palindrome canary test', () => {
  it('shows the infrastructure works', () => {
    true.should.equal(true);
  });

  const isPalindrome = phrase => phrase.split('').reverse().join('') === phrase;

  describe('palindrome should be', () => {
    it('yes for mom', () => {
      isPalindrome('mom').should.equal(true);
    });

    it('no for dude', () => {
      isPalindrome('dude').should.equal(false);
    });

    it('yes for mom mom');
    it('no for mom dad');
    it('no for empty phrase');
    it('no for whitespace only phrase');
  });
});
<commit_msg>tests for phrases with more than 1 word<commit_after>describe('the palindrome canary test', () => {
  it('shows the infrastructure works', () => {
    true.should.equal(true);
  });

  const isPalindrome = phrase => phrase.split('').reverse().join('') === phrase;

  describe('palindrome should be', () => {
    it('yes for mom', () => {
      isPalindrome('mom').should.equal(true);
    });

    it('no for dude', () => {
      isPalindrome('dude').should.equal(false);
    });

    it('yes for mom mom', () => {
      isPalindrome('mom mom').should.equal(true);
    });

    it('no for mom dad', () => {
      isPalindrome('mom dad').should.equal(false);
    });

    it('no for empty phrase');
    it('no for whitespace only phrase');
  });
});
<|endoftext|>


<commit_before>const defaults = require('./defaults');
const assign = require('./assign');
const { removeEles, setStyles, createElement, getPixelRatio, getOffset } = require('./dom-util');

let cxtmenu = function(params){
  let options = assign({}, defaults, params);
  let cy = this;
  let container = cy.container();
  let target;

  let data = {
    options: options,
    handlers: [],
    container: createElement({class: 'cxtmenu'})
  };

  let wrapper = data.container;
  let parent = createElement();
  let canvas = createElement({tag: 'canvas'});
  let commands = [];
  let c2d = canvas.getContext('2d');
  let r = options.menuRadius;
  let containerSize = (r + options.activePadding)*2;
  let activeCommandI;
  let offset;

  container.insertBefore(wrapper, container.firstChild);
  wrapper.appendChild(parent);
  parent.appendChild(canvas);

  setStyles(wrapper, {
    position: 'absolute',
    zIndex: options.zIndex,
    userSelect: 'none',
    pointerEvents: 'none' // prevent events on menu in modern browsers
  });

  // prevent events on menu in legacy browsers
  ['mousedown', 'mousemove', 'mouseup', 'contextmenu'].forEach(evt => {
    wrapper.addEventListener(evt, e => {
      e.preventDefault();

      return false;
    });
  });

  setStyles(parent, {
    display: 'none',
    width: containerSize + 'px',
    height: containerSize + 'px',
    position: 'absolute',
    zIndex: 1,
    marginLeft: - options.activePadding + 'px',
    marginTop: - options.activePadding + 'px',
    userSelect: 'none'
  });

  canvas.width = containerSize;
  canvas.height = containerSize;

  function createMenuItems() {
    removeEles('.cxtmenu-item', parent);
    let dtheta = 2 * Math.PI / (commands.length);
    let theta1 = Math.PI / 2;
    let theta2 = theta1 + dtheta;

    for (let i = 0; i < commands.length; i++) {
      let command = commands[i];

      let midtheta = (theta1 + theta2) / 2;
      let rx1 = 0.66 * r * Math.cos(midtheta);
      let ry1 = 0.66 * r * Math.sin(midtheta);

      let item = createElement({class: 'cxtmenu-item'});
      setStyles(item, {
        color: options.itemColor,
        cursor: 'default',
        display: 'table',
        'text-align': 'center',
        //background: 'red',
        position: 'absolute',
        'text-shadow': '-1px -1px 2px ' + options.itemTextShadowColor + ', 1px -1px 2px ' + options.itemTextShadowColor + ', -1px 1px 2px ' + options.itemTextShadowColor + ', 1px 1px 1px ' + options.itemTextShadowColor,
        left: '50%',
        top: '50%',
        'min-height': (r * 0.66) + 'px',
        width: (r * 0.66) + 'px',
        height: (r * 0.66) + 'px',
        marginLeft: (rx1 - r * 0.33) + 'px',
        marginTop: (-ry1 - r * 0.33) + 'px'
      });

      let content = createElement({class: 'cxtmenu-content'});

      if( command.content instanceof HTMLElement ){
        content.appendChild( command.content );
      } else {
        content.innerHTML = command.content;
      }

      setStyles(content, {
        'width': (r * 0.66) + 'px',
        'height': (r * 0.66) + 'px',
        'vertical-align': 'middle',
        'display': 'table-cell'
      });

      setStyles(content, command.contentStyle || {});

      if (command.disabled === true || command.enabled === false) {
        content.setAttribute('class', 'cxtmenu-content cxtmenu-disabled');
      }

      parent.appendChild(item);
      item.appendChild(content);

      theta1 += dtheta;
      theta2 += dtheta;
    }
  }

  function queueDrawBg( rspotlight ){
    redrawQueue.drawBg = [ rspotlight ];
  }

  function drawBg( rspotlight ){
    rspotlight = rspotlight !== undefined ? rspotlight : rs;

    c2d.globalCompositeOperation = 'source-over';

    c2d.clearRect(0, 0, containerSize, containerSize);

    // draw background items
    c2d.fillStyle = options.fillColor;
    let dtheta = 2*Math.PI/(commands.length);
    let theta1 = Math.PI/2;
    let theta2 = theta1 + dtheta;

    for( let index = 0; index < commands.length; index++ ){
      let command = commands[index];

      if( command.fillColor ){
        c2d.fillStyle = command.fillColor;
      }
      c2d.beginPath();
      c2d.moveTo(r + options.activePadding, r + options.activePadding);
      c2d.arc(r + options.activePadding, r + options.activePadding, r, 2*Math.PI - theta1, 2*Math.PI - theta2, true);
      c2d.closePath();
      c2d.fill();

      theta1 += dtheta;
      theta2 += dtheta;

      c2d.fillStyle = options.fillColor;
    }

    // draw separators between items
    c2d.globalCompositeOperation = 'destination-out';
    c2d.strokeStyle = 'white';
    c2d.lineWidth = options.separatorWidth;
    theta1 = Math.PI/2;
    theta2 = theta1 + dtheta;

    for( let i = 0; i < commands.length; i++ ){
      let rx1 = r * Math.cos(theta1);
      let ry1 = r * Math.sin(theta1);
      c2d.beginPath();
      c2d.moveTo(r + options.activePadding, r + options.activePadding);
      c2d.lineTo(r + options.activePadding + rx1, r + options.activePadding - ry1);
      c2d.closePath();
      c2d.stroke();

      theta1 += dtheta;
      theta2 += dtheta;
    }

    c2d.fillStyle = 'white';
    c2d.globalCompositeOperation = 'destination-out';
    c2d.beginPath();
    c2d.arc(r + options.activePadding, r + options.activePadding, rspotlight + options.spotlightPadding, 0, Math.PI*2, true);
    c2d.closePath();
    c2d.fill();

    c2d.globalCompositeOperation = 'source-over';
  }

  function queueDrawCommands( rx, ry, theta ){
    redrawQueue.drawCommands = [ rx, ry, theta ];
  }

  function drawCommands( rx, ry, theta ){
    let dtheta = 2*Math.PI/(commands.length);
    let theta1 = Math.PI/2;
    let theta2 = theta1 + dtheta;

    theta1 += dtheta * activeCommandI;
    theta2 += dtheta * activeCommandI;

    c2d.fillStyle = options.activeFillColor;
    c2d.strokeStyle = 'black';
    c2d.lineWidth = 1;
    c2d.beginPath();
    c2d.moveTo(r + options.activePadding, r + options.activePadding);
    c2d.arc(r + options.activePadding, r + options.activePadding, r + options.activePadding, 2*Math.PI - theta1, 2*Math.PI - theta2, true);
    c2d.closePath();
    c2d.fill();

    c2d.fillStyle = 'white';
    c2d.globalCompositeOperation = 'destination-out';

    let tx = r + options.activePadding + rx/r*(rs + options.spotlightPadding - options.indicatorSize/4);
    let ty = r + options.activePadding + ry/r*(rs + options.spotlightPadding - options.indicatorSize/4);
    let rot = Math.PI/4 - theta;

    c2d.translate( tx, ty );
    c2d.rotate( rot );

    // clear the indicator
    c2d.beginPath();
    c2d.fillRect(-options.indicatorSize/2, -options.indicatorSize/2, options.indicatorSize, options.indicatorSize);
    c2d.closePath();
    c2d.fill();

    c2d.rotate( -rot );
    c2d.translate( -tx, -ty );

    // c2d.setTransform( 1, 0, 0, 1, 0, 0 );

    // clear the spotlight
    c2d.beginPath();
    c2d.arc(r + options.activePadding, r + options.activePadding, rs + options.spotlightPadding, 0, Math.PI*2, true);
    c2d.closePath();
    c2d.fill();

    c2d.globalCompositeOperation = 'source-over';
  }

  function updatePixelRatio(){
    let pxr = getPixelRatio();
    let w = containerSize;
    let h = containerSize;

    canvas.width = w * pxr;
    canvas.height = h * pxr;

    canvas.style.width = w + 'px';
    canvas.style.height = h + 'px';

    c2d.setTransform( 1, 0, 0, 1, 0, 0 );
    c2d.scale( pxr, pxr );
  }

  let redrawing = true;
  let redrawQueue = {};

  let raf = (
    window.requestAnimationFrame
    || window.webkitRequestAnimationFrame
    || window.mozRequestAnimationFrame
    || window.msRequestAnimationFrame
    || (fn => setTimeout(fn, 16))
  );

  let redraw = function(){
    if( redrawQueue.drawBg ){
      drawBg.apply( null, redrawQueue.drawBg );
    }

    if( redrawQueue.drawCommands ){
      drawCommands.apply( null, redrawQueue.drawCommands );
    }

    redrawQueue = {};

    if( redrawing ){
      raf( redraw );
    }
  };

  // kick off
  updatePixelRatio();
  redraw();

  let ctrx, ctry, rs;

  let bindings = {
    on: function(events, selector, fn){

      let _fn = fn;
      if( selector === 'core'){
        _fn = function( e ){
          if( e.cyTarget === cy || e.target === cy ){ // only if event target is directly core
            return fn.apply( this, [ e ] );
          }
        };
      }

      data.handlers.push({
        events: events,
        selector: selector,
        fn: _fn
      });

      if( selector === 'core' ){
        cy.on(events, _fn);
      } else {
        cy.on(events, selector, _fn);
      }

      return this;
    }
  };

  function addEventListeners(){
    let grabbable;
    let inGesture = false;
    let dragHandler;
    let zoomEnabled;
    let panEnabled;
    let boxEnabled;
    let gestureStartEvent;

    let restoreZoom = function(){
      if( zoomEnabled ){
        cy.userZoomingEnabled( true );
      }
    };

    let restoreGrab = function(){
      if( grabbable ){
        target.grabify();
      }
    };

    let restorePan = function(){
      if( panEnabled ){
        cy.userPanningEnabled( true );
      }
    };

    let restoreBoxSeln = function(){
      if( boxEnabled ){
        cy.boxSelectionEnabled( true );
      }
    };

    let restoreGestures = function(){
      restoreGrab();
      restoreZoom();
      restorePan();
      restoreBoxSeln();
    };

    window.addEventListener('resize', updatePixelRatio);

    bindings
      .on('resize', function(){
        updatePixelRatio();
      })

      .on(options.openMenuEvents, options.selector, function(e){
        target = this; // Remember which node the context menu is for
        let ele = this;
        let isCy = this === cy;

        if (inGesture) {
          parent.style.display = 'none';

          inGesture = false;

          restoreGestures();
        }

        if( typeof options.commands === 'function' ){
          const res = options.commands(target);
          if( res.then ){
            res.then(_commands => {
              commands = _commands;
              openMenu();
            })
          } else {
            commands = res;
            openMenu();
          }
        } else {
          commands = options.commands;
          openMenu();
        }

        function openMenu(){
          if( !commands || commands.length === 0 ){ return; }

          zoomEnabled = cy.userZoomingEnabled();
          cy.userZoomingEnabled( false );

          panEnabled = cy.userPanningEnabled();
          cy.userPanningEnabled( false );

          boxEnabled = cy.boxSelectionEnabled();
          cy.boxSelectionEnabled( false );

          grabbable = target.grabbable &&  target.grabbable();
          if( grabbable ){
            target.ungrabify();
          }

          let rp, rw, rh;
          if( !isCy && ele.isNode() && !ele.isParent() && !options.atMouse ){
            rp = ele.renderedPosition();
            rw = ele.renderedWidth();
            rh = ele.renderedHeight();
          } else {
            rp = e.renderedPosition || e.cyRenderedPosition;
            rw = 1;
            rh = 1;
          }

          offset = getOffset(container);

          ctrx = rp.x;
          ctry = rp.y;

          createMenuItems();

          setStyles(parent, {
            display: 'block',
            left: (rp.x - r) + 'px',
            top: (rp.y - r) + 'px'
          });

          rs = Math.max(rw, rh)/2;
          rs = Math.max(rs, options.minSpotlightRadius);
          rs = Math.min(rs, options.maxSpotlightRadius);

          queueDrawBg();

          activeCommandI = undefined;

          inGesture = true;
          gestureStartEvent = e;
        }
      })

      .on('cxtdrag tapdrag', options.selector, dragHandler = function(e){

        if( !inGesture ){ return; }

        let origE = e.originalEvent;
        let isTouch = origE.touches && origE.touches.length > 0;

        let pageX = (isTouch ? origE.touches[0].pageX : origE.pageX) - window.scrollX;
        let pageY = (isTouch ? origE.touches[0].pageY : origE.pageY) - window.scrollY;

        activeCommandI = undefined;

        let dx = pageX - offset.left - ctrx;
        let dy = pageY - offset.top - ctry;

        if( dx === 0 ){ dx = 0.01; }

        let d = Math.sqrt( dx*dx + dy*dy );
        let cosTheta = (dy*dy - d*d - dx*dx)/(-2 * d * dx);
        let theta = Math.acos( cosTheta );

        if( d < rs + options.spotlightPadding ){
          queueDrawBg();
          return;
        }

        queueDrawBg();

        let rx = dx*r / d;
        let ry = dy*r / d;

        if( dy > 0 ){
          theta = Math.PI + Math.abs(theta - Math.PI);
        }

        let dtheta = 2*Math.PI/(commands.length);
        let theta1 = Math.PI/2;
        let theta2 = theta1 + dtheta;

        for( let i = 0; i < commands.length; i++ ){
          let command = commands[i];

          let inThisCommand = theta1 <= theta && theta <= theta2
            || theta1 <= theta + 2*Math.PI && theta + 2*Math.PI <= theta2;

          if( command.disabled === true || command.enabled === false ){
            inThisCommand = false;
          }

          if( inThisCommand ){
            activeCommandI = i;
            break;
          }

          theta1 += dtheta;
          theta2 += dtheta;
        }

        queueDrawCommands( rx, ry, theta );
      })

      .on('tapdrag', dragHandler)

      .on('cxttapend tapend', function(){
        parent.style.display = 'none';

        if( activeCommandI !== undefined ){
          let select = commands[ activeCommandI ].select;

          if( select ){
            select.apply( target, [target, gestureStartEvent] );
            activeCommandI = undefined;
          }
        }

        inGesture = false;

        restoreGestures();
      })
    ;
  }

  function removeEventListeners(){
    let handlers = data.handlers;

    for( let i = 0; i < handlers.length; i++ ){
      let h = handlers[i];

      if( h.selector === 'core' ){
        cy.off(h.events, h.fn);
      } else {
        cy.off(h.events, h.selector, h.fn);
      }
    }

    window.removeEventListener('resize', updatePixelRatio);
  }

  function destroyInstance(){
    redrawing = false;

    removeEventListeners();

    wrapper.remove();
  }

  addEventListeners();

  return {
    destroy: function(){
      destroyInstance();
    }
  };

};

module.exports = cxtmenu;
<commit_msg>fix issue #91<commit_after>const defaults = require('./defaults');
const assign = require('./assign');
const { removeEles, setStyles, createElement, getPixelRatio, getOffset } = require('./dom-util');

let cxtmenu = function(params){
  let options = assign({}, defaults, params);
  let cy = this;
  let container = cy.container();
  let target;

  let data = {
    options: options,
    handlers: [],
    container: createElement({class: 'cxtmenu'})
  };

  let wrapper = data.container;
  let parent = createElement();
  let canvas = createElement({tag: 'canvas'});
  let commands = [];
  let c2d = canvas.getContext('2d');
  let r = options.menuRadius;
  let containerSize = (r + options.activePadding)*2;
  let activeCommandI;
  let offset;

  container.insertBefore(wrapper, container.firstChild);
  wrapper.appendChild(parent);
  parent.appendChild(canvas);

  setStyles(wrapper, {
    position: 'absolute',
    zIndex: options.zIndex,
    userSelect: 'none',
    pointerEvents: 'none' // prevent events on menu in modern browsers
  });

  // prevent events on menu in legacy browsers
  ['mousedown', 'mousemove', 'mouseup', 'contextmenu'].forEach(evt => {
    wrapper.addEventListener(evt, e => {
      e.preventDefault();

      return false;
    });
  });

  setStyles(parent, {
    display: 'none',
    width: containerSize + 'px',
    height: containerSize + 'px',
    position: 'absolute',
    zIndex: 1,
    marginLeft: - options.activePadding + 'px',
    marginTop: - options.activePadding + 'px',
    userSelect: 'none'
  });

  canvas.width = containerSize;
  canvas.height = containerSize;

  function createMenuItems() {
    removeEles('.cxtmenu-item', parent);
    let dtheta = 2 * Math.PI / (commands.length);
    let theta1 = Math.PI / 2;
    let theta2 = theta1 + dtheta;

    for (let i = 0; i < commands.length; i++) {
      let command = commands[i];

      let midtheta = (theta1 + theta2) / 2;
      let rx1 = 0.66 * r * Math.cos(midtheta);
      let ry1 = 0.66 * r * Math.sin(midtheta);

      let item = createElement({class: 'cxtmenu-item'});
      setStyles(item, {
        color: options.itemColor,
        cursor: 'default',
        display: 'table',
        'text-align': 'center',
        //background: 'red',
        position: 'absolute',
        'text-shadow': '-1px -1px 2px ' + options.itemTextShadowColor + ', 1px -1px 2px ' + options.itemTextShadowColor + ', -1px 1px 2px ' + options.itemTextShadowColor + ', 1px 1px 1px ' + options.itemTextShadowColor,
        left: '50%',
        top: '50%',
        'min-height': (r * 0.66) + 'px',
        width: (r * 0.66) + 'px',
        height: (r * 0.66) + 'px',
        marginLeft: (rx1 - r * 0.33) + 'px',
        marginTop: (-ry1 - r * 0.33) + 'px'
      });

      let content = createElement({class: 'cxtmenu-content'});

      if( command.content instanceof HTMLElement ){
        content.appendChild( command.content );
      } else {
        content.innerHTML = command.content;
      }

      setStyles(content, {
        'width': (r * 0.66) + 'px',
        'height': (r * 0.66) + 'px',
        'vertical-align': 'middle',
        'display': 'table-cell'
      });

      setStyles(content, command.contentStyle || {});

      if (command.disabled === true || command.enabled === false) {
        content.setAttribute('class', 'cxtmenu-content cxtmenu-disabled');
      }

      parent.appendChild(item);
      item.appendChild(content);

      theta1 += dtheta;
      theta2 += dtheta;
    }
  }

  function queueDrawBg( rspotlight ){
    redrawQueue.drawBg = [ rspotlight ];
  }

  function drawBg( rspotlight ){
    rspotlight = rspotlight !== undefined ? rspotlight : rs;

    c2d.globalCompositeOperation = 'source-over';

    c2d.clearRect(0, 0, containerSize, containerSize);

    // draw background items
    c2d.fillStyle = options.fillColor;
    let dtheta = 2*Math.PI/(commands.length);
    let theta1 = Math.PI/2;
    let theta2 = theta1 + dtheta;

    for( let index = 0; index < commands.length; index++ ){
      let command = commands[index];

      if( command.fillColor ){
        c2d.fillStyle = command.fillColor;
      }
      c2d.beginPath();
      c2d.moveTo(r + options.activePadding, r + options.activePadding);
      c2d.arc(r + options.activePadding, r + options.activePadding, r, 2*Math.PI - theta1, 2*Math.PI - theta2, true);
      c2d.closePath();
      c2d.fill();

      theta1 += dtheta;
      theta2 += dtheta;

      c2d.fillStyle = options.fillColor;
    }

    // draw separators between items
    c2d.globalCompositeOperation = 'destination-out';
    c2d.strokeStyle = 'white';
    c2d.lineWidth = options.separatorWidth;
    theta1 = Math.PI/2;
    theta2 = theta1 + dtheta;

    for( let i = 0; i < commands.length; i++ ){
      let rx1 = r * Math.cos(theta1);
      let ry1 = r * Math.sin(theta1);
      c2d.beginPath();
      c2d.moveTo(r + options.activePadding, r + options.activePadding);
      c2d.lineTo(r + options.activePadding + rx1, r + options.activePadding - ry1);
      c2d.closePath();
      c2d.stroke();

      theta1 += dtheta;
      theta2 += dtheta;
    }

    c2d.fillStyle = 'white';
    c2d.globalCompositeOperation = 'destination-out';
    c2d.beginPath();
    c2d.arc(r + options.activePadding, r + options.activePadding, rspotlight + options.spotlightPadding, 0, Math.PI*2, true);
    c2d.closePath();
    c2d.fill();

    c2d.globalCompositeOperation = 'source-over';
  }

  function queueDrawCommands( rx, ry, theta ){
    redrawQueue.drawCommands = [ rx, ry, theta ];
  }

  function drawCommands( rx, ry, theta ){
    let dtheta = 2*Math.PI/(commands.length);
    let theta1 = Math.PI/2;
    let theta2 = theta1 + dtheta;

    theta1 += dtheta * activeCommandI;
    theta2 += dtheta * activeCommandI;

    c2d.fillStyle = options.activeFillColor;
    c2d.strokeStyle = 'black';
    c2d.lineWidth = 1;
    c2d.beginPath();
    c2d.moveTo(r + options.activePadding, r + options.activePadding);
    c2d.arc(r + options.activePadding, r + options.activePadding, r + options.activePadding, 2*Math.PI - theta1, 2*Math.PI - theta2, true);
    c2d.closePath();
    c2d.fill();

    c2d.fillStyle = 'white';
    c2d.globalCompositeOperation = 'destination-out';

    let tx = r + options.activePadding + rx/r*(rs + options.spotlightPadding - options.indicatorSize/4);
    let ty = r + options.activePadding + ry/r*(rs + options.spotlightPadding - options.indicatorSize/4);
    let rot = Math.PI/4 - theta;

    c2d.translate( tx, ty );
    c2d.rotate( rot );

    // clear the indicator
    c2d.beginPath();
    c2d.fillRect(-options.indicatorSize/2, -options.indicatorSize/2, options.indicatorSize, options.indicatorSize);
    c2d.closePath();
    c2d.fill();

    c2d.rotate( -rot );
    c2d.translate( -tx, -ty );

    // c2d.setTransform( 1, 0, 0, 1, 0, 0 );

    // clear the spotlight
    c2d.beginPath();
    c2d.arc(r + options.activePadding, r + options.activePadding, rs + options.spotlightPadding, 0, Math.PI*2, true);
    c2d.closePath();
    c2d.fill();

    c2d.globalCompositeOperation = 'source-over';
  }

  function updatePixelRatio(){
    let pxr = getPixelRatio();
    let w = containerSize;
    let h = containerSize;

    canvas.width = w * pxr;
    canvas.height = h * pxr;

    canvas.style.width = w + 'px';
    canvas.style.height = h + 'px';

    c2d.setTransform( 1, 0, 0, 1, 0, 0 );
    c2d.scale( pxr, pxr );
  }

  let redrawing = true;
  let redrawQueue = {};

  let raf = (
    window.requestAnimationFrame
    || window.webkitRequestAnimationFrame
    || window.mozRequestAnimationFrame
    || window.msRequestAnimationFrame
    || (fn => setTimeout(fn, 16))
  );

  let redraw = function(){
    if( redrawQueue.drawBg ){
      drawBg.apply( null, redrawQueue.drawBg );
    }

    if( redrawQueue.drawCommands ){
      drawCommands.apply( null, redrawQueue.drawCommands );
    }

    redrawQueue = {};

    if( redrawing ){
      raf( redraw );
    }
  };

  // kick off
  updatePixelRatio();
  redraw();

  let ctrx, ctry, rs;

  let bindings = {
    on: function(events, selector, fn){

      let _fn = fn;
      if( selector === 'core'){
        _fn = function( e ){
          if( e.cyTarget === cy || e.target === cy ){ // only if event target is directly core
            return fn.apply( this, [ e ] );
          }
        };
      }

      data.handlers.push({
        events: events,
        selector: selector,
        fn: _fn
      });

      if( selector === 'core' ){
        cy.on(events, _fn);
      } else {
        cy.on(events, selector, _fn);
      }

      return this;
    }
  };

  function addEventListeners(){
    let grabbable;
    let inGesture = false;
    let dragHandler;
    let zoomEnabled;
    let panEnabled;
    let boxEnabled;
    let gestureStartEvent;

    let restoreZoom = function(){
      if( zoomEnabled ){
        cy.userZoomingEnabled( true );
      }
    };

    let restoreGrab = function(){
      if( grabbable ){
        target.grabify();
      }
    };

    let restorePan = function(){
      if( panEnabled ){
        cy.userPanningEnabled( true );
      }
    };

    let restoreBoxSeln = function(){
      if( boxEnabled ){
        cy.boxSelectionEnabled( true );
      }
    };

    let restoreGestures = function(){
      restoreGrab();
      restoreZoom();
      restorePan();
      restoreBoxSeln();
    };

    window.addEventListener('resize', updatePixelRatio);

    bindings
      .on('resize', function(){
        updatePixelRatio();
      })

      .on(options.openMenuEvents, options.selector, function(e){
        target = this; // Remember which node the context menu is for
        let ele = this;
        let isCy = this === cy;

        if (inGesture) {
          parent.style.display = 'none';

          inGesture = false;

          restoreGestures();
        }

        if( typeof options.commands === 'function' ){
          const res = options.commands(target);
          if( res.then ){
            res.then(_commands => {
              commands = _commands;
              openMenu();
            })
          } else {
            commands = res;
            openMenu();
          }
        } else {
          commands = options.commands;
          openMenu();
        }

        function openMenu(){
          if( !commands || commands.length === 0 ){ return; }

          zoomEnabled = cy.userZoomingEnabled();
          cy.userZoomingEnabled( false );

          panEnabled = cy.userPanningEnabled();
          cy.userPanningEnabled( false );

          boxEnabled = cy.boxSelectionEnabled();
          cy.boxSelectionEnabled( false );

          grabbable = target.grabbable &&  target.grabbable();
          if( grabbable ){
            target.ungrabify();
          }

          let rp, rw, rh;
          if( !isCy && ele.isNode() && !ele.isParent() && !options.atMouse ){
            rp = ele.renderedPosition();
            rw = ele.renderedWidth();
            rh = ele.renderedHeight();
          } else {
            rp = e.renderedPosition || e.cyRenderedPosition;
            rw = 1;
            rh = 1;
          }

          offset = getOffset(container);

          ctrx = rp.x;
          ctry = rp.y;

          createMenuItems();

          setStyles(parent, {
            display: 'block',
            left: (rp.x - r) + 'px',
            top: (rp.y - r) + 'px'
          });

          rs = Math.max(rw, rh)/2;
          rs = Math.max(rs, options.minSpotlightRadius);
          rs = Math.min(rs, options.maxSpotlightRadius);

          queueDrawBg();

          activeCommandI = undefined;

          inGesture = true;
          gestureStartEvent = e;
        }
      })

      .on('cxtdrag tapdrag', options.selector, dragHandler = function(e){

        if( !inGesture ){ return; }

        let origE = e.originalEvent;
        let isTouch = origE.touches && origE.touches.length > 0;

        let pageX = (isTouch ? origE.touches[0].pageX : origE.pageX) - window.pageXOffset;
        let pageY = (isTouch ? origE.touches[0].pageY : origE.pageY) - window.pageYOffset;

        activeCommandI = undefined;

        let dx = pageX - offset.left - ctrx;
        let dy = pageY - offset.top - ctry;

        if( dx === 0 ){ dx = 0.01; }

        let d = Math.sqrt( dx*dx + dy*dy );
        let cosTheta = (dy*dy - d*d - dx*dx)/(-2 * d * dx);
        let theta = Math.acos( cosTheta );

        if( d < rs + options.spotlightPadding ){
          queueDrawBg();
          return;
        }

        queueDrawBg();

        let rx = dx*r / d;
        let ry = dy*r / d;

        if( dy > 0 ){
          theta = Math.PI + Math.abs(theta - Math.PI);
        }

        let dtheta = 2*Math.PI/(commands.length);
        let theta1 = Math.PI/2;
        let theta2 = theta1 + dtheta;

        for( let i = 0; i < commands.length; i++ ){
          let command = commands[i];

          let inThisCommand = theta1 <= theta && theta <= theta2
            || theta1 <= theta + 2*Math.PI && theta + 2*Math.PI <= theta2;

          if( command.disabled === true || command.enabled === false ){
            inThisCommand = false;
          }

          if( inThisCommand ){
            activeCommandI = i;
            break;
          }

          theta1 += dtheta;
          theta2 += dtheta;
        }

        queueDrawCommands( rx, ry, theta );
      })

      .on('tapdrag', dragHandler)

      .on('cxttapend tapend', function(){
        parent.style.display = 'none';

        if( activeCommandI !== undefined ){
          let select = commands[ activeCommandI ].select;

          if( select ){
            select.apply( target, [target, gestureStartEvent] );
            activeCommandI = undefined;
          }
        }

        inGesture = false;

        restoreGestures();
      })
    ;
  }

  function removeEventListeners(){
    let handlers = data.handlers;

    for( let i = 0; i < handlers.length; i++ ){
      let h = handlers[i];

      if( h.selector === 'core' ){
        cy.off(h.events, h.fn);
      } else {
        cy.off(h.events, h.selector, h.fn);
      }
    }

    window.removeEventListener('resize', updatePixelRatio);
  }

  function destroyInstance(){
    redrawing = false;

    removeEventListeners();

    wrapper.remove();
  }

  addEventListeners();

  return {
    destroy: function(){
      destroyInstance();
    }
  };

};

module.exports = cxtmenu;
<|endoftext|>


<commit_before>var db = require( '../config/db' );
var helpers = require( '../config/helpers' );
var Sequelize = require( 'sequelize' );
var User = require( '../users/users' );
var Session = require( '../sessions/sessions' );

var Session_User = db.define( 'sessions_users', {
	user_id: {
    type: Sequelize.INTEGER,
    unique: 'session_user_idx'
  },
	session_id: {
    type: Sequelize.INTEGER,
    unique: 'session_user_idx'
  }
} );

Session_User.sync().then( function(){
  console.log("sessions_users table created");
} )
.catch( function( err ){
  console.error(err);
} );

Session_User.belongsTo( User, {foreignKey: 'user_id'} );
Session_User.belongsTo( Session, {foreignKey: 'session_id'} );

Session_User.getSessionUserBySessionIdAndUserId = function( sessionID, userID ) {
  return Session_User.findOne({where: {session_id: sessionID, user_id: userID} })
    .catch( function( err ) {
      helpers.errorLogger( err );
    });
};

Session_User.countUsersInOneSession = function( sessionID ) {
  /* STUB FOR TESTING, REMOVE WHEN THIS FUNCTION IS IMPLEMENTED */
  return {
    then: function( resolve ) {
      if( sessionID == 1 ) {
        resolve( 2 );
      } else {
        resolve( 0 );
      }
    }
  }
  /* END STUB */
};

module.exports = Session_User;
<commit_msg>Refactor stub into real query<commit_after>var db = require( '../config/db' );
var helpers = require( '../config/helpers' );
var Sequelize = require( 'sequelize' );
var User = require( '../users/users' );
var Session = require( '../sessions/sessions' );

var Session_User = db.define( 'sessions_users', {
	user_id: {
    type: Sequelize.INTEGER,
    unique: 'session_user_idx'
  },
	session_id: {
    type: Sequelize.INTEGER,
    unique: 'session_user_idx'
  }
} );

Session_User.sync().then( function(){
  console.log("sessions_users table created");
} )
.catch( function( err ){
  console.error(err);
} );

Session_User.belongsTo( User, {foreignKey: 'user_id'} );
Session_User.belongsTo( Session, {foreignKey: 'session_id'} );

Session_User.getSessionUserBySessionIdAndUserId = function( sessionID, userID ) {
  return Session_User.findOne({where: {session_id: sessionID, user_id: userID} })
    .catch( function( err ) {
      helpers.errorLogger( err );
    });
};

Session_User.countUsersInOneSession = function( sessionID ) {
  return Session_User.count( { where: { id: sessionId } } )
  .catch( function( err ) {
    helpers.errorLogger( err );
  });
};

module.exports = Session_User;
<|endoftext|>


<commit_before>/*

  arg.js - v1
  JavaScript URL argument processing once and for all.

  by Mat Ryer and Ryan Quinn
  Copyright (c) 2013 Stretchr, Inc.

  Please consider promoting this project if you find it useful.

  Permission is hereby granted, free of charge, to any person obtaining a copy of this
  software and associated documentation files (the "Software"), to deal in the Software
  without restriction, including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  to whom the Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all copies
  or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.

*/

/**
 * MakeArg makes the Arg namespace.
 * var Arg = MakeArg();
 */
var MakeArg = function(){

  /** @namespace
   */
  var Arg = {
    version: "1.0.1"
  };

  /**
   * Parses the arg string into an Arg.Arg object.
   */
  Arg.parse = function(s){
    if (!s) return {};
    s = Arg._cleanParamStr(s);
    var obj = {};
    var pairs = s.split("&");
    for (var pi in pairs) {
      var kvsegs = pairs[pi].split("=");
      var key = decodeURIComponent(kvsegs[0]), val = decodeURIComponent(kvsegs[1]);
      Arg._access(obj, key, val, true);
    }
    return obj;
  };

  /*
   * recrusively, deeply accesses an object.
   */
  Arg._access = function(current, selector, setValue, shouldSet){

    // split the selector by the first dot
    var thisSel = selector;
    var dotPos = selector.indexOf(".");
    var arrPos = selector.indexOf("[");

    if (dotPos > -1) {
      thisSel = selector.substr(0, dotPos);
      var nextSel = selector.substr(dotPos+1);
    } else if (arrPos == -1) {
      return shouldSet ? (current[selector] = setValue) : current[selector];
    }

    arrPos = thisSel.indexOf("[");

    if ((arrPos > -1 && arrPos < dotPos) || (arrPos > -1 && dotPos == -1)) {

      var arrName = thisSel.substr(0, thisSel.indexOf("["));
      var b = thisSel.split("[")[1];
      var index = parseInt(b.substr(0,b.length-1));

      current = (current[arrName] = current[arrName] || []);
      current = (current[index] = current[index] || {});

    } else {
      if (!current[thisSel]) {
        current[thisSel] = {};
      }
      current = current[thisSel] || {};
    }

    if (nextSel)
      return Arg._access(current, nextSel, setValue, shouldSet);
    else
      return current;

  };

  /**
   * Turns the specified object into a URL parameter string.
   */
  Arg.stringify = function(obj, keyPrefix) {

    switch (typeof(obj)) {
    case "object":
      var segs = [];
      var thisKey;
      for (var key in obj) {

        if (!obj.hasOwnProperty(key)) continue;
        var val = obj[key];

        if (typeof(key) === "undefined" || key.length === 0 || typeof(val) === "undefined") continue;

        thisKey = keyPrefix ? keyPrefix+"."+key : key;

        if (typeof obj.length !== "undefined") {
          thisKey = keyPrefix ? keyPrefix+"["+key+"]" : key;
        }

        if (typeof val === "object") {
          segs.push(Arg.stringify(val, thisKey));
        } else {
          segs.push(encodeURIComponent(thisKey)+"="+encodeURIComponent(val));
        }

      }
      return segs.join("&");
    }

    return encodeURIComponent(obj);

  };

  /**
   * Generates a URL with the given parameters.
   * (object) = A URL to the current page with the specified parameters.
   * (path, object) = A URL to the specified path, with the object of parameters.
   * (path, object, object) = A URL to the specified path with the first object as query parameters,
   * and the second object as hash parameters.
   */
  Arg.url = function(){

    var sep = (Arg.urlUseHash ? Arg.hashQuerySeperator : Arg.querySeperator);
    var segs = [location.pathname, sep];

    switch (arguments.length) {
    case 1: // Arg.url(params)
      segs.push(Arg.stringify(arguments[0]));
      break;
    case 2: // Arg.url(path, params)
      segs[0] = arguments[0];
      segs.push(Arg.stringify(arguments[1]));
      break;
    case 3: // Arg.url(path, query, hash)
      segs[0] = arguments[0];
      segs[1] = Arg.querySeperator;
      segs.push(Arg.stringify(arguments[1]));
      segs.push(Arg.hashQuerySeperator);
      segs.push(Arg.stringify(arguments[2]));
    }

    var s = segs.join("");

    // trim off sep if it's the last thing
    if (s.indexOf(sep) == s.length - sep.length) {
      s = s.substr(0, s.length - sep.length);
    }

    return s;

  };

  /** urlUseHash tells the Arg.url method to always put the parameters in the hash. */
  Arg.urlUseHash = false;

  /** The string that seperates the path and query parameters. */
  Arg.querySeperator = "?";

  /** The string that seperates the path or query, and the hash property. */
  Arg.hashSeperator = "#";

  /** The string that seperates the the path or query, and the hash query parameters. */
  Arg.hashQuerySeperator = "#?";

  /**
   * Gets all parameters from the current URL.
   */
  Arg.all = function(){
    var merged = Arg.parse(Arg.querystring() + "&" + Arg.hashstring());
    return Arg._all ? Arg._all : Arg._all = merged;
  };

  /**
   * Gets a parameter from the URL.
   */
  Arg.get = function(selector, def){
    var val = Arg._access(Arg.all(), selector);
    return typeof(val) === "undefined" ? def : val;
  };

  /**
   * Gets the query string parameters from the current URL.
   */
  Arg.query = function(){
    return Arg._query ? Arg._query : Arg._query = Arg.parse(Arg.querystring());
  };

  /**
   * Gets the hash string parameters from the current URL.
   */
  Arg.hash = function(){
    return Arg._hash ? Arg._hash : Arg._hash = Arg.parse(Arg.hashstring());
  };

  /**
   * Gets the query string from the URL (the part after the ?).
   */
  Arg.querystring = function(){
    return Arg._cleanParamStr(location.search);
  };

  /**
   * Gets the hash param string from the URL (the part after the #).
   */
  Arg.hashstring = function(){
    return Arg._cleanParamStr(location.hash)
  };

  /*
   * Cleans the URL parameter string stripping # and ? from the beginning.
   */
  Arg._cleanParamStr = function(s){
    while (s.indexOf(Arg.hashSeperator) == 0 || s.indexOf(Arg.querySeperator) == 0) {
      s = s.substr(1);
    }
    return s;
  };

  /**
   * Merges all the arguments into a new object.
   */
  Arg.merge = function(){
    var all = {};
    for (var ai in arguments)
      for (var k in arguments[ai])
        all[k] = arguments[ai][k];
    return all;
  };

  return Arg;

};

/** @namespace
 * Arg is the root namespace for all arg.js functionality.
 */
var Arg = MakeArg();
<commit_msg>Update arg.js<commit_after>/*

  arg.js - v1
  JavaScript URL argument processing once and for all.

  by Mat Ryer and Ryan Quinn
  Copyright (c) 2013 Stretchr, Inc.

  Please consider promoting this project if you find it useful.

  Permission is hereby granted, free of charge, to any person obtaining a copy of this
  software and associated documentation files (the "Software"), to deal in the Software
  without restriction, including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  to whom the Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all copies
  or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.

*/

/**
 * MakeArg makes the Arg namespace.
 * var Arg = MakeArg();
 */
var MakeArg = function(){

  /** @namespace
   */
  var Arg = {
    version: "1.0.1"
  };

  /**
   * Parses the arg string into an Arg.Arg object.
   */
  Arg.parse = function(s){
    if (!s) return {};
    s = Arg._cleanParamStr(s);
    var obj = {};
    var pairs = s.split("&");
    for (var pi in pairs) {
      var kvsegs = pairs[pi].split("=");
      var key = decodeURIComponent(kvsegs[0]), val = decodeURIComponent(kvsegs[1]);
      Arg._access(obj, key, val, true);
    }
    return obj;
  };

  /*
   * recursively, deeply accesses an object.
   */
  Arg._access = function(current, selector, setValue, shouldSet){

    // split the selector by the first dot
    var thisSel = selector;
    var dotPos = selector.indexOf(".");
    var arrPos = selector.indexOf("[");

    if (dotPos > -1) {
      thisSel = selector.substr(0, dotPos);
      var nextSel = selector.substr(dotPos+1);
    } else if (arrPos == -1) {
      return shouldSet ? (current[selector] = setValue) : current[selector];
    }

    arrPos = thisSel.indexOf("[");

    if ((arrPos > -1 && arrPos < dotPos) || (arrPos > -1 && dotPos == -1)) {

      var arrName = thisSel.substr(0, thisSel.indexOf("["));
      var b = thisSel.split("[")[1];
      var index = parseInt(b.substr(0,b.length-1));

      current = (current[arrName] = current[arrName] || []);
      current = (current[index] = current[index] || {});

    } else {
      if (!current[thisSel]) {
        current[thisSel] = {};
      }
      current = current[thisSel] || {};
    }

    if (nextSel)
      return Arg._access(current, nextSel, setValue, shouldSet);
    else
      return current;

  };

  /**
   * Turns the specified object into a URL parameter string.
   */
  Arg.stringify = function(obj, keyPrefix) {

    switch (typeof(obj)) {
    case "object":
      var segs = [];
      var thisKey;
      for (var key in obj) {

        if (!obj.hasOwnProperty(key)) continue;
        var val = obj[key];

        if (typeof(key) === "undefined" || key.length === 0 || typeof(val) === "undefined") continue;

        thisKey = keyPrefix ? keyPrefix+"."+key : key;

        if (typeof obj.length !== "undefined") {
          thisKey = keyPrefix ? keyPrefix+"["+key+"]" : key;
        }

        if (typeof val === "object") {
          segs.push(Arg.stringify(val, thisKey));
        } else {
          segs.push(encodeURIComponent(thisKey)+"="+encodeURIComponent(val));
        }

      }
      return segs.join("&");
    }

    return encodeURIComponent(obj);

  };

  /**
   * Generates a URL with the given parameters.
   * (object) = A URL to the current page with the specified parameters.
   * (path, object) = A URL to the specified path, with the object of parameters.
   * (path, object, object) = A URL to the specified path with the first object as query parameters,
   * and the second object as hash parameters.
   */
  Arg.url = function(){

    var sep = (Arg.urlUseHash ? Arg.hashQuerySeperator : Arg.querySeperator);
    var segs = [location.pathname, sep];

    switch (arguments.length) {
    case 1: // Arg.url(params)
      segs.push(Arg.stringify(arguments[0]));
      break;
    case 2: // Arg.url(path, params)
      segs[0] = arguments[0];
      segs.push(Arg.stringify(arguments[1]));
      break;
    case 3: // Arg.url(path, query, hash)
      segs[0] = arguments[0];
      segs[1] = Arg.querySeperator;
      segs.push(Arg.stringify(arguments[1]));
      segs.push(Arg.hashQuerySeperator);
      segs.push(Arg.stringify(arguments[2]));
    }

    var s = segs.join("");

    // trim off sep if it's the last thing
    if (s.indexOf(sep) == s.length - sep.length) {
      s = s.substr(0, s.length - sep.length);
    }

    return s;

  };

  /** urlUseHash tells the Arg.url method to always put the parameters in the hash. */
  Arg.urlUseHash = false;

  /** The string that seperates the path and query parameters. */
  Arg.querySeperator = "?";

  /** The string that seperates the path or query, and the hash property. */
  Arg.hashSeperator = "#";

  /** The string that seperates the the path or query, and the hash query parameters. */
  Arg.hashQuerySeperator = "#?";

  /**
   * Gets all parameters from the current URL.
   */
  Arg.all = function(){
    var merged = Arg.parse(Arg.querystring() + "&" + Arg.hashstring());
    return Arg._all ? Arg._all : Arg._all = merged;
  };

  /**
   * Gets a parameter from the URL.
   */
  Arg.get = function(selector, def){
    var val = Arg._access(Arg.all(), selector);
    return typeof(val) === "undefined" ? def : val;
  };

  /**
   * Gets the query string parameters from the current URL.
   */
  Arg.query = function(){
    return Arg._query ? Arg._query : Arg._query = Arg.parse(Arg.querystring());
  };

  /**
   * Gets the hash string parameters from the current URL.
   */
  Arg.hash = function(){
    return Arg._hash ? Arg._hash : Arg._hash = Arg.parse(Arg.hashstring());
  };

  /**
   * Gets the query string from the URL (the part after the ?).
   */
  Arg.querystring = function(){
    return Arg._cleanParamStr(location.search);
  };

  /**
   * Gets the hash param string from the URL (the part after the #).
   */
  Arg.hashstring = function(){
    return Arg._cleanParamStr(location.hash)
  };

  /*
   * Cleans the URL parameter string stripping # and ? from the beginning.
   */
  Arg._cleanParamStr = function(s){
    while (s.indexOf(Arg.hashSeperator) == 0 || s.indexOf(Arg.querySeperator) == 0) {
      s = s.substr(1);
    }
    return s;
  };

  /**
   * Merges all the arguments into a new object.
   */
  Arg.merge = function(){
    var all = {};
    for (var ai in arguments)
      for (var k in arguments[ai])
        all[k] = arguments[ai][k];
    return all;
  };

  return Arg;

};

/** @namespace
 * Arg is the root namespace for all arg.js functionality.
 */
var Arg = MakeArg();
<|endoftext|>


<commit_before>/* App Module */
var config = {
    localhost: 'http://localhost:8080'
};

var kanbanApp = angular.module('kanbanApp', [
    'ngRoute', 'ngAnimate', 'ui.bootstrap',
    'ui.sortable',
    'xeditable',
    'LocalStorageModule',
    'ui.router',
    'mgcrea.ngStrap'
]);

kanbanApp.config(['$routeProvider', '$httpProvider', 'localStorageServiceProvider', '$stateProvider', '$urlRouterProvider',
    function ($routeProvider, $httpProvider, localStorageServiceProvider, $stateProvider, $urlRouterProvider) {
        localStorageServiceProvider.setPrefix('thiki.kanban').setStorageType('sessionStorage');
        $httpProvider.interceptors.push('httpInterceptor');
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common["X-Requested-With"];
        $stateProvider
            .state('boards', {
                url: "/:userName/boards",
                views: {
                    "register": {template: " "},
                    "kanban": {templateUrl: "component/board/partials/boards.html", controller: 'boardController'},
                    "kanban-banner": {templateUrl: "component/banner/partials/banner.html"}
                }
            })
            .state('procedures', {
                url: "/boards/:boardId",
                views: {
                    "register": {template: " "},
                    "kanban": {templateUrl: "component/procedure/partials/procedures-partial.html"},
                    "kanban-banner": {templateUrl: "component/banner/partials/banner.html"}
                }
            })
            .state('welcome', {
                url: "/welcome",
                views: {
                    "welcome": {templateUrl: "component/welcome/partials/index.html"},
                    "kanban-banner": {template: " "},
                    "kanban": {template: " "}
                }
            });

        $urlRouterProvider.otherwise('/welcome');
    }]);

<commit_msg>Adding teams route.<commit_after>/* App Module */
var config = {
    localhost: 'http://localhost:8080'
};

var kanbanApp = angular.module('kanbanApp', [
    'ngRoute', 'ngAnimate', 'ui.bootstrap',
    'ui.sortable',
    'xeditable',
    'LocalStorageModule',
    'ui.router',
    'mgcrea.ngStrap'
]);

kanbanApp.config(['$routeProvider', '$httpProvider', 'localStorageServiceProvider', '$stateProvider', '$urlRouterProvider',
    function ($routeProvider, $httpProvider, localStorageServiceProvider, $stateProvider, $urlRouterProvider) {
        localStorageServiceProvider.setPrefix('thiki.kanban').setStorageType('sessionStorage');
        $httpProvider.interceptors.push('httpInterceptor');
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common["X-Requested-With"];
        $stateProvider
            .state('boards', {
                url: "/:userName/boards",
                views: {
                    "register": {template: " "},
                    "kanban": {templateUrl: "component/board/partials/boards.html", controller: 'boardController'},
                    "kanban-banner": {templateUrl: "component/banner/partials/banner.html"}
                }
            })
            .state('teams', {
                url: "/:userName/teams",
                views: {
                    "register": {template: " "},
                    "kanban": {templateUrl: "component/team/partials/teams.html", controller: 'teamController'},
                    "kanban-banner": {templateUrl: "component/banner/partials/banner.html"}
                }
            })
            .state('procedures', {
                url: "/boards/:boardId",
                views: {
                    "register": {template: " "},
                    "kanban": {templateUrl: "component/procedure/partials/procedures-partial.html"},
                    "kanban-banner": {templateUrl: "component/banner/partials/banner.html"}
                }
            })
            .state('welcome', {
                url: "/welcome",
                views: {
                    "welcome": {templateUrl: "component/welcome/partials/index.html"},
                    "kanban-banner": {template: " "},
                    "kanban": {template: " "}
                }
            });

        $urlRouterProvider.otherwise('/welcome');
    }]);

<|endoftext|>