<commit_before>var Component = new Brick.Component();
Component.requires = {
    mod: [
        {name: 'sys', files: ['editor.js']},
        {name: '{C#MODNAME}', files: ['lib.js', 'addValueModal.js']}
    ]
};
Component.entryPoint = function(NS){

    var Y = Brick.YUI,
        COMPONENT = this,
        SYS = Brick.mod.sys;

    NS.ValueListComplexWidget = Y.Base.create('valueListComplexWidget', SYS.AppWidget, [], {
        onInitAppWidget: function(err, appInstance){
        	this.addValueModal = new NS.AddValueModalWidget({
                srcNode: this.template.gel('modal')
    		});
        },
        destroy: function(){
        	this.template.setHTML('values', "");
        },
        reloadList: function(){
        	var lib = this.get('appInstance'),
	    		sectionid = this.get('sectionid'),
	    		complexid = this.get('currentAttrid'),
	    		data = lib.dataAttributeList(sectionid, true, complexid);

		    	this.set('waiting', true);
		    		lib.attributeList(data, this.renderAttributeList, this);
        },
        renderAttributeList: function(err, result){
        	var compositObj = {};

    		this.set('waiting', false);
    			if(!err){
    				result.attributeList.each(function(attribute){
    					var id = attribute.get('id'),
    						cid = attribute.get('compositeid'),
    						name = attribute.get('nameattribute'),
    						type = attribute.get('typeattribute');

    						switch(type){
    							case 'composite':
    								compositObj[id] = [name, []];
    									break;
    							case 'subcomposite':
    								compositObj[cid][1].push([id, name]);
    								this.set('rowSpan', 2);
    									break;
    						}
    				}, this);
    				this.set('compositeObj', compositObj);
    				this.renderList();
    			}
        },
        renderList: function(){//Заполнение tHead
        	var tp = this.template,
        		compositeObj = this.get('compositeObj'),
        		rowspan = this.get('rowSpan'),
        		insert = this.get('insert'),
        		tdComp = "",
        		tdSubComp = "",
        		len = 0,
        		currArr = '',
        		col = '';

        	for(var i in compositeObj){
        		col = 'rowspan=' + rowspan;
        		currArr = compositeObj[i][1];
        		len = currArr.length;

        		if(len > 0){
        			for(var j = 0; j < len; j++){
            			tdSubComp += this.tdReplace(currArr[j][1], '', currArr[j][0]);
        			}
        			col = 'colspan=' + len;

        			tdComp += this.tdReplace(compositeObj[i][0], col);
        		} else {
        			tdComp += this.tdReplace(compositeObj[i][0], col, i);
        		}
        	}

        	tp.setHTML('values', tp.replace('table', {
        		th: this.renderThead(tdComp, tdSubComp)
        	}))
        		this.reloadListValue();
        },
        tdReplace: function(value, span, id){
        	var insert = this.get('insert');

	        	return this.template.replace('td', {
	        		span: span,
	        		value: insert != 2 || !id ? value : this.referAddReplace(value, id),
	        		add: ''
	        	});
        },
        referAddReplace: function(value, atrid, numrow, mainid, valueid, view){
        	return this.template.replace('referAdd', {
    			nameurl: value + "(+)",
    			id: atrid,
    			vid: 0,
    			view: 'value',
    			numrow: numrow || 0,
    			mainid: mainid || 0
    		})
        },
        renderThead: function(tdComp, tdSubComp){
        	return this.tRowReplace(tdComp) + this.tRowReplace(tdSubComp);
        },
        tRowReplace: function(td){
        	return this.template.replace('tr', {
        		td: td
        	});
        },
        actRowShow: function(){
        	var tp = this.template,
        		numrow = arguments[3],
        		mainid = arguments[4];

        	if(numrow == 0){
        		numrow = tp.gel('table.tBody').rows.length + 1;
        	}

        	this.addValueModal.set('numrow', numrow);
        	this.addValueModal.set('mainid', mainid);

        	this.addValueModal.showModal.apply(this.addValueModal, arguments);
        },
        reloadListValue: function(){
           	var attrid = this.get('currentAttrid');

	    	this.set('waiting', true);
	        	this.get('appInstance').valueComplexList(attrid, function(err, result){
	        		var insert = this.get('insert');//тип таблицы

	        			this.set('waiting', false);
	        			if(!err){
	        				this.set('valueComplexList', result.valueComplexList);
	        					if(insert == 1){
	        						this.renderAutoValueList();
	        					} else {
	        						this.renderValueList();
	        					}
	        			}
	        	}, this);
        },
        renderAutoValueList: function(){//Заполнение tBody авто таблицы
        	var valueComplexList = this.get('valueComplexList'),
    			tp = this.template,
    			curArray = "",
    			tr = "",
    			td,
    			isSpan = "",
    			rowspan = "";

        	for(var i in valueComplexList){
        		rowspan = "rowspan=" + this.determineSpan(valueComplexList[i]);

        		isSpan = true;

	        		for(var z = 0; z < 3; z++){
	        			td = "";

	            		for(var j in valueComplexList[i]){
	            			curArray = valueComplexList[i][j];
		            			if(curArray[z]){
		            				td += tp.replace('td', {
		            					span: isSpan ? rowspan : "",
		            					value: curArray[z].value,
		            					add: this.parseButtonGroup(curArray[z])
		            				});

		            				isSpan = false;
		            			}
	            		}
	            		tr += tp.replace('tr', {
	            			td: td
	            		});
	        		}
        	}
        	tp.setHTML('table.tBody', tr);
        },
        determineSpan: function(obj){
        	var cnt = 0;

        	for(var i in obj){
        		if(cnt == 1){
        			return obj[i].length;
        		} else {
        			cnt++;
        		}
        	}
        },
        renderValueList: function(){//Заполнение tBody ручной таблицы
        	var valueComplexList = this.get('valueComplexList'),
        		tp = this.template,
        		tr = "";

        	if(valueComplexList){
               	for(var i in valueComplexList){
	                	tr += tp.replace('tr', {
	                		td: this.parseRowValue(valueComplexList[i], i)
	                	});
            	}
        	}
        	tp.setHTML('table.tBody', tr);
        },
        parseRowValue: function(objValue, numrow){
        	var tp = this.template,
        		td = "", isRelation, curObj, item,
        		curRelationid = 0;

        	for(var i in objValue){
        		curObj = objValue[i];
        		isRelation = false;
        		item = "";

        		for(var j = 0; j < curObj.length; j++){
        			if(curObj[j].relationid > 0){
        				curRelationid = curObj[j].relationid;
        				isRelation = true;
        			}

        			item += tp.replace('item', {
        				value: this.addValueModal.parseValue(curObj[j].view, curObj[j].nameurl, curObj[j].value),
        				btnGroup: this.parseButtonGroup(curObj[j])
        			});
        		}

     			td += tp.replace('td', {
    				span: "",
    				value: item,
    				add: isRelation ? "" : this.referAddReplace("", i, numrow, curRelationid)
    			});
        	}

        	return td;
        },
        parseButtonGroup: function(obj){
        	if(obj.relationid > 0){
        		return "";
        	} else {
            	return this.template.replace('btnGroup', {
            		vid: obj.id,
            		view: obj.view,
            		id: obj.attributeid,
            		numrow: obj.numrow
            	});
        	}
        },
        removeAct: function(valueid, show){
        	var tp = this.template,
        		remove = "";

	        	if(show){
	        		remove = tp.replace('remove', {
	    				id: valueid
	    			})
	        	}

				tp.setHTML('btnGroup.remove-' + valueid, remove);
        },
        removeValue: function(valueid){
        	var data = {
            		valueid: valueid,
            		remove: 1
            	};

	    	this.set('waiting', true);
	        	this.get('appInstance').removeValueAttribute(data, function(err, result){
	        		this.set('waiting', false);
	        			if(!err){
	        				this.reloadListValue();
	        			}
	        	}, this);
        }
    }, {
        ATTRS: {
        	component: {value: COMPONENT},
            templateBlockName: {value: 'widget,table,tr,td,referAdd,item,remove,btnGroup'},
            valueComplexList: {value: null},
            currentAttrid: {value: null},
            currentType: {value: null},
            sectionid: {value: null},
            compositeObj: {value: null},
            rowSpan: {value: 0},
            insert: {value: 0}
        },
        CLICKS: {
        	'modal-show': {
        		event: function(e){
        			var targ = e.defineTarget,
        				valueid = targ.getData('id'),
        				view = targ.getData('view'),
        				atrid = targ.getData('atrid'),
        				numrow = targ.getData('numrow'),
        				mainid = targ.getData('mainid');

        				this.actRowShow(valueid, atrid, view, numrow, mainid);
        		}
        	},
        	'remove-show': {
        		event: function(e){
        			var id = e.defineTarget.getData('id');

        				this.removeAct(id, true);
        		}
        	},
        	'remove-hide': {
        		event: function(e){
        			var id = e.target.getData('id');

        				this.removeAct(id);
        		}
        	},
        	removeValue: {
        		event: function(e){
        			var valueid = e.target.getData('id');

        				this.removeValue(valueid);
        		}
        	},
        	addValue: {
        		event: function(e){
        			var _self = this;

	        			this.addValueModal.actValue(function(respond){
	        				if(respond){
	        					_self.reloadListValue();
	        				}
	        			});
        		}
        	}
        }
    });
};<commit_msg>hide empty row<commit_after>var Component = new Brick.Component();
Component.requires = {
    mod: [
        {name: 'sys', files: ['editor.js']},
        {name: '{C#MODNAME}', files: ['lib.js', 'addValueModal.js']}
    ]
};
Component.entryPoint = function(NS){

    var Y = Brick.YUI,
        COMPONENT = this,
        SYS = Brick.mod.sys;

    NS.ValueListComplexWidget = Y.Base.create('valueListComplexWidget', SYS.AppWidget, [], {
        onInitAppWidget: function(err, appInstance){
        	this.addValueModal = new NS.AddValueModalWidget({
                srcNode: this.template.gel('modal')
    		});
        },
        destroy: function(){
        	this.template.setHTML('values', "");
        },
        reloadList: function(){
        	var lib = this.get('appInstance'),
	    		sectionid = this.get('sectionid'),
	    		complexid = this.get('currentAttrid'),
	    		data = lib.dataAttributeList(sectionid, true, complexid);

		    	this.set('waiting', true);
		    		lib.attributeList(data, this.renderAttributeList, this);
        },
        renderAttributeList: function(err, result){
        	var compositObj = {};

    		this.set('waiting', false);
    			if(!err){
    				result.attributeList.each(function(attribute){
    					var id = attribute.get('id'),
    						cid = attribute.get('compositeid'),
    						name = attribute.get('nameattribute'),
    						type = attribute.get('typeattribute');

    						switch(type){
    							case 'composite':
    								compositObj[id] = [name, []];
    									break;
    							case 'subcomposite':
    								compositObj[cid][1].push([id, name]);
    								this.set('rowSpan', 2);
    									break;
    						}
    				}, this);
    				this.set('compositeObj', compositObj);
    				this.renderList();
    			}
        },
        renderList: function(){//Заполнение tHead
        	var tp = this.template,
        		compositeObj = this.get('compositeObj'),
        		rowspan = this.get('rowSpan'),
        		insert = this.get('insert'),
        		tdComp = "",
        		tdSubComp = "",
        		len = 0,
        		currArr = '',
        		col = '';

        	for(var i in compositeObj){
        		col = 'rowspan=' + rowspan;
        		currArr = compositeObj[i][1];
        		len = currArr.length;

        		if(len > 0){
        			for(var j = 0; j < len; j++){
            			tdSubComp += this.tdReplace(currArr[j][1], '', currArr[j][0]);
        			}
        			col = 'colspan=' + len;

        			tdComp += this.tdReplace(compositeObj[i][0], col);
        		} else {
        			tdComp += this.tdReplace(compositeObj[i][0], col, i);
        		}
        	}

        	tp.setHTML('values', tp.replace('table', {
        		th: this.renderThead(tdComp, tdSubComp)
        	}))
        		this.reloadListValue();
        },
        tdReplace: function(value, span, id){
        	var insert = this.get('insert');

	        	return this.template.replace('td', {
	        		span: span,
	        		value: insert != 2 || !id ? value : this.referAddReplace(value, id),
	        		add: ''
	        	});
        },
        referAddReplace: function(value, atrid, numrow, mainid, valueid, view){
        	return this.template.replace('referAdd', {
    			nameurl: value + "(+)",
    			id: atrid,
    			vid: 0,
    			view: 'value',
    			numrow: numrow || 0,
    			mainid: mainid || 0
    		})
        },
        renderThead: function(tdComp, tdSubComp){
        	return this.tRowReplace(tdComp) + this.tRowReplace(tdSubComp);
        },
        tRowReplace: function(td){
        	return this.template.replace('tr', {
        		td: td
        	});
        },
        actRowShow: function(){
        	var tp = this.template,
        		numrow = arguments[3],
        		mainid = arguments[4];

        	if(numrow == 0){
        		numrow = tp.gel('table.tBody').rows.length + 1;
        	}

        	this.addValueModal.set('numrow', numrow);
        	this.addValueModal.set('mainid', mainid);

        	this.addValueModal.showModal.apply(this.addValueModal, arguments);
        },
        reloadListValue: function(){
           	var attrid = this.get('currentAttrid');

	    	this.set('waiting', true);
	        	this.get('appInstance').valueComplexList(attrid, function(err, result){
	        		var insert = this.get('insert');//тип таблицы

	        			this.set('waiting', false);
	        			if(!err){
	        				this.set('valueComplexList', result.valueComplexList);
	        					if(insert == 1){
	        						this.renderAutoValueList();
	        					} else {
	        						this.renderValueList();
	        					}
	        			}
	        	}, this);
        },
        renderAutoValueList: function(){//Заполнение tBody авто таблицы
        	var valueComplexList = this.get('valueComplexList'),
    			tp = this.template,
    			curArray = "",
    			tr = "",
    			td,
    			isSpan = "",
    			rowspan = "";

        	for(var i in valueComplexList){
        		rowspan = "rowspan=" + this.determineSpan(valueComplexList[i]);

        		isSpan = true;

	        		for(var z = 0; z < 3; z++){
	        			td = "";
	            		for(var j in valueComplexList[i]){
	            			curArray = valueComplexList[i][j];
		            			if(curArray[z]){
		            				td += tp.replace('td', {
		            					span: isSpan ? rowspan : "",
		            					value: curArray[z].value,
		            					add: this.parseButtonGroup(curArray[z])
		            				});

		            				isSpan = false;
		            			}
	            		}
	            		tr += tp.replace('tr', {
	            			td: td
	            		});
	        		}
        	}
        	tp.setHTML('table.tBody', tr);
        },
        determineSpan: function(obj){
        	var cnt = 0;

        	for(var i in obj){
        		if(cnt == 1){
        			return obj[i].length;
        		} else {
        			cnt++;
        		}
        	}
        },
        renderValueList: function(){//Заполнение tBody ручной таблицы
        	var valueComplexList = this.get('valueComplexList'),
        		tp = this.template,
        		tr = "",
        		td = "",
        		regEx = /show-td-buttons/i;

        	if(valueComplexList){
               	for(var i in valueComplexList){
               		td = this.parseRowValue(valueComplexList[i], i);

               		if(regEx.test(td)){
	                	tr += tp.replace('tr', {
	                		td: td
	                	});
               		}
            	}
        	}
        	tp.setHTML('table.tBody', tr);
        },
        parseRowValue: function(objValue, numrow){
        	var tp = this.template,
        		td = "",
        		isRelation,
        		curObj,
        		curRelationid = 0,
        		curLen = 0;

        	for(var i in objValue){
        		curObj = objValue[i];
        		isRelation = false;

        		for(var j = 0, item = ""; j < curObj.length; j++){
        			if(curObj[j].relationid > 0){
        				curRelationid = curObj[j].relationid;
        				isRelation = true;
        			}
        			item += tp.replace('item', {
        				value: this.addValueModal.parseValue(curObj[j].view, curObj[j].nameurl, curObj[j].value),
        				btnGroup: this.parseButtonGroup(curObj[j])
        			});
        		}
     			td += tp.replace('td', {
    				span: "",
    				value: item,
    				add: isRelation ? "" : this.referAddReplace("", i, numrow, curRelationid)
    			});

        	}
        	return td;
        },
        parseButtonGroup: function(obj){
        	if(obj.relationid > 0){
        		return "";
        	} else {
            	return this.template.replace('btnGroup', {
            		vid: obj.id,
            		view: obj.view,
            		id: obj.attributeid,
            		numrow: obj.numrow
            	});
        	}
        },
        removeAct: function(valueid, show){
        	var tp = this.template,
        		remove = "";

	        	if(show){
	        		remove = tp.replace('remove', {
	    				id: valueid
	    			})
	        	}

				tp.setHTML('btnGroup.remove-' + valueid, remove);
        },
        removeValue: function(valueid){
        	var data = {
            		valueid: valueid,
            		remove: 1
            	};

	    	this.set('waiting', true);
	        	this.get('appInstance').removeValueAttribute(data, function(err, result){
	        		this.set('waiting', false);
	        			if(!err){
	        				this.reloadListValue();
	        			}
	        	}, this);
        }
    }, {
        ATTRS: {
        	component: {value: COMPONENT},
            templateBlockName: {value: 'widget,table,tr,td,referAdd,item,remove,btnGroup'},
            valueComplexList: {value: null},
            currentAttrid: {value: null},
            currentType: {value: null},
            sectionid: {value: null},
            compositeObj: {value: null},
            rowSpan: {value: 0},
            insert: {value: 0}
        },
        CLICKS: {
        	'modal-show': {
        		event: function(e){
        			var targ = e.defineTarget,
        				valueid = targ.getData('id'),
        				view = targ.getData('view'),
        				atrid = targ.getData('atrid'),
        				numrow = targ.getData('numrow'),
        				mainid = targ.getData('mainid');

        				this.actRowShow(valueid, atrid, view, numrow, mainid);
        		}
        	},
        	'remove-show': {
        		event: function(e){
        			var id = e.defineTarget.getData('id');

        				this.removeAct(id, true);
        		}
        	},
        	'remove-hide': {
        		event: function(e){
        			var id = e.target.getData('id');

        				this.removeAct(id);
        		}
        	},
        	removeValue: {
        		event: function(e){
        			var valueid = e.target.getData('id');

        				this.removeValue(valueid);
        		}
        	},
        	addValue: {
        		event: function(e){
        			var _self = this;

	        			this.addValueModal.actValue(function(respond){
	        				if(respond){
	        					_self.reloadListValue();
	        				}
	        			});
        		}
        	}
        }
    });
};<|endoftext|>


<commit_before>onOpenDialog = function(dialog) {
  (dialog = $('.ui-dialog')).find('.ui-dialog-titlebar').corner('1px top');
  if(!$.browser.msie){
    dialog.corner('6px');
  }
  if (dialog.height() < $(window).height()) {
    if(iframed()) {
      $(parent.document.body).addClass('hide-overflow');
    } else {
      $(document.body).addClass('hide-overflow');
    }
  }
};

onCloseDialog = function(dialog) {
  if(iframed()) {
    $(parent.document.body).removeClass('hide-overflow');
  } else {
    $(document.body).removeClass('hide-overflow');
  }
};

WYMeditor.onload_functions = [];
var wymeditor_inputs = [];
var wymeditors_loaded = 0;
// supply custom_wymeditor_boot_options if you want to override anything here.
if (typeof(custom_wymeditor_boot_options) == "undefined") { custom_wymeditor_boot_options = {}; }
var form_actions =
"
"
  + "
"
    + "<input id='submit_button' class='wym_submit button' type='submit' value='{Insert}' class='button' />"
    + "{Cancel}"
  + "
"
+ "
";
var wymeditor_boot_options = $.extend({
  skin: 'refinery'
  , basePath: "/"
  , wymPath: "/javascripts/wymeditor/jquery.refinery.wymeditor.js"
  , cssSkinPath: "/stylesheets/wymeditor/skins/"
  , jsSkinPath: "/javascripts/wymeditor/skins/"
  , langPath: "/javascripts/wymeditor/lang/"
  , iframeBasePath: '/'
  , classesItems: [
    {name: 'text-align', rules:['left', 'center', 'right', 'justify'], join: '-'}
    , {name: 'image-align', rules:['left', 'right'], join: '-'}
    , {name: 'font-size', rules:['small', 'normal', 'large'], join: '-'}
  ]

  , containersItems: [
    {'name': 'h1', 'title':'Heading_1', 'css':'wym_containers_h1'}
    , {'name': 'h2', 'title':'Heading_2', 'css':'wym_containers_h2'}
    , {'name': 'h3', 'title':'Heading_3', 'css':'wym_containers_h3'}
    , {'name': 'p', 'title':'Paragraph', 'css':'wym_containers_p'}
  ]
  , toolsItems: [
    {'name': 'Bold', 'title': 'Bold', 'css': 'wym_tools_strong'}
    ,{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'}
    ,{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}
    ,{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}
    /*,{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'}
    ,{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'}
    ,{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'}
    ,{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}*/
    ,{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'}
    ,{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'}
    ,{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'}
    ,{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'}
    //,{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}
    ,{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}
  ]

  ,toolsHtml: "
" + WYMeditor.TOOLS_ITEMS + WYMeditor.CLASSES + "
"

  ,toolsItemHtml:
    "
"
      + ""
        + WYMeditor.TOOL_TITLE
      + ""
    + "
"

  , classesHtml: "
"
                 + ""
                   + WYMeditor.APPLY_CLASS
                 + ""
                 + "
" + WYMeditor.CLASSES_ITEMS + "
"
                + "
"

  , classesItemHtml: "
"+ WYMeditor.CLASS_TITLE+ "
"
  , classesItemHtmlMultiple: "
"
                              + "" + WYMeditor.CLASS_TITLE + ""
                              + "
{classesItemHtml}
"
                            +"
"

  , containersHtml: "
" + WYMeditor.CONTAINERS_ITEMS + "
"

  , containersItemHtml:
      "
"
        + ""
      + "
"

  , boxHtml:
  "
"
    + "
"
      + WYMeditor.CONTAINERS
      + WYMeditor.TOOLS
    + "
"
    + "
"
      + WYMeditor.HTML
      + WYMeditor.IFRAME
      + WYMeditor.STATUS
    + "
"
  + "
"

  , iframeHtml:
    "
"
     + ""
    +"
"

  , dialogImageHtml: ""

  , dialogLinkHtml: ""

  , dialogTableHtml:
    "
"
      + "<form>"
        + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"+ WYMeditor.DIALOG_TABLE + "' />"
        + "
"
          + "{Caption}"
          + "<input type='text' id='wym_caption' class='wym_caption' value='' size='40' />"
        + "
"
        + "
"
          + "{Number_Of_Rows}"
          + "<input type='text' id='wym_rows' class='wym_rows' value='3' size='3' />"
        + "
"
        + "
"
          + "{Number_Of_Cols}"
          + "<input type='text' id='wym_cols' class='wym_cols' value='2' size='3' />"
        + "
"
        + form_actions
      + "</form>"
    + "
"

  , dialogPasteHtml:
    "
"
      + "<form>"
        + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='" + WYMeditor.DIALOG_PASTE + "' />"
        + "
"
          + "<textarea class='wym_text' rows='10' cols='50'></textarea>"
        + "
"
        + form_actions
      + "</form>"
    + "
"

  , dialogPath: "/refinery/dialogs/"
  , dialogFeatures: {
      width: 866
    , height: 455
    , modal: true
    , draggable: true
    , resizable: false
    , autoOpen: true
    , open: onOpenDialog
    , close: onCloseDialog
  }
  , dialogInlineFeatures: {
      width: 600
    , height: 485
    , modal: true
    , draggable: true
    , resizable: false
    , autoOpen: true
    , open: onOpenDialog
    , close: onCloseDialog
  }

  , dialogId: 'editor_dialog'

  , dialogHtml:
    "<!DOCTYPE html>"
    + ""
      + ""
        + "<link rel='stylesheet' type='text/css' media='screen' href='" + WYMeditor.CSS_PATH + "' />"
        + "<title>" + WYMeditor.DIALOG_TITLE + "</title>"
        + ""
        + ""
      + ""
      + ""
        + "
" + WYMeditor.DIALOG_BODY + "
"
      + ""
    + ""
  , postInit: function(wym)
  {
    // register loaded
    wymeditors_loaded += 1;

    // fire loaded if all editors loaded
    if(WYMeditor.INSTANCES.length == wymeditors_loaded){
      $('.wym_loading_overlay').remove();

      // load any functions that have been registered to happen onload.
      // these will have to be registered BEFORE postInit is fired (which is fairly quickly).
      for(i=0; i < WYMeditor.onload_functions.length; i++) {
        WYMeditor.onload_functions[i]();
      }
    }

    $(wym._iframe).contents().find('body').addClass('wym_iframe_body');

    $('.field.hide-overflow').removeClass('hide-overflow').css('height', 'auto');
  }
  , postInitDialog: function(wym) {
    if($.browser.msie) {
      ($the_ui_dialog = $('.ui-dialog')).css('height',
        $the_ui_dialog.find('iframe').height()
        + $the_ui_dialog.find('iframe').contents().find('.form-actions').height()
        - 12
      );
    }
  }
  , lang: (typeof(I18n.locale) != "undefined" ? I18n.locale : 'en')
}, custom_wymeditor_boot_options);

WYMeditor.editor.prototype.loadIframe = function(iframe) {
  var wym = this;

  var doc = (iframe.document || iframe.contentDocument || iframe.contentWindow.document);
  doc.open('text/html', 'replace');
  html = "<!DOCTYPE html>\
  \
    \
      <title>WYMeditor</title>\
      <meta charset='" + $('meta[charset]').attr('charset') + "' />\
      <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />\
    \
    \
    \
  ";
  doc.write(html);
  doc.close();

  if ((id_of_editor = wym._element.parent().attr('id')) != null) {
    $(doc.body).addClass(id_of_editor);
  }

  $.each(["wymeditor/skins/refinery/wymiframe", "formatting", "theme"], function(i, href) {
    $("<link href='/stylesheets/" + href + ".css' media='all' rel='stylesheet' />").appendTo(doc.head);
  });
  $("").appendTo(doc.head);

  wym.initIframe(iframe);
};

WYMeditor.init = function() {
  wymeditor_inputs = $('.wymeditor');
  wymeditor_inputs = wymeditor_inputs.filter(function(index) {
    for (i=0; i < WYMeditor.INSTANCES.length; i++) {
      if (WYMeditor.INSTANCES[i]._element.attr('id') == $(this).attr('id')) {
        return false;
      }
    }

    return true;
  });

  wymeditor_inputs.each(function(input) {
    if ((containing_field = $(this).parents('.field')).get(0).style.height === '') {
      containing_field.addClass('hide-overflow')
                      .css('height', $(this).outerHeight() - containing_field.offset().top + $(this).offset().top + 45);
    }
    $(this).hide();
  });

  wymeditor_inputs.wymeditor(wymeditor_boot_options);
};

$(function(){
  WYMeditor.init();
});
<commit_msg>Don't assume<commit_after>onOpenDialog = function(dialog) {
  (dialog = $('.ui-dialog')).find('.ui-dialog-titlebar').corner('1px top');
  if(!$.browser.msie){
    dialog.corner('6px');
  }
  if (dialog.height() < $(window).height()) {
    if(iframed()) {
      $(parent.document.body).addClass('hide-overflow');
    } else {
      $(document.body).addClass('hide-overflow');
    }
  }
};

onCloseDialog = function(dialog) {
  if(iframed()) {
    $(parent.document.body).removeClass('hide-overflow');
  } else {
    $(document.body).removeClass('hide-overflow');
  }
};

WYMeditor.onload_functions = [];
var wymeditor_inputs = [];
var wymeditors_loaded = 0;
// supply custom_wymeditor_boot_options if you want to override anything here.
if (typeof(custom_wymeditor_boot_options) == "undefined") { custom_wymeditor_boot_options = {}; }
var form_actions =
"
"
  + "
"
    + "<input id='submit_button' class='wym_submit button' type='submit' value='{Insert}' class='button' />"
    + "{Cancel}"
  + "
"
+ "
";
var wymeditor_boot_options = $.extend({
  skin: 'refinery'
  , basePath: "/"
  , wymPath: "/javascripts/wymeditor/jquery.refinery.wymeditor.js"
  , cssSkinPath: "/stylesheets/wymeditor/skins/"
  , jsSkinPath: "/javascripts/wymeditor/skins/"
  , langPath: "/javascripts/wymeditor/lang/"
  , iframeBasePath: '/'
  , classesItems: [
    {name: 'text-align', rules:['left', 'center', 'right', 'justify'], join: '-'}
    , {name: 'image-align', rules:['left', 'right'], join: '-'}
    , {name: 'font-size', rules:['small', 'normal', 'large'], join: '-'}
  ]

  , containersItems: [
    {'name': 'h1', 'title':'Heading_1', 'css':'wym_containers_h1'}
    , {'name': 'h2', 'title':'Heading_2', 'css':'wym_containers_h2'}
    , {'name': 'h3', 'title':'Heading_3', 'css':'wym_containers_h3'}
    , {'name': 'p', 'title':'Paragraph', 'css':'wym_containers_p'}
  ]
  , toolsItems: [
    {'name': 'Bold', 'title': 'Bold', 'css': 'wym_tools_strong'}
    ,{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'}
    ,{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}
    ,{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}
    /*,{'name': 'Indent', 'title': 'Indent', 'css': 'wym_tools_indent'}
    ,{'name': 'Outdent', 'title': 'Outdent', 'css': 'wym_tools_outdent'}
    ,{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'}
    ,{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}*/
    ,{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'}
    ,{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'}
    ,{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'}
    ,{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'}
    //,{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}
    ,{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}
  ]

  ,toolsHtml: "
" + WYMeditor.TOOLS_ITEMS + WYMeditor.CLASSES + "
"

  ,toolsItemHtml:
    "
"
      + ""
        + WYMeditor.TOOL_TITLE
      + ""
    + "
"

  , classesHtml: "
"
                 + ""
                   + WYMeditor.APPLY_CLASS
                 + ""
                 + "
" + WYMeditor.CLASSES_ITEMS + "
"
                + "
"

  , classesItemHtml: "
"+ WYMeditor.CLASS_TITLE+ "
"
  , classesItemHtmlMultiple: "
"
                              + "" + WYMeditor.CLASS_TITLE + ""
                              + "
{classesItemHtml}
"
                            +"
"

  , containersHtml: "
" + WYMeditor.CONTAINERS_ITEMS + "
"

  , containersItemHtml:
      "
"
        + ""
      + "
"

  , boxHtml:
  "
"
    + "
"
      + WYMeditor.CONTAINERS
      + WYMeditor.TOOLS
    + "
"
    + "
"
      + WYMeditor.HTML
      + WYMeditor.IFRAME
      + WYMeditor.STATUS
    + "
"
  + "
"

  , iframeHtml:
    "
"
     + ""
    +"
"

  , dialogImageHtml: ""

  , dialogLinkHtml: ""

  , dialogTableHtml:
    "
"
      + "<form>"
        + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"+ WYMeditor.DIALOG_TABLE + "' />"
        + "
"
          + "{Caption}"
          + "<input type='text' id='wym_caption' class='wym_caption' value='' size='40' />"
        + "
"
        + "
"
          + "{Number_Of_Rows}"
          + "<input type='text' id='wym_rows' class='wym_rows' value='3' size='3' />"
        + "
"
        + "
"
          + "{Number_Of_Cols}"
          + "<input type='text' id='wym_cols' class='wym_cols' value='2' size='3' />"
        + "
"
        + form_actions
      + "</form>"
    + "
"

  , dialogPasteHtml:
    "
"
      + "<form>"
        + "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='" + WYMeditor.DIALOG_PASTE + "' />"
        + "
"
          + "<textarea class='wym_text' rows='10' cols='50'></textarea>"
        + "
"
        + form_actions
      + "</form>"
    + "
"

  , dialogPath: "/refinery/dialogs/"
  , dialogFeatures: {
      width: 866
    , height: 455
    , modal: true
    , draggable: true
    , resizable: false
    , autoOpen: true
    , open: onOpenDialog
    , close: onCloseDialog
  }
  , dialogInlineFeatures: {
      width: 600
    , height: 485
    , modal: true
    , draggable: true
    , resizable: false
    , autoOpen: true
    , open: onOpenDialog
    , close: onCloseDialog
  }

  , dialogId: 'editor_dialog'

  , dialogHtml:
    "<!DOCTYPE html>"
    + ""
      + ""
        + "<link rel='stylesheet' type='text/css' media='screen' href='" + WYMeditor.CSS_PATH + "' />"
        + "<title>" + WYMeditor.DIALOG_TITLE + "</title>"
        + ""
        + ""
      + ""
      + ""
        + "
" + WYMeditor.DIALOG_BODY + "
"
      + ""
    + ""
  , postInit: function(wym)
  {
    // register loaded
    wymeditors_loaded += 1;

    // fire loaded if all editors loaded
    if(WYMeditor.INSTANCES.length == wymeditors_loaded){
      $('.wym_loading_overlay').remove();

      // load any functions that have been registered to happen onload.
      // these will have to be registered BEFORE postInit is fired (which is fairly quickly).
      for(i=0; i < WYMeditor.onload_functions.length; i++) {
        WYMeditor.onload_functions[i]();
      }
    }

    $(wym._iframe).contents().find('body').addClass('wym_iframe_body');

    $('.field.hide-overflow').removeClass('hide-overflow').css('height', 'auto');
  }
  , postInitDialog: function(wym) {
    if($.browser.msie) {
      ($the_ui_dialog = $('.ui-dialog')).css('height',
        $the_ui_dialog.find('iframe').height()
        + $the_ui_dialog.find('iframe').contents().find('.form-actions').height()
        - 12
      );
    }
  }
  , lang: (typeof(I18n.locale) != "undefined" ? I18n.locale : 'en')
}, custom_wymeditor_boot_options);

WYMeditor.editor.prototype.loadIframe = function(iframe) {
  var wym = this;

  var doc = (iframe.document || iframe.contentDocument || iframe.contentWindow.document);
  doc.open('text/html', 'replace');
  html = "<!DOCTYPE html>\
  \
    \
      <title>WYMeditor</title>\
      <meta charset='" + $('meta[charset]').attr('charset') + "' />\
      <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1' />\
    \
    \
    \
  ";
  doc.write(html);
  doc.close();

  if ((id_of_editor = wym._element.parent().attr('id')) != null) {
    $(doc.body).addClass(id_of_editor);
  }

  $.each(["wymeditor/skins/refinery/wymiframe", "formatting", "theme"], function(i, href) {
    $("<link href='/stylesheets/" + href + ".css' media='all' rel='stylesheet' />").appendTo(doc.head);
  });
  $("").appendTo(doc.head);

  wym.initIframe(iframe);
};

WYMeditor.init = function() {
  wymeditor_inputs = $('.wymeditor');
  wymeditor_inputs = wymeditor_inputs.filter(function(index) {
    for (i=0; i < WYMeditor.INSTANCES.length; i++) {
      if (WYMeditor.INSTANCES[i]._element.attr('id') == $(this).attr('id')) {
        return false;
      }
    }

    return true;
  });

  wymeditor_inputs.each(function(input) {
    if ((containing_field = $(this).parents('.field')).length > 0 && containing_field.get(0).style.height === '') {
      containing_field.addClass('hide-overflow')
                      .css('height', $(this).outerHeight() - containing_field.offset().top + $(this).offset().top + 45);
    }
    $(this).hide();
  });

  wymeditor_inputs.wymeditor(wymeditor_boot_options);
};

$(function(){
  WYMeditor.init();
});
<|endoftext|>


<commit_before>/* eslint no-console:0 */

/*
 *copied from https://github.com/Khan/KaTeX/tree/master/contrib/auto-render
 *until https://github.com/Khan/KaTeX/issues/425 is resolved.
 */

/*
 *The MIT License (MIT)
 *
 *Copyright (c) 2015 Khan Academy
 *
 *This software also uses portions of the underscore.js project, which is
 *MIT licensed with the following copyright:
 *
 *Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative
 *Reporters & Editors
 *
 *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.
 */

(function() {
  'use strict';
  angular.module('bk.katexhelper', []).factory('katexhelper', function() {
    return {
      splitWithDelimiters: function(text, delimiters) {
        var data = [{type: "text", data: text}];
        delimiters = delimiters.delimiters;
        for(var i = 0; i<delimiters.length; i++){
          var delimiter = delimiters[i];
          data = this.splitAtDelimiters(
            data, delimiter.left, delimiter.right,
            delimiter.display || false);
        }
        return data;
      },
      renderMathInText: function(text, delimiters) {
        var data = this.splitWithDelimiters(text, delimiters);
        var fragment = document.createDocumentFragment();
        for(var i = 0; i<data.length; i++){
          var element = document.createElement("span");
          if (data[i].type === "text"){
            element.appendChild(document.createTextNode(data[i].data));
          } else {
            fragment.appendChild(element);
            var math = data[i].data;
            try {
              katex.render(math, element);
            } catch(err) {
              element.style.color = '#cc0000';
              element.title = err.message;
              element.appendChild(document.createTextNode(data[i].rawData));
            }
          }
          fragment.appendChild(element);
        }
        return fragment;
      },
      renderElem: function(elem, delimiters, ignoredTags) {
        for(var i = 0; i<elem.childNodes.length; i++){
          var childNode = elem.childNodes[i];
          if (childNode.nodeType === 3){
            // Text node
            var frag = this.renderMathInText(childNode.textContent, delimiters);
            i += frag.childNodes.length - 1;
            elem.replaceChild(frag, childNode);
          } else if (childNode.nodeType === 1){
            //because all tags are ignored we don't care about those. if the node is element - render child is called
            this.renderElem(childNode, delimiters, ignoredTags);
          }
          // Otherwise, it's something else, and ignore it.
        }
      },
      defaultOptions: {
        delimiters: [
          {left: "$$", right: "$$", display: true},
          {left: "\\[", right: "\\]", display: true},
          {left: "\\(", right: "\\)", display: false},
          // LaTeX uses this, but it ruins the display of normal `$` in text:
          {left: "$", right: "$", display: false},
        ],

        ignoredTags: [
          "script", "noscript", "style", "textarea", "pre", "code",
        ]
      },
      extend: function(obj) {
        // Adapted from underscore.js' `_.extend`. See LICENSE.txt for license.
        var source;
        var prop;
        for(var i = 1, length = arguments.length; i<length; i++){
          source = arguments[i];
          for(prop in source){
            if (Object.prototype.hasOwnProperty.call(source, prop)){
              obj[prop] = source[prop];
            }
          }
        }
        return obj;
      },
      findEndOfMath: function(delimiter, text, startIndex) {
        // Adapted from
        // https://github.com/Khan/perseus/blob/master/src/perseus-markdown.jsx
        var index = startIndex;
        var braceLevel = 0;

        var delimLength = delimiter.length;

        while(index<text.length) {

          if (text.slice(index, index + delimLength) === delimiter){
            return index;
          }

          index++;
        }

        return -1;
      },
      splitAtDelimiters: function(startData, leftDelim, rightDelim, display) {
        var finalData = [];

        for(var i = 0; i<startData.length; i++){
          if (startData[i].type === "text"){
            var text = startData[i].data;

            var lookingForLeft = true;
            var currIndex = 0;
            var nextIndex;

            nextIndex = text.indexOf(leftDelim);
            if (nextIndex !== -1){
              currIndex = nextIndex;
              finalData.push({
                type: "text",
                data: text.slice(0, currIndex),
              });
              lookingForLeft = false;
            }

            while(true) {
              if (lookingForLeft){
                nextIndex = text.indexOf(leftDelim, currIndex);
                if (nextIndex === -1){
                  break;
                }

                finalData.push({
                  type: "text",
                  data: text.slice(currIndex, nextIndex),
                });

                currIndex = nextIndex;
              } else {
                nextIndex = this.findEndOfMath(
                  rightDelim,
                  text,
                  currIndex + leftDelim.length);
                if (nextIndex === -1){
                  break;
                }

                finalData.push({
                  type: "math",
                  data: text.slice(
                    currIndex + leftDelim.length,
                    nextIndex),
                  rawData: text.slice(
                    currIndex,
                    nextIndex + rightDelim.length),
                  display: display,
                });

                currIndex = nextIndex + rightDelim.length;
              }

              lookingForLeft = !lookingForLeft;
            }

            finalData.push({
              type: "text",
              data: text.slice(currIndex),
            });
          } else {
            finalData.push(startData[i]);
          }
        }
        return finalData;
      }
    };
  });
})();<commit_msg>#3203 firefox test fix, empty span was added, not anymore<commit_after>/* eslint no-console:0 */

/*
 *copied from https://github.com/Khan/KaTeX/tree/master/contrib/auto-render
 *until https://github.com/Khan/KaTeX/issues/425 is resolved.
 */

/*
 *The MIT License (MIT)
 *
 *Copyright (c) 2015 Khan Academy
 *
 *This software also uses portions of the underscore.js project, which is
 *MIT licensed with the following copyright:
 *
 *Copyright (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative
 *Reporters & Editors
 *
 *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.
 */

(function() {
  'use strict';
  angular.module('bk.katexhelper', []).factory('katexhelper', function() {
    return {
      splitWithDelimiters: function(text, delimiters) {
        var data = [{type: "text", data: text}];
        delimiters = delimiters.delimiters;
        for(var i = 0; i<delimiters.length; i++){
          var delimiter = delimiters[i];
          data = this.splitAtDelimiters(
            data, delimiter.left, delimiter.right,
            delimiter.display || false);
        }
        return data;
      },
      renderMathInText: function(text, delimiters) {
        var data = this.splitWithDelimiters(text, delimiters);
        var fragment = document.createDocumentFragment();

        for(var i = 0; i<data.length; i++){
          if (data[i].type === "text"){
            fragment.appendChild(document.createTextNode(data[i].data));
          } else {
            var element = document.createElement("span");
            var math = data[i].data;
            try {
              katex.render(math, element);
              fragment.appendChild(element);
            } catch(err) {
              element.style.color = '#cc0000';
              element.title = err.message;
              element.appendChild(document.createTextNode(data[i].rawData));
              fragment.appendChild(element);
            }
          }
        }

        return fragment;
      },
      renderElem: function(elem, delimiters, ignoredTags) {
        for(var i = 0; i<elem.childNodes.length; i++){
          var childNode = elem.childNodes[i];
          if (childNode.nodeType === 3){
            // Text node
            var frag = this.renderMathInText(childNode.textContent, delimiters);
            i += frag.childNodes.length - 1;
            elem.replaceChild(frag, childNode);
          } else if (childNode.nodeType === 1){
            //because all tags are ignored we don't care about those. if the node is element - render child is called
            this.renderElem(childNode, delimiters, ignoredTags);
          }
          // Otherwise, it's something else, and ignore it.
        }
      },
      defaultOptions: {
        delimiters: [
          {left: "$$", right: "$$", display: true},
          {left: "\\[", right: "\\]", display: true},
          {left: "\\(", right: "\\)", display: false},
          // LaTeX uses this, but it ruins the display of normal `$` in text:
          {left: "$", right: "$", display: false},
        ],

        ignoredTags: [
          "script", "noscript", "style", "textarea", "pre", "code",
        ]
      },
      extend: function(obj) {
        // Adapted from underscore.js' `_.extend`. See LICENSE.txt for license.
        var source;
        var prop;
        for(var i = 1, length = arguments.length; i<length; i++){
          source = arguments[i];
          for(prop in source){
            if (Object.prototype.hasOwnProperty.call(source, prop)){
              obj[prop] = source[prop];
            }
          }
        }
        return obj;
      },
      findEndOfMath: function(delimiter, text, startIndex) {
        // Adapted from
        // https://github.com/Khan/perseus/blob/master/src/perseus-markdown.jsx
        var index = startIndex;
        var braceLevel = 0;

        var delimLength = delimiter.length;

        while(index<text.length) {

          if (text.slice(index, index + delimLength) === delimiter){
            return index;
          }

          index++;
        }

        return -1;
      },
      splitAtDelimiters: function(startData, leftDelim, rightDelim, display) {
        var finalData = [];

        for(var i = 0; i<startData.length; i++){
          if (startData[i].type === "text"){
            var text = startData[i].data;

            var lookingForLeft = true;
            var currIndex = 0;
            var nextIndex;

            nextIndex = text.indexOf(leftDelim);
            if (nextIndex !== -1){
              currIndex = nextIndex;
              finalData.push({
                type: "text",
                data: text.slice(0, currIndex),
              });
              lookingForLeft = false;
            }

            while(true) {
              if (lookingForLeft){
                nextIndex = text.indexOf(leftDelim, currIndex);
                if (nextIndex === -1){
                  break;
                }

                finalData.push({
                  type: "text",
                  data: text.slice(currIndex, nextIndex),
                });

                currIndex = nextIndex;
              } else {
                nextIndex = this.findEndOfMath(
                  rightDelim,
                  text,
                  currIndex + leftDelim.length);
                if (nextIndex === -1){
                  break;
                }

                finalData.push({
                  type: "math",
                  data: text.slice(
                    currIndex + leftDelim.length,
                    nextIndex),
                  rawData: text.slice(
                    currIndex,
                    nextIndex + rightDelim.length),
                  display: display,
                });

                currIndex = nextIndex + rightDelim.length;
              }

              lookingForLeft = !lookingForLeft;
            }

            finalData.push({
              type: "text",
              data: text.slice(currIndex),
            });
          } else {
            finalData.push(startData[i]);
          }
        }
        return finalData;
      }
    };
  });
})();<|endoftext|>


<commit_before>import {stringToSlug} from './slug';

export default class GroupedMetaData {
  static to(data) {
    const ret = {
      name: data.name,
      nameSlug: stringToSlug(data.name),
      groups: {}
    };
    const groups = data.groups;
    for (let groupName in  groups) {
      const items = itemsFromGroup(groups[groupName].items, groupName);
      const slug = stringToSlug(groupName);
      ret.groups[groupName] = {items, slug, name: groupName};
    }
    return ret;
  }
}

function itemsFromGroup(items, groupName) {
  let newItems = [];
  for (let id in items) {
    const item = cloneObject(items[id]);
    item.groupName = groupName;
    item.id = id;
    newItems.push(item);
  }
  return newItems;
}
function cloneObject(obj) {
  return JSON.parse(JSON.stringify(obj));
}<commit_msg>MOdernize code a bit.<commit_after>import {stringToSlug} from './slug';

export default class GroupedMetaData {
  static to(data) {
    const ret = {
      name: data.name,
      nameSlug: stringToSlug(data.name),
      groups: {}
    };
    const groups = data.groups;
    for (let groupName in  groups) {
      const items = itemsFromGroup(groups[groupName].items, groupName);
      const slug = stringToSlug(groupName);
      ret.groups[groupName] = {items, slug, name: groupName};
    }
    return ret;
  }
}

const itemsFromGroup = (items, groupName) => {
  const newItems = [];
  for (let id in items) {
    const item = cloneObject(items[id]);
    item.groupName = groupName;
    item.id = id;
    newItems.push(item);
  }
  return newItems;
};

const cloneObject = obj => JSON.parse(JSON.stringify(obj));
<|endoftext|>


<commit_before>'use strict';

var Immutable = require('immutable');
var xtend = require('xtend');
var Handler = require('./handlers');
var { translatePoint } = require('../util');

/**
 * Polygon geometry object
 *
 * @param {Object} map - Instance of MapboxGl Map
 * @param {Object} drawStore - The drawStore for this session
 * @param {Object} data - GeoJSON polygon feature
 * @return {Polygon} this
 */
function Polygon(map, drawStore, data) {

  this.initialize(map, drawStore, 'Polygon', data);

  // event handlers
  this.addVertex = this._addVertex.bind(this);
  this.onMouseMove = this._onMouseMove.bind(this);
  this.completeDraw = this._completeDraw.bind(this);

}

Polygon.prototype = xtend(Handler, {

  startDraw() {
    this._map.fire('draw.start', { featureType: 'polygon' });
    this._map.getContainer().classList.add('mapboxgl-draw-activated');
    this._map.on('click', this.addVertex);
    this._map.on('dblclick', this.completeDraw);
  },

  _addVertex(e) {
    var p = [ e.latLng.lng, e.latLng.lat ];

    if (this.editting) {
      var c = this.coordinates.get(0).splice(-1, 0, p);
      this.coordinates = this.coordinates.set(0, c);
    } else {
      this.editting = true;
      this.coordinates = Immutable.fromJS([[ p, p ]]);
      this._map.getContainer().addEventListener('mousemove', this.onMouseMove);
    }

    this.feature = this.feature.setIn(['geometry', 'coordinates'], this.coordinates);
    this.store.update(this.feature.toJS());
  },

  _onMouseMove(e) {
    var coords = this._map.unproject([e.x, e.y]);
    var c = this.coordinates.get(0).splice(-1, 0, [ coords.lng, coords.lat ]);
    var temp = this.coordinates.set(0, c);
    this.store.update(this.feature.setIn(['geometry', 'coordinates'], temp).toJS());
  },

  _completeDraw() {
    this._map.getContainer().classList.remove('mapboxgl-draw-activated');
    this._map.off('click', this.addVertex);
    this._map.off('dblclick', this.completeDraw);
    this._map.getContainer().removeEventListener('mousemove', this.onMouseMove);
    this._map.getContainer().classList.remove('mapboxgl-draw-activated');

    this._done('polygon');
  },

  /**
   * Update the position of a vertex in the polygon
   *
   * @param {Array<Number>} init - the position of the mouse at the start of the drag
   * @param {Array<Number>} curr - the current position of the mouse
   * @param {Number} idx - the index of the point being updated in `feature.geometry.coordinates`
   */
  moveVertex(init, curr, idx) {
    if (!this.movingVertex) {
      this.movingVertex = true;
      this.initCoords = this.feature.getIn(['geometry', 'coordinates', 0, idx]);
    }

    var dx = curr.x - init.x;
    var dy = curr.y - init.y;
    var newPoint = translatePoint(this.initCoords, dx, dy, this._map);

    this.feature = this.feature.setIn(['geometry', 'coordinates', 0, idx], Immutable.fromJS(newPoint));
    if (idx === 0)
      this.feature = this.feature.setIn(['geometry', 'coordinates', 0, -1], Immutable.fromJS(newPoint));

    this.store.update(this.feature.toJS());
  },

  /**
   * Add a new vertex to a polygon in edit mode
   *
   * @param {Object} coords - The coordinates of the new vertex in the for { lng: <Number>, lat: <Number> }
   * @param {Number} idx - the index at which the new point will be placed in `feature.geometry.coordinates`
   */
  editAddVertex(coords, idx) {
    coords = this._map.unproject(coords);
    var newCoords = this.feature.getIn(['geometry', 'coordinates', 0]).splice(idx, 0, [ coords.lng, coords.lat ]);
    this.feature = this.feature.setIn(['geometry', 'coordinates', 0], newCoords);
    this.store.update(this.feature.toJS());
  }

});

module.exports = Polygon;
<commit_msg>use immutable for the new vertex<commit_after>'use strict';

var Immutable = require('immutable');
var xtend = require('xtend');
var Handler = require('./handlers');
var { translatePoint } = require('../util');

/**
 * Polygon geometry object
 *
 * @param {Object} map - Instance of MapboxGl Map
 * @param {Object} drawStore - The drawStore for this session
 * @param {Object} data - GeoJSON polygon feature
 * @return {Polygon} this
 */
function Polygon(map, drawStore, data) {

  this.initialize(map, drawStore, 'Polygon', data);

  // event handlers
  this.addVertex = this._addVertex.bind(this);
  this.onMouseMove = this._onMouseMove.bind(this);
  this.completeDraw = this._completeDraw.bind(this);

}

Polygon.prototype = xtend(Handler, {

  startDraw() {
    this._map.fire('draw.start', { featureType: 'polygon' });
    this._map.getContainer().classList.add('mapboxgl-draw-activated');
    this._map.on('click', this.addVertex);
    this._map.on('dblclick', this.completeDraw);
  },

  _addVertex(e) {
    var p = [ e.latLng.lng, e.latLng.lat ];

    if (this.editting) {
      var c = this.coordinates.get(0).splice(-1, 0, p);
      this.coordinates = this.coordinates.set(0, c);
    } else {
      this.editting = true;
      this.coordinates = Immutable.fromJS([[ p, p ]]);
      this._map.getContainer().addEventListener('mousemove', this.onMouseMove);
    }

    this.feature = this.feature.setIn(['geometry', 'coordinates'], this.coordinates);
    this.store.update(this.feature.toJS());
  },

  _onMouseMove(e) {
    var coords = this._map.unproject([e.x, e.y]);
    var c = this.coordinates.get(0).splice(-1, 0, [ coords.lng, coords.lat ]);
    var temp = this.coordinates.set(0, c);
    this.store.update(this.feature.setIn(['geometry', 'coordinates'], temp).toJS());
  },

  _completeDraw() {
    this._map.getContainer().classList.remove('mapboxgl-draw-activated');
    this._map.off('click', this.addVertex);
    this._map.off('dblclick', this.completeDraw);
    this._map.getContainer().removeEventListener('mousemove', this.onMouseMove);
    this._map.getContainer().classList.remove('mapboxgl-draw-activated');

    this._done('polygon');
  },

  /**
   * Update the position of a vertex in the polygon
   *
   * @param {Array<Number>} init - the position of the mouse at the start of the drag
   * @param {Array<Number>} curr - the current position of the mouse
   * @param {Number} idx - the index of the point being updated in `feature.geometry.coordinates`
   */
  moveVertex(init, curr, idx) {
    if (!this.movingVertex) {
      this.movingVertex = true;
      this.initCoords = this.feature.getIn(['geometry', 'coordinates', 0, idx]);
    }

    var dx = curr.x - init.x;
    var dy = curr.y - init.y;
    var newPoint = translatePoint(this.initCoords.toJS(), dx, dy, this._map);

    this.feature = this.feature.setIn(['geometry', 'coordinates', 0, idx], Immutable.fromJS(newPoint));
    if (idx === 0)
      this.feature = this.feature.setIn(['geometry', 'coordinates', 0, -1], Immutable.fromJS(newPoint));

    this.store.update(this.feature.toJS());
  },

  /**
   * Add a new vertex to a polygon in edit mode
   *
   * @param {Object} coords - The coordinates of the new vertex in the for { lng: <Number>, lat: <Number> }
   * @param {Number} idx - the index at which the new point will be placed in `feature.geometry.coordinates`
   */
  editAddVertex(coords, idx) {
    coords = this._map.unproject(coords);
    var newCoords = this.feature.getIn(['geometry', 'coordinates', 0]).splice(idx, 0, Immutable.fromJS([ coords.lng, coords.lat ]));
    this.feature = this.feature.setIn(['geometry', 'coordinates', 0], newCoords);
    this.store.update(this.feature.toJS());
  }

});

module.exports = Polygon;
<|endoftext|>


<commit_before>import fs from 'fs';
import XLSX from 'xlsx';
import d3 from 'd3';
import schemas from '../schemas';
import { remote, app, shell } from 'electron'; // native electron module
import Excel from 'exceljs';

var exportToExcel= function(data,headers,width,nameSheet,lengthApbdesCode){
	var workbook = new Excel.Workbook();
	workbook.creator = "Sideka";
	workbook.created = new Date();
	var sheet = workbook.addWorksheet(nameSheet);
	var worksheet = workbook.getWorksheet(nameSheet);
	var dataHeader =[];
	var style={
		font : { name: 'Times New Roman', family: 4, size: 11, bold: true },
		alignment: { vertical: "middle", horizontal: "center" },
		border: {top: {style:'thin'},left: {style:'thin'},bottom: {style:'thin'},right: {style:'thin'}}

	};

	//headers
	if(nameSheet.toLowerCase() !=="apbdes"){
		for(var C = 0; C != headers.length; ++C) {
			dataHeader.push({
				header:headers[C],
				width:width[C]
			})
		}
	}else{
		for(var C = 0; C != headers.length; ++C) {
			if(C == 0){
				for(var i=0; i != lengthApbdesCode; i++){
					dataHeader.push({
						header:"Kode Rekening",
						width:4
					})
				}
			}
			else{
				dataHeader.push({
					header:headers[C],
					width:width[C]
				})
			}
		}

	}
	worksheet.columns=dataHeader;

	if(nameSheet.toLowerCase() !=="apbdes"){
		//apply number format
		if(nameSheet.toLowerCase()==="data penduduk")
			var indexNIK = headers.indexOf("NIK");
		else if(nameSheet === "Data Keluarga")
			var indexNIK = headers.indexOf("NIK Kepala Keluarga");
		var indexNoKK = headers.indexOf("No KK");

		worksheet.getColumn(++indexNIK).numFmt = '@';
		worksheet.getColumn(++indexNoKK).numFmt = '@';

		worksheet.views = [{state: 'frozen', ySplit: 1, activeCell: 'A1'}];
	}else{
		var indexAnggaran;
		var col = String.fromCharCode(64 + lengthApbdesCode);

		worksheet.mergeCells('A1:'+col+1);
		dataHeader.some((elem, i) => {
			return elem.header === 'Anggaran' ? (indexAnggaran = i, true) : false;
		});
		worksheet.getColumn(++indexAnggaran).numFmt  = '#,##0';;
	}
	//data
	for(var R = 0; R < data.length; ++R) {
		var dataRow=[];
		for(var C = 0; C != data[R].length; ++C) {
			dataRow[C] = data[R][C];
		}
		worksheet.addRow(dataRow);
	}

	//apply style
	worksheet.getRow(1).font = style.font;
	worksheet.getRow(1).alignment = style.alignment;

	var fileName = remote.dialog.showSaveDialog({
		filters: [
			{name: 'Excel Workbook', extensions: ['xlsx']},
		]
	});

	if(fileName){
		workbook.xlsx.writeFile(fileName).then(
			function() {
				shell.openItem(fileName);
			},
			function(e){
				var message = "File Masih Digunakan"
				if(e.code != "EBUSY")
					message = e.message;
				remote.dialog.showErrorBox("Error", message);
		});
	}
}

var convertWidth = function(width){
	var data = [];
	for(var i=0; i != width.length; i++){
		data.push(width[i]/7);
	}
	return data;
}

var splitAccountCode = function(data, maxLengthCode){
	var result=[];
	for(var i = 0; i != data.length;i++){
		var resultSplit =[];
		for(var x = 0; x != data[i].length; x++){
			if(x==0){
				var accountCode=[];
				if(data[i][x]!= null) accountCode = data[i][0].split(".");
				for(var j=0;j != maxLengthCode;j++){
					if(accountCode[j]) resultSplit.push(parseInt(accountCode[j]));
					else resultSplit.push(null);
				}
			}else
				resultSplit.push(data[i][x]);
		}
		result.push(resultSplit);
	}
	return result;
}

var getMaxLengthCode = function(accountCodes){
	accountCodes = accountCodes.filter(c=>c != null);
	var longest = accountCodes.sort((a, b) => { return b.length - a.length; })[0];
	var maxLengthCode = longest.split(".");
	return maxLengthCode.length;
}

export var exportPenduduk = function(data, nameSheet)
{
    var headers = schemas.getHeader(schemas.penduduk);
	var width = convertWidth(schemas.getColWidths(schemas.penduduk));
	exportToExcel(data,headers,width,nameSheet);

};

export var exportKeluarga = function(data,nameSheet)
{
	var headers = schemas.getHeader(schemas.keluarga);
	var width = convertWidth(schemas.getColWidths(schemas.penduduk));
	exportToExcel(data,headers,width,nameSheet);

};

export var exportApbdes = function(data, nameSheet)
{
	var accountCodes = data.map(c => c[0]);
	var maxLengthCode = getMaxLengthCode(accountCodes);
	var result = splitAccountCode(data, maxLengthCode);
	var headers = schemas.getHeader(schemas.apbdes);
	var width = convertWidth(schemas.getColWidths(schemas.apbdes));
	exportToExcel(result,headers,width,nameSheet,maxLengthCode);
};
<commit_msg>add currency in apbdes<commit_after>import fs from 'fs';
import XLSX from 'xlsx';
import d3 from 'd3';
import schemas from '../schemas';
import { remote, app, shell } from 'electron'; // native electron module
import Excel from 'exceljs';

var exportToExcel= function(data,headers,width,nameSheet,lengthApbdesCode){
	var workbook = new Excel.Workbook();
	workbook.creator = "Sideka";
	workbook.created = new Date();
	var sheet = workbook.addWorksheet(nameSheet);
	var worksheet = workbook.getWorksheet(nameSheet);
	var dataHeader =[];
	var style={
		font : { name: 'Times New Roman', family: 4, size: 11, bold: true },
		alignment: { vertical: "middle", horizontal: "center" },
		border: {top: {style:'thin'},left: {style:'thin'},bottom: {style:'thin'},right: {style:'thin'}}

	};

	//headers
	if(nameSheet.toLowerCase() !=="apbdes"){
		for(var C = 0; C != headers.length; ++C) {
			dataHeader.push({
				header:headers[C],
				width:width[C]
			})
		}
	}else{
		for(var C = 0; C != headers.length; ++C) {
			if(C == 0){
				for(var i=0; i != lengthApbdesCode; i++){
					dataHeader.push({
						header:"Kode Rekening",
						width:4,
						style: {alignment: {horizontal: "center" }}
					})
				}
			}
			else{
				dataHeader.push({
					header:headers[C],
					width:width[C]
				})
			}
		}

	}
	worksheet.columns=dataHeader;

	if(nameSheet.toLowerCase() !=="apbdes"){
		//apply number format
		if(nameSheet.toLowerCase()==="data penduduk")
			var indexNIK = headers.indexOf("NIK");
		else if(nameSheet.toLowerCase() === "data keluarga")
			var indexNIK = headers.indexOf("NIK Kepala Keluarga");
		var indexNoKK = headers.indexOf("No KK");

		worksheet.getColumn(++indexNIK).numFmt = '@';
		worksheet.getColumn(++indexNoKK).numFmt = '@';

		worksheet.views = [{state: 'frozen', ySplit: 1, activeCell: 'A1'}];
	}else{
		var indexAnggaran;
		var col = String.fromCharCode(64 + lengthApbdesCode);

		worksheet.mergeCells('A1:'+col+1);
		dataHeader.some((elem, i) => {
			return elem.header === 'Anggaran' ? (indexAnggaran = i, true) : false;
		});
		worksheet.getColumn(++indexAnggaran).numFmt  = '_([$Rp-id-ID]* #,##0_);_([$Rp-id-ID]* (#,##0);_([$Rp-id-ID]* "-"_);_(@_)';;
	}
	//data
	for(var R = 0; R < data.length; ++R) {
		var dataRow=[];
		for(var C = 0; C != data[R].length; ++C) {
			dataRow[C] = data[R][C];
		}
		worksheet.addRow(dataRow);
	}

	//apply style
	worksheet.getRow(1).font = style.font;
	worksheet.getRow(1).alignment = style.alignment;

	var fileName = remote.dialog.showSaveDialog({
		filters: [
			{name: 'Excel Workbook', extensions: ['xlsx']},
		]
	});

	if(fileName){
		workbook.xlsx.writeFile(fileName).then(
			function() {
				shell.openItem(fileName);
			},
			function(e){
				var message = "File Masih Digunakan"
				if(e.code != "EBUSY")
					message = e.message;
				remote.dialog.showErrorBox("Error", message);
		});
	}
}

var convertWidth = function(width){
	var data = [];
	for(var i=0; i != width.length; i++){
		data.push(width[i]/7);
	}
	return data;
}

var splitAccountCode = function(data, maxLengthCode){
	var result=[];
	for(var i = 0; i != data.length;i++){
		var resultSplit =[];
		for(var x = 0; x != data[i].length; x++){
			if(x==0){
				var accountCode=[];
				if(data[i][x]!= null) accountCode = data[i][0].split(".");
				for(var j=0;j != maxLengthCode;j++){
					if(accountCode[j]) resultSplit.push(parseInt(accountCode[j]));
					else resultSplit.push(null);
				}
			}else
				resultSplit.push(data[i][x]);
		}
		result.push(resultSplit);
	}
	return result;
}

var getMaxLengthCode = function(accountCodes){
	accountCodes = accountCodes.filter(c=>c != null);
	var longest = accountCodes.sort((a, b) => { return b.length - a.length; })[0];
	var maxLengthCode = longest.split(".");
	return maxLengthCode.length;
}

export var exportPenduduk = function(data, nameSheet)
{
    var headers = schemas.getHeader(schemas.penduduk);
	var width = convertWidth(schemas.getColWidths(schemas.penduduk));
	exportToExcel(data,headers,width,nameSheet);

};

export var exportKeluarga = function(data,nameSheet)
{
	var headers = schemas.getHeader(schemas.keluarga);
	var width = convertWidth(schemas.getColWidths(schemas.penduduk));
	exportToExcel(data,headers,width,nameSheet);

};

export var exportApbdes = function(data, nameSheet)
{
	var accountCodes = data.map(c => c[0]);
	var maxLengthCode = getMaxLengthCode(accountCodes);
	var result = splitAccountCode(data, maxLengthCode);
	var headers = schemas.getHeader(schemas.apbdes);
	var width = convertWidth(schemas.getColWidths(schemas.apbdes));
	exportToExcel(result,headers,width,nameSheet,maxLengthCode);
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import * as actionCore from '../core/action-core';
import {createJsonRoute, throwStatus} from '../util/express';
import {assert} from '../validation';
import * as imageHttp from './image-http';
import * as eventHttp from './event-http';
import * as throttleCore from '../core/throttle-core';
import * as commentCore from '../core/comment-core';

let postAction = createJsonRoute(function(req, res) {
  const action = assert(req.body, 'action');

  if (_.isString(action.text) && action.text.trim().length === 0) {
    throwStatus(400, 'Text cannot be empty.');
  }

  if (!req.client.id) {
    throwStatus(403);
  }

  return throttleCore.canDoAction(action.user, action.type)
    .then(canDoAction => {
      if (!canDoAction) {
        throwStatus(429, `Too many actions of type ${ action.type }`);
      }

      let handleAction;
      if (action.type === 'IMAGE') {
        handleAction = imageHttp.postImage(req, res, action);
      } else if (action.type === 'COMMENT') {
        handleAction = commentCore.comment(action);
      } else {
        action.ip = req.ip;
        action.isBanned = req.client.isBanned;

        handleAction = actionCore.getActionType(action.type)
        .then(type => {
          if (type === null) {
            throwStatus(400, 'Action type ' + action.type + ' does not exist');
          } else if (type.code === 'CHECK_IN_EVENT') {
            return eventHttp.isValidCheckIn(action);
          } else {
            return Promise.resolve();
          }
        })
        .then(() => actionCore.createAction(_.merge(action, {client: req.client})));
      }

      return handleAction
        .then(() => throttleCore.executeAction(action.user, action.type))
        .then(() => undefined);
    });
});

export {
  postAction
};
<commit_msg>Pass a more detailed client info to comment-core<commit_after>import _ from 'lodash';
import * as actionCore from '../core/action-core';
import {createJsonRoute, throwStatus} from '../util/express';
import {assert} from '../validation';
import * as imageHttp from './image-http';
import * as eventHttp from './event-http';
import * as throttleCore from '../core/throttle-core';
import * as commentCore from '../core/comment-core';

let postAction = createJsonRoute(function(req, res) {
  const action = assert(req.body, 'action');

  if (_.isString(action.text) && action.text.trim().length === 0) {
    throwStatus(400, 'Text cannot be empty.');
  }

  if (!req.client.id) {
    throwStatus(403);
  }

  return throttleCore.canDoAction(action.user, action.type)
    .then(canDoAction => {
      if (!canDoAction) {
        throwStatus(429, `Too many actions of type ${ action.type }`);
      }

      let handleAction;
      if (action.type === 'IMAGE') {
        handleAction = imageHttp.postImage(req, res, action);
      } else if (action.type === 'COMMENT') {
        handleAction = commentCore.comment(_.merge(action, {client: req.client}));
      } else {
        action.ip = req.ip;
        action.isBanned = req.client.isBanned;

        handleAction = actionCore.getActionType(action.type)
        .then(type => {
          if (type === null) {
            throwStatus(400, 'Action type ' + action.type + ' does not exist');
          } else if (type.code === 'CHECK_IN_EVENT') {
            return eventHttp.isValidCheckIn(action);
          } else {
            return Promise.resolve();
          }
        })
        .then(() => actionCore.createAction(_.merge(action, {client: req.client})));
      }

      return handleAction
        .then(() => throttleCore.executeAction(action.user, action.type))
        .then(() => undefined);
    });
});

export {
  postAction
};
<|endoftext|>


<commit_before>$(document).ready(function() {
// static stuff
var ref = new Firebase("***firebase-url***");
var socket = io();
var canPost = true;
var authData;
var lastUser;
var unreadMessages =  false;
var soundEnabledText = "Sound enabled";
var soundDisabledText = "Mentions Only";
var lostConnection = false;
var ServerUser = {name: "Server", tags: "Server", image: "", colour: "inherit"};

var msgbox = $("#message");

$('.helpButton').click(function() {
  $('.about-box').fadeIn(function() {
    $('.close-button').click(function() {
      $('.about-box').fadeOut()
    });
  })
});

function updateSoundPrefButton(){
  // Check localstorage
  if (localStorage.getItem("soundPref") === null){
    localStorage.setItem("soundPref", 1)
  }else if (localStorage.getItem("soundPref") == 1){
    document.getElementById("soundPref").innerHTML = soundEnabledText;
  }else{
    document.getElementById("soundPref").innerHTML = soundDisabledText;
  }
}
updateSoundPrefButton();

$("#soundPref").click(toggleSoundPref);

function toggleSoundPref(){
  if (localStorage.getItem("soundPref") == "1"){
    localStorage.setItem("soundPref", 0);
  } else {
    localStorage.setItem("soundPref", 1);
  }

  updateSoundPrefButton()
}

function updateTitle() {
  var title= $(document).find("title");
  console.log(title);
  if (unreadMessages){
    if (title.text().charAt(0) != "*" ){
      title.text("* " + title.text())
    }
  }else{
    if (title.text().charAt(0) == "*"){
      title.text(title.text().substring(2));
    }
  }
}

window.onfocus = function() {
  unreadMessages = false;
  updateTitle();
};

//function showMessage(msg, user, tags, imageLink, colour) {
//  msg = emojione.toImage(msg);
//
//  var messageElement;
//  if (user == 'RubyBot' && lastUser != 'RubyBot') {
//    messageElement = $('
').html(
//      '' +
//      '
' +
//      '@' + user + '' + tags + '' +
//      '
' + msg + '

'
//    );
//
//  } else if (user == 'Server') {
//    messageElement = $('
').html('' + user + '' + ': ' + msg);
//
//  } else {
//    if (user == lastUser) {
//      messageElement = $('#messages li').last();
//      messageElement.find(".message").append("
" + msg + "
");
//    } else if (!imageLink || imageLink == ''){
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    } else {
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    }
//
//
//  }
//  lastUser = user;
//  messageElement.linkify({
//    target: "_blank"
//  });
//
//  $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
//
//  if (document.hasFocus() == false){
//    unreadMessages = true;
//    updateTitle();
//    var nameFormatted = authData.twitter.username;
//    if (msg.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
//        var audio = new Audio('/assets/sound/Ding.mp3');
//        audio.play();
//    }else{
//      if (localStorage.getItem("soundPref") == "1"){
//        var audio = new Audio('/assets/sound/pop.ogg');
//        audio.play();
//      }
//    }
//  }
//}
function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  if (hours.length == 0){
    hours = "0" + hours
  }
  if (minutes.length == 0){
    minutes = "0" + minutes
  }
  return hours + ":" + minutes
}

function SayAsServer(message){
  showMessage({text: message, timestamp: Date.now()}, ServerUser)
}

function showMessage(message, user){
  var msgClass = "msg";
  var hasImage = Boolean(user.image);
  var wasLastUser = lastUser == user.name;
  var canTweet = true;
  console.log(user);

  var twitterUser = user.name;
  var href = "https://twitter.com/"+ user + "/";

  if (user.name == "Server"){
    msgClass = "server-msg";
    hasImage = false;
    wasLastUser = false;
    canTweet = false;
    href = "http://yrs.io";
  }
  var messageElement = $('
');

  if (hasImage) {
    messageElement.html('')
  }
  messageElement.html(messageElement.html()+
    '
' +
    '' + '@' + user.name + '' +
    '' + user.tags + '' + formatTimestamp(message.timestamp) + '' +
    '
' + message.text + '
'
  );

  if(canTweet){
    messageElement.html(messageElement.html() + '' +
      'Tweet')
  }

  lastUser = user.name;
  messageElement.linkify({
    target: "_blank"
  });

  messageElement.html(messageElement.html() + '
');

  $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");

  if(canTweet){
    twttr.widgets.load()
  }

  if (!document.hasFocus()){
    unreadMessages = true;
    updateTitle();
    var nameFormatted = authData.twitter.username;
    if (msg.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
        var audio = new Audio('/assets/sound/Ding.mp3');
        audio.play();
    }else{
      if (localStorage.getItem("soundPref") == "1"){
        var audio = new Audio('/assets/sound/pop.ogg');
        audio.play();
      }
    }
  }
}

// firebase stuff
ref.onAuth(function(data) {
  authData = data;
  if (!data){
    $('.twitter').css("display", "block")
  } else {
    socket.emit("user join", data.token, data.twitter.username, data.twitter.profileImageURL);
  }
});

$('#twitter-button').click(function() {
  ref.authWithOAuthPopup("twitter", function(error, data) {
    if (error) {
      console.log("Login Failed!", error);
    } else {
      $('.twitter').fadeOut()
    }
  });
  return false;
});

ref.getAuth();

$('form').submit(function(){
  if(canPost == false){
    showMessage('Please do not spam!', 'Server', '');
  } else {
    socket.emit('chat message',
      msgbox.val(),
      authData.token,
      function(response) {
        if (response.status == "failed"){
          showMessage(response.message, ServerUser);
        }
      }
    );
    canPost=false;
    setTimeout(function(){canPost=true},500);
  }
  msgbox.val('');
  return false;
});

socket.on("connect", function(){
  if (!authData) return;
  if (!lostConnection) return;
  SayAsServer("You have reconnected to the server.");
  socket.emit("user join", authData.token, authData.twitter.username, authData.twitter.profileImageURL);
  lostConnection = false;
});

socket.on("disconnect", function(){
  SayAsServer("You have been temporarlly disconnected from the server.");
  lostConnection = true;
});

socket.on('chat message', function(message, user) {
  showMessage(message, user);
});

socket.on("user join", function(user) {
  SayAsServer(user.name + " has joined!")
});

socket.on("user leave", function(user) {
  SayAsServer(user.name + " has left.")
});

window.setInterval(function() {
  socket.emit("user ping", authData.token)
}, 5000);

$(window).unload(function() {
  socket.emit("user leave", authData.token);
})
});

window.onbeforeunload = function(){
    return "Closing the window will disconnect your from YRS Chat";
};
<commit_msg>Finish message reformatting (twitter still broken)<commit_after>$(document).ready(function() {
// static stuff
var ref = new Firebase("***firebase-url***");
var socket = io();
var canPost = true;
var authData;
var lastUser;
var unreadMessages =  false;
var soundEnabledText = "Sound enabled";
var soundDisabledText = "Mentions Only";
var lostConnection = false;
var ServerUser = {name: "Server", tags: "Server", image: "", colour: "inherit"};

var msgbox = $("#message");

$('.helpButton').click(function() {
  $('.about-box').fadeIn(function() {
    $('.close-button').click(function() {
      $('.about-box').fadeOut()
    });
  })
});

function updateSoundPrefButton(){
  // Check localstorage
  if (localStorage.getItem("soundPref") === null){
    localStorage.setItem("soundPref", 1)
  }else if (localStorage.getItem("soundPref") == 1){
    document.getElementById("soundPref").innerHTML = soundEnabledText;
  }else{
    document.getElementById("soundPref").innerHTML = soundDisabledText;
  }
}
updateSoundPrefButton();

$("#soundPref").click(toggleSoundPref);

function toggleSoundPref(){
  if (localStorage.getItem("soundPref") == "1"){
    localStorage.setItem("soundPref", 0);
  } else {
    localStorage.setItem("soundPref", 1);
  }

  updateSoundPrefButton()
}

function updateTitle() {
  var title= $(document).find("title");
  console.log(title);
  if (unreadMessages){
    if (title.text().charAt(0) != "*" ){
      title.text("* " + title.text())
    }
  }else{
    if (title.text().charAt(0) == "*"){
      title.text(title.text().substring(2));
    }
  }
}

window.onfocus = function() {
  unreadMessages = false;
  updateTitle();
};

//function showMessage(msg, user, tags, imageLink, colour) {
//  msg = emojione.toImage(msg);
//
//  var messageElement;
//  if (user == 'RubyBot' && lastUser != 'RubyBot') {
//    messageElement = $('
').html(
//      '' +
//      '
' +
//      '@' + user + '' + tags + '' +
//      '
' + msg + '

'
//    );
//
//  } else if (user == 'Server') {
//    messageElement = $('
').html('' + user + '' + ': ' + msg);
//
//  } else {
//    if (user == lastUser) {
//      messageElement = $('#messages li').last();
//      messageElement.find(".message").append("
" + msg + "
");
//    } else if (!imageLink || imageLink == ''){
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    } else {
//      messageElement = $('
').html(
//        '' +
//        '
' +
//        '@' + user + '' + tags + '' +
//        '
' + msg + '

'
//      );
//    }
//
//
//  }
//  lastUser = user;
//  messageElement.linkify({
//    target: "_blank"
//  });
//
//  $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
//
//  if (document.hasFocus() == false){
//    unreadMessages = true;
//    updateTitle();
//    var nameFormatted = authData.twitter.username;
//    if (msg.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
//        var audio = new Audio('/assets/sound/Ding.mp3');
//        audio.play();
//    }else{
//      if (localStorage.getItem("soundPref") == "1"){
//        var audio = new Audio('/assets/sound/pop.ogg');
//        audio.play();
//      }
//    }
//  }
//}
function formatTimestamp(timestamp) {
  var date = new Date(timestamp);
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  if (hours.length == 1){
    hours = "0" + hours
  }
  if (minutes.length == 1){
    minutes = "0" + minutes
  }
  return hours + ":" + minutes
}

function SayAsServer(message){
  showMessage({text: message, timestamp: Date.now()}, ServerUser)
}

function showMessage(message, user){
  message.text = emojione.toImage(message.text);

  var msgClass = "msg";
  var hasImage = Boolean(user.image);
  var wasLastUser = lastUser == user.name;
  var canTweet = true;
  console.log(user);

  var twitterUser = user.name;
  var href = "https://twitter.com/"+ user + "/";

  if (user.name == "Server"){
    msgClass = "server-msg";
    hasImage = false;
    wasLastUser = false;
    canTweet = false;
    href = "http://yrs.io";
  } else if (user.name == "RubyBot") {
    msgClass = "bot-msg";
    canTweet = false;
    href = "http://twitter.com/YRSChat"
  }

  var messageElement = $('
');

  if (!wasLastUser) {
    if (hasImage) {
      messageElement.html('')
    }

    messageElement.html(messageElement.html()+
      '
' +
      '' + '@' + user.name + '' +
      '' + user.tags + '' + formatTimestamp(message.timestamp) + '' +
      '
' + message.text + '
'
    );

    if(canTweet){
      messageElement.html(messageElement.html() + '' +
        'Tweet'
      )
    }

    messageElement.html(messageElement.html() + '
');
  } else {
    messageElement = $('#messages li').last();

    if (canTweet){
      messageElement.find(".message").append(
        "
" + message.text + "
" +
        '' +
        'Tweet'
      );
    }
  }

  lastUser = user.name;
  messageElement.linkify({
    target: "_blank"
  });

  if (!wasLastUser){
    $('#messages').append(messageElement).animate({scrollTop: 1000000}, "slow");
  }

  if(canTweet){
    twttr.widgets.load()
  }

  if (!document.hasFocus()){
    unreadMessages = true;
    updateTitle();
    var nameFormatted = authData.twitter.username;
    if (message.text.toLowerCase().indexOf(nameFormatted.toLowerCase()) !== -1){
        var audio = new Audio('/assets/sound/Ding.mp3');
        audio.play();
    }else{
      if (localStorage.getItem("soundPref") == "1"){
        var audio = new Audio('/assets/sound/pop.ogg');
        audio.play();
      }
    }
  }
}

// firebase stuff
ref.onAuth(function(data) {
  authData = data;
  if (!data){
    $('.twitter').css("display", "block")
  } else {
    socket.emit("user join", data.token, data.twitter.username, data.twitter.profileImageURL);
  }
});

$('#twitter-button').click(function() {
  ref.authWithOAuthPopup("twitter", function(error, data) {
    if (error) {
      console.log("Login Failed!", error);
    } else {
      $('.twitter').fadeOut()
    }
  });
  return false;
});

ref.getAuth();

$('form').submit(function(){
  if(canPost == false){
    showMessage('Please do not spam!', 'Server', '');
  } else {
    socket.emit('chat message',
      msgbox.val(),
      authData.token,
      function(response) {
        if (response.status == "failed"){
          showMessage(response.message, ServerUser);
        }
      }
    );
    canPost=false;
    setTimeout(function(){canPost=true},500);
  }
  msgbox.val('');
  return false;
});

socket.on("connect", function(){
  if (!authData) return;
  if (!lostConnection) return;
  SayAsServer("You have reconnected to the server.");
  socket.emit("user join", authData.token, authData.twitter.username, authData.twitter.profileImageURL);
  lostConnection = false;
});

socket.on("disconnect", function(){
  SayAsServer("You have been temporarlly disconnected from the server.");
  lostConnection = true;
});

socket.on('chat message', function(message, user) {
  showMessage(message, user);
});

socket.on("user join", function(user) {
  SayAsServer(user.name + " has joined!")
});

socket.on("user leave", function(user) {
  SayAsServer(user.name + " has left.")
});

window.setInterval(function() {
  socket.emit("user ping", authData.token)
}, 5000);

$(window).unload(function() {
  socket.emit("user leave", authData.token);
})
});

window.onbeforeunload = function(){
    return "Closing the window will disconnect your from YRS Chat";
};
<|endoftext|>


<commit_before>(function(){
  var $searchButton,
      $originInput,
      $destinationInput,
      $clearButton,
      $metricsContent,
      options = {
          modes: ['walking', 'biking', 'transit', 'driving'],
          metrics: ['cost', 'duration', 'calories', 'emissions']
      },
      metricsEjs = new EJS({url: 'views/metrics.ejs'}),
      log = function(toLog) {
        if (window.console && window.console.log) {
          window.console.log(toLog);
        }
      };

  var renderers = {
    'km': function(val) {
      return {
        value: (val * 0.62137).toFixed(1),
        label: 'miles'
      };
    },
    'sec': function(val) {
      return {
        value: (val / 60).toFixed(0),
        label: 'minutes'
      };
    },
    'kg_co2': function(val) {
      return {
        value: (val || 0).toFixed(2),
        label: 'kg of CO2'
      };
    },
    'usd': function(val) {
      return {
        value: '$' + (val || 0).toFixed(2),
        label: ' '
      };
    },
    'cal': function(val) {
      return {
        value: (val || 0).toFixed(),
        label: 'calories'
      };
    }
  };

  var clearInputs = function() {
    $originInput.val('');
    $destinationInput.val('');
  };

  var formatResults = function(data) {
    var val, i, j, metric, mode, results = {};

    for(j=0; j<options.modes.length; j++) {
      mode = options.modes[j];
      results[mode] = {};

      for (i=0; i<options.metrics.length; i++) {
        metric = options.metrics[i];
        if (metric) {
          results[mode][metric] = renderers[data.units[metric]](data.results[mode][metric]);
        }
      }
    }

    return results;
  };

  var calculate = function(origin, destination) {
    $.mobile.pageLoading();

    $.ajax({
      url: 'info_for_route_bing',
      dataType: 'json',
      data: {
        origin: origin,
        destination: destination
      },
      success: function(data, textStatus, jqXHR) {
        var html = metricsEjs.render({
          modes: options.modes,
          metrics: options.metrics,
          results: formatResults(data)
        });

        $metricsContent.html(html);

        $('#metrics-table th, #metrics-table td').bind('tap', function(evt) {
          $('#plan h1').text(this.parentNode.id);
          $.mobile.changePage('plan');
        });

        $.mobile.changePage('home', {
          transition: 'flip'
        });
      },
      error: function(jqXHR, textStatus, errorThrown) {
        log(errorThrown);
        $.mobile.pageLoading(true);
      },
      complete: function() {
        $.mobile.pageLoading(true);
      }
    });
  };

  var bindEvents = function() {
    $searchButton.tap(function() {
      calculate($originInput.val(), $destinationInput.val());
    });

    $clearButton.tap(clearInputs);
  };

  $('#search').live('pagecreate',function(evt) {
    //Cache vars
    $searchButton = $('#search-button');
    $originInput = $('#origin');
    $destinationInput = $('#destination');
    $clearButton = $('#clear-button');
    $metricsContent = $('#metrics-content');

    bindEvents();
  });
})();<commit_msg>No longer binding tap events to the metrics header.<commit_after>(function(){
  var $searchButton,
      $originInput,
      $destinationInput,
      $clearButton,
      $metricsContent,
      options = {
          modes: ['walking', 'biking', 'transit', 'driving'],
          metrics: ['cost', 'duration', 'calories', 'emissions']
      },
      metricsEjs = new EJS({url: 'views/metrics.ejs'}),
      log = function(toLog) {
        if (window.console && window.console.log) {
          window.console.log(toLog);
        }
      };

  var renderers = {
    'km': function(val) {
      return {
        value: (val * 0.62137).toFixed(1),
        label: 'miles'
      };
    },
    'sec': function(val) {
      return {
        value: (val / 60).toFixed(0),
        label: 'minutes'
      };
    },
    'kg_co2': function(val) {
      return {
        value: (val || 0).toFixed(2),
        label: 'kg of CO2'
      };
    },
    'usd': function(val) {
      return {
        value: '$' + (val || 0).toFixed(2),
        label: ' '
      };
    },
    'cal': function(val) {
      return {
        value: (val || 0).toFixed(),
        label: 'calories'
      };
    }
  };

  var clearInputs = function() {
    $originInput.val('');
    $destinationInput.val('');
  };

  var formatResults = function(data) {
    var val, i, j, metric, mode, results = {};

    for(j=0; j<options.modes.length; j++) {
      mode = options.modes[j];
      results[mode] = {};

      for (i=0; i<options.metrics.length; i++) {
        metric = options.metrics[i];
        if (metric) {
          results[mode][metric] = renderers[data.units[metric]](data.results[mode][metric]);
        }
      }
    }

    return results;
  };

  var calculate = function(origin, destination) {
    $.mobile.pageLoading();

    $.ajax({
      url: 'info_for_route_bing',
      dataType: 'json',
      data: {
        origin: origin,
        destination: destination
      },
      success: function(data, textStatus, jqXHR) {
        var html = metricsEjs.render({
          modes: options.modes,
          metrics: options.metrics,
          results: formatResults(data)
        });

        $metricsContent.html(html);

        $('#metrics-table tbody th, #metrics-table tbody td').bind('tap', function(evt) {
          $('#plan h1').text(this.parentNode.id);
          $.mobile.changePage('plan');
        });

        $.mobile.changePage('home', {
          transition: 'flip'
        });
      },
      error: function(jqXHR, textStatus, errorThrown) {
        log(errorThrown);
        $.mobile.pageLoading(true);
      },
      complete: function() {
        $.mobile.pageLoading(true);
      }
    });
  };

  var bindEvents = function() {
    $searchButton.tap(function() {
      calculate($originInput.val(), $destinationInput.val());
    });

    $clearButton.tap(clearInputs);
  };

  $('#search').live('pagecreate',function(evt) {
    //Cache vars
    $searchButton = $('#search-button');
    $originInput = $('#origin');
    $destinationInput = $('#destination');
    $clearButton = $('#clear-button');
    $metricsContent = $('#metrics-content');

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