<commit_before>/*jshint indent:2, curly:true eqeqeq:true, immed:true, latedef:true,
newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true
white:true*/
/*global XT:true, XM:true, Backbone:true, _:true, console:true, setTimeout: true, enyo:true */

(function () {
  "use strict";

  /**
  */
  _.extend(XT.Session, {
    /** @scope XT.Session */

    privileges: {},
    relevantPrivileges: [], // those privileges that are needed for an active extension
    settings: {},
    schema: {},

    SETTINGS: 0x01,
    PRIVILEGES: 0x02,
    SCHEMA: 0x04,
    LOCALE: 0x08,
    EXTENSIONS: 0x10,
    ALL: 0x01 | 0x02 | 0x04 | 0x08 | 0x10,

    /**
      Loads session objects for settings, preferences and privileges into local
      memory. Types `XT.session.SETTINGS` or `XT.session.PRIVILEGES` can be passed
      as bitwise operators. If no arguments are passed the default is
      `XT.session.ALL` which will load all session objects.

      @param {Number} Types
      @param {Object} Options
    */
    loadSessionObjects: function (types, options) {
      var that = this,
        privilegesOptions,
        privileges,
        settingsOptions,
        settings,
        schemaOptions,
        localeOptions,
        extensionOptions,
        callback,
        schemaCount = 0,
        schemasReturned = 0,
        privilegeSetCount = 0,
        privilegeSetsReturned = 0,
        i;

      if (options && options.success && options.success instanceof Function) {
        callback = options.success;
      } else { callback = XT.K; }

      if (types === undefined) { types = this.ALL; }

      if (types & this.PRIVILEGES) {
        privilegesOptions = options ? _.clone(options) : {};

        // callback
        privilegesOptions.success = function (resp) {
          var privileges, i;

          if (that.getPrivileges().attributes) {
            // add incoming data to already loaded privilege
            privileges = that.getPrivileges();

          } else {
            // create privilege as a new model
            privileges = new Backbone.Model();
            privileges.get = function (attr) {
              // Sometimes the answer is already known...
              if (_.isBoolean(attr)) { return attr; }
              return Backbone.Model.prototype.get.call(this, attr);
            };
          }

          privilegeSetsReturned++;

          // Loop through the response and set a privilege for each found.
          for (i = 0; i < resp.length; i++) {
            privileges.set(resp[i].privilege, resp[i].isGranted);
          }

          // Attach the privileges to the session object.
          that.setPrivileges(privileges);

          if (privilegeSetsReturned === privilegeSetCount) {
            callback();
          }
        };

        if (!privilegesOptions.databaseTypes) {
          // by default we just run one query against the default database type
          privilegesOptions.databaseTypes = [undefined];
        }
        for (i = 0; i < privilegesOptions.databaseTypes.length; i++) {
          privilegesOptions.databaseType = privilegesOptions.databaseTypes[i];
          XT.dataSource.dispatch('XT.Session', 'privileges', null, privilegesOptions);
          privilegeSetCount++;
        }

      }

      if (types & this.SETTINGS) {
        settingsOptions = options ? _.clone(options) : {};

        // callback
        settingsOptions.success = function (resp) {
          settings = new Backbone.Model(resp);

          // Attach the settings to the session object
          that.setSettings(settings);

          callback();
        };

        XT.dataSource.dispatch('XT.Session', 'settings', null, settingsOptions);
      }

      if (types & this.SCHEMA) {
        schemaOptions = options ? _.clone(options) : {};

        // callback
        schemaOptions.success = function (resp) {
          var schema,
            prop,
            Klass,
            relations,
            i;

          if (that.getSchema().attributes) {
            // add incoming data to already loaded schema attributes
            schema = that.getSchema();
            schema.set(resp);

          } else {
            // create schema as a new model
            schema = new Backbone.Model(resp);
            that.setSchema(schema);
          }
          schemasReturned++;

          if (schemasReturned === schemaCount) {
            // Set relations
            for (prop in schema.attributes) {
              if (schema.attributes.hasOwnProperty(prop)) {
                Klass = XM.Model.getObjectByName('XM' + '.' + prop);
                if (Klass) {
                  relations = schema.attributes[prop].relations || [];
                  if (relations.length) {
                    Klass.prototype.relations = [];
                    for (i = 0; i < relations.length; i++) {
                      if (relations[i].type === "Backbone.HasOne") {
                        relations[i].type = Backbone.HasOne;
                      } else if (relations[i].type === "Backbone.HasMany") {
                        relations[i].type = Backbone.HasMany;
                      } else {
                        continue;
                      }
                      Klass.prototype.relations.push(relations[i]);
                    }
                  }

                  privileges = schema.attributes[prop].privileges;
                  if (privileges) {
                    Klass.prototype.privileges = privileges;
                  }
                }
              }
            }
            callback();
          }
        };

        // get schema for instance DB models
        XT.dataSource.dispatch('XT.Session', 'schema', 'xm', schemaOptions);
        schemaCount++;

        // get schema for global DB models
        schemaOptions.databaseType = 'global';
        XT.dataSource.dispatch('XT.Session', 'schema', 'xm', schemaOptions);
        schemaCount++;
      }

      if (types & this.LOCALE) {
        localeOptions = options ? _.clone(options) : {};

        // callback
        localeOptions.success = function (resp) {
          var locale = new Backbone.Model(resp);
          that.setLocale(locale);
          callback();
        };

        XT.dataSource.dispatch('XT.Session', 'locale', null, localeOptions);
      }

      if (types & this.EXTENSIONS) {
        extensionOptions = options ? _.clone(options) : {};

        // callback
        extensionOptions.error = function (resp) {
          XT.log("Error loading extensions");
        };
        extensionOptions.success = function (resp) {
          that.extensions = resp;
          callback();
        };

        XT.dataSource.getExtensionList(extensionOptions);
      }

      return true;
    },

    getLocale: function () {
      return this.locale;
    },

    getSchema: function () {
      return this.schema;
    },

    getSettings: function () {
      return this.settings;
    },

    getPrivileges: function () {
      return this.privileges;
    },

    setLocale: function (value) {
      this.locale = value;
      return this;
    },

    setSchema: function (value) {
      this.schema = value;
      return this;
    },

    setSettings: function (value) {
      this.settings = value;
      return this;
    },

    setPrivileges: function (value) {
      this.privileges = value;
      return this;
    },

    addRelevantPrivileges: function (module, privArray) {
      var privMap = _.map(privArray, function (priv) {return {module: module, privilege: priv};});
      this.relevantPrivileges.add(privMap);
    }

    // ..........................................................
    // CLASS CONSTANTS
    //

    DB_BOOLEAN: 'B',
    DB_STRING: 'S',
    DB_COMPOUND: 'C',
    DB_DATE: 'D',
    DB_NUMBER: 'N',
    DB_ARRAY: 'A',
    DB_BYTEA: 'U',
    DB_UNKNOWN: 'X'

  });

}());
<commit_msg>issue #18575: bugfix<commit_after>/*jshint indent:2, curly:true eqeqeq:true, immed:true, latedef:true,
newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true
white:true*/
/*global XT:true, XM:true, Backbone:true, _:true, console:true, setTimeout: true, enyo:true */

(function () {
  "use strict";

  /**
  */
  _.extend(XT.Session, {
    /** @scope XT.Session */

    privileges: {},
    relevantPrivileges: [], // those privileges that are needed for an active extension
    settings: {},
    schema: {},

    SETTINGS: 0x01,
    PRIVILEGES: 0x02,
    SCHEMA: 0x04,
    LOCALE: 0x08,
    EXTENSIONS: 0x10,
    ALL: 0x01 | 0x02 | 0x04 | 0x08 | 0x10,

    /**
      Loads session objects for settings, preferences and privileges into local
      memory. Types `XT.session.SETTINGS` or `XT.session.PRIVILEGES` can be passed
      as bitwise operators. If no arguments are passed the default is
      `XT.session.ALL` which will load all session objects.

      @param {Number} Types
      @param {Object} Options
    */
    loadSessionObjects: function (types, options) {
      var that = this,
        privilegesOptions,
        privileges,
        settingsOptions,
        settings,
        schemaOptions,
        localeOptions,
        extensionOptions,
        callback,
        schemaCount = 0,
        schemasReturned = 0,
        privilegeSetCount = 0,
        privilegeSetsReturned = 0,
        i;

      if (options && options.success && options.success instanceof Function) {
        callback = options.success;
      } else { callback = XT.K; }

      if (types === undefined) { types = this.ALL; }

      if (types & this.PRIVILEGES) {
        privilegesOptions = options ? _.clone(options) : {};

        // callback
        privilegesOptions.success = function (resp) {
          var privileges, i;

          if (that.getPrivileges().attributes) {
            // add incoming data to already loaded privilege
            privileges = that.getPrivileges();

          } else {
            // create privilege as a new model
            privileges = new Backbone.Model();
            privileges.get = function (attr) {
              // Sometimes the answer is already known...
              if (_.isBoolean(attr)) { return attr; }
              return Backbone.Model.prototype.get.call(this, attr);
            };
          }

          privilegeSetsReturned++;

          // Loop through the response and set a privilege for each found.
          for (i = 0; i < resp.length; i++) {
            privileges.set(resp[i].privilege, resp[i].isGranted);
          }

          // Attach the privileges to the session object.
          that.setPrivileges(privileges);

          if (privilegeSetsReturned === privilegeSetCount) {
            callback();
          }
        };

        if (!privilegesOptions.databaseTypes) {
          // by default we just run one query against the default database type
          privilegesOptions.databaseTypes = [undefined];
        }
        for (i = 0; i < privilegesOptions.databaseTypes.length; i++) {
          privilegesOptions.databaseType = privilegesOptions.databaseTypes[i];
          XT.dataSource.dispatch('XT.Session', 'privileges', null, privilegesOptions);
          privilegeSetCount++;
        }

      }

      if (types & this.SETTINGS) {
        settingsOptions = options ? _.clone(options) : {};

        // callback
        settingsOptions.success = function (resp) {
          settings = new Backbone.Model(resp);

          // Attach the settings to the session object
          that.setSettings(settings);

          callback();
        };

        XT.dataSource.dispatch('XT.Session', 'settings', null, settingsOptions);
      }

      if (types & this.SCHEMA) {
        schemaOptions = options ? _.clone(options) : {};

        // callback
        schemaOptions.success = function (resp) {
          var schema,
            prop,
            Klass,
            relations,
            i;

          if (that.getSchema().attributes) {
            // add incoming data to already loaded schema attributes
            schema = that.getSchema();
            schema.set(resp);

          } else {
            // create schema as a new model
            schema = new Backbone.Model(resp);
            that.setSchema(schema);
          }
          schemasReturned++;

          if (schemasReturned === schemaCount) {
            // Set relations
            for (prop in schema.attributes) {
              if (schema.attributes.hasOwnProperty(prop)) {
                Klass = XM.Model.getObjectByName('XM' + '.' + prop);
                if (Klass) {
                  relations = schema.attributes[prop].relations || [];
                  if (relations.length) {
                    Klass.prototype.relations = [];
                    for (i = 0; i < relations.length; i++) {
                      if (relations[i].type === "Backbone.HasOne") {
                        relations[i].type = Backbone.HasOne;
                      } else if (relations[i].type === "Backbone.HasMany") {
                        relations[i].type = Backbone.HasMany;
                      } else {
                        continue;
                      }
                      Klass.prototype.relations.push(relations[i]);
                    }
                  }

                  privileges = schema.attributes[prop].privileges;
                  if (privileges) {
                    Klass.prototype.privileges = privileges;
                  }
                }
              }
            }
            callback();
          }
        };

        // get schema for instance DB models
        XT.dataSource.dispatch('XT.Session', 'schema', 'xm', schemaOptions);
        schemaCount++;

        // get schema for global DB models
        schemaOptions.databaseType = 'global';
        XT.dataSource.dispatch('XT.Session', 'schema', 'xm', schemaOptions);
        schemaCount++;
      }

      if (types & this.LOCALE) {
        localeOptions = options ? _.clone(options) : {};

        // callback
        localeOptions.success = function (resp) {
          var locale = new Backbone.Model(resp);
          that.setLocale(locale);
          callback();
        };

        XT.dataSource.dispatch('XT.Session', 'locale', null, localeOptions);
      }

      if (types & this.EXTENSIONS) {
        extensionOptions = options ? _.clone(options) : {};

        // callback
        extensionOptions.error = function (resp) {
          XT.log("Error loading extensions");
        };
        extensionOptions.success = function (resp) {
          that.extensions = resp;
          callback();
        };

        XT.dataSource.getExtensionList(extensionOptions);
      }

      return true;
    },

    getLocale: function () {
      return this.locale;
    },

    getSchema: function () {
      return this.schema;
    },

    getSettings: function () {
      return this.settings;
    },

    getPrivileges: function () {
      return this.privileges;
    },

    setLocale: function (value) {
      this.locale = value;
      return this;
    },

    setSchema: function (value) {
      this.schema = value;
      return this;
    },

    setSettings: function (value) {
      this.settings = value;
      return this;
    },

    setPrivileges: function (value) {
      this.privileges = value;
      return this;
    },

    addRelevantPrivileges: function (module, privArray) {
      var privMap = _.map(privArray, function (priv) {return {module: module, privilege: priv}; });
      this.relevantPrivileges.add(privMap);
    },

    // ..........................................................
    // CLASS CONSTANTS
    //

    DB_BOOLEAN: 'B',
    DB_STRING: 'S',
    DB_COMPOUND: 'C',
    DB_DATE: 'D',
    DB_NUMBER: 'N',
    DB_ARRAY: 'A',
    DB_BYTEA: 'U',
    DB_UNKNOWN: 'X'

  });

}());
<|endoftext|>


<commit_before>$(document).ready(function(){

	function initPhenoDataTable(){
            var aDataTblCols = [0,1,2,3,4,5,6,7,8];
            var oDataTable = $.fn.initDataTable($('table#phenotypes'), {
		"aoColumns": [{ "sType": "html", "mRender":function( data, type, full ) {
      	  return (type === "filter") ? $(data).text() : data;
        }},

		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "html", "mRender":function( data, type, full ) {
		            	  return (type === "filter") ? $(data).text() : data;
		              }},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "html"},
                              { "sType": "allnumeric", "aTargets": [ 3 ] },
		              { "sType": "string", "bSortable" : false }
		              ],
                               "aaSorting": [[ 7, 'asc' ]],//sort by the p value on init
		              "bDestroy": true,
		              "bFilter":false
            });
        }

	// AJAX calls for the overview charts
	$('.oChart').each(function(i, obj) {
		$( '#spinner-overview-charts' ).show();
		var mp = $(this).attr('mp');
		var id = $(this).attr('parameter');
		var chartUrl = document.URL.split("/phenotypes/")[0];
		chartUrl += "/overviewCharts/" + mp + "?parameter_id=" + id;
		console.log("request uri = " + chartUrl);
		$.ajax({
		  url: chartUrl,
		  cache: false
		})
		.done(function( html ) {
			$( '#spinner-overview-charts' ).hide();
			$( '#single-chart-div' ).html( html );
			$( '#single-chart-div' ).attr("parameter", id);
		});
	});

	// bubble popup for brief panel documentation
	$.fn.qTip({
		'pageName': 'phenotypes',
		'tip': 'top right',
		'corner' : 'right top'
	});

	$( "#show_other_procedures" ).click(function() {
		$( "#other_procedures" ).toggle( "slow", function() {
		// Animation complete.
		 });
	});

	//function to fire off a refresh of a table and it's dropdown filters
	var selectedFilters = "";
	var dropdownsList = new Array();
	// use jquery DataTable for table searching/sorting/pagination
        initPhenoDataTable();

	//$.fn.dataTableshowAllShowLess(oDataTable, aDataTblCols, null);
	$('div#exportIconsDiv').html($.fn.loadFileExporterUI({
		label: 'Export table as:',
		textPos : "textright",
		formatSelector: {
			TSV: 'tsv_phenoAssoc',
			XLS: 'xls_phenoAssoc'
		},
		class: 'fileIcon exportButton'
	}));

	var mpId = window.location.href.split("/")[window.location.href.split("/").length-1];
	mpId = mpId.split("#")[0];
	var windowLocation = window.location;

	initFileExporter();

	function initFileExporter() {
		var conf = {
			mpId: "\"" + mpId+ "\"",
			externalDbId: 3,
			fileName: 'gene_variants_with_phen_'+mpId.replace(/:/g,'_'),
			solrCoreName: 'genotype-phenotype',
			dumpMode: 'all',
			baseUrl: windowLocation,
			page:"phenotype",
			params: ""
           };

            var exportObj = buildExportUrl(conf);                                   // Build the export url, page url, and form strings.
            $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);    // Initialize the url.
// WARNING NOTE: FILTER CHANGES DO NOT UPDATE data-exporturl; THUS, THE data-exporturl VALUE WILL BE OUT-OF-SYNC SHOULD
// THE USER CHANGE FILTERS. THIS WILL LIKELY RESULT IN A HARD-TO-FIND BUG.
// RECOMMENDATION: ANY FILTER CHANGES SHOULD TRIGGER AN UPDATE OF THE data-exporturl.

            $('button.fileIcon').click(function() {
                var exportObj = buildExportUrl(conf, $(this).text());                       // Build the export url, page url, and form strings.
                $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);        // Update the url in case the filters changed.
                _doDataExport(exportObj.url, exportObj.form);
            });
	}

        function buildExportUrl(conf, fileType) {
            if (fileType === undefined)
                fileType = '';
            var url = baseUrl + '/export';
            var sInputs = '';
            for ( var k in conf ){
                    if (k === "params"){
                            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + selectedFilters + "'>";
                    }
                    else {
                            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + "'>";
                    }
            }
            sInputs += "<input type='text' name='fileType' value='" + fileType.toLowerCase() + "'>";
            var form = $("<form action='"+ url + "' method=get>" + sInputs + "</form>");
            var exportUrl = url + '?' + $(form).serialize();

            var retVal = new Object();
            retVal.url = url;
            retVal.form = form;
            retVal.exportUrl = exportUrl;
            return retVal;
        }

	 function _doDataExport(url, form){
	    	$.ajax({
				type: 'GET',
				url: url,
				cache: false,
				data: $(form).serialize(),
				success:function(data){
					$(form).appendTo('body').submit().remove();
				},
				error:function(){
					//alert("Oops, there is error during data export..");
				}
			});
	 }
	function refreshPhenoTable(newUrl){
		//alert(newUrl);
		$.ajax({
			url: newUrl,
			cache: false
		}).done(function( html ) {
                    console.log('refreshPhenotable called');
			$("#phenotypes_wrapper").html(html);//phenotypes wrapper div has been created by the original datatable so we need to replace this div with the new table and content
			initPhenoDataTable();
		});
	}
	//http://stackoverflow.com/questions/5990386/datatables-search-box-outside-datatable
	//to move the input text or reassign the div that does it and hide the other one??
	//put filtering in another text field than the default so we can position it with the other controls like dropdown ajax filters for project etc

	//stuff for dropdown tick boxes here
	var allDropdowns = new Array();
	allDropdowns[0] = $('#resource_fullname');
	allDropdowns[1] = $('#procedure_name');
	allDropdowns[2] = $('#marker_symbol');
	allDropdowns[3] = $('#mp_term_name');
	// the phenptype dropdown should only be shown on the top level terms pages

	createDropdown(allDropdowns[3].sort(), "Phenotype: All", allDropdowns);
	createDropdown(allDropdowns[0],"Source: All", allDropdowns);
	createDropdown(allDropdowns[1], "Procedure: All", allDropdowns);
	createDropdown(allDropdowns[2].sort(), "Gene: All", allDropdowns);

	function createDropdown(multipleSel, emptyText,  allDd){
		$(multipleSel).dropdownchecklist( { firstItemChecksAll: false, emptyText: emptyText, icon: {},
			minWidth: 150, onItemClick: function(checkbox, selector){
				var justChecked = checkbox.prop("checked");
//				console.log("justChecked="+justChecked);
//				console.log("checked="+ checkbox.val());
				var values = [];

				for(var  i=0; i < selector.options.length; i++ ) {
					if (selector.options[i].selected && (selector.options[i].value != "")) {
						values .push(selector.options[i].value);
					}
				}

				if(justChecked){
					values.push( checkbox.val());
				}else{//just unchecked value is in the array so we remove it as already ticked
					var index = $.inArray(checkbox.val(), values);
					values.splice(index, 1);
				}

				console.log("values="+values );
				// add current one and create dropdown object
				dd1 = new Object();
				dd1.name = multipleSel.attr('id');
				dd1.array = values; // selected values
				dropdownsList[0] = dd1;

				var ddI  = 1;
				for (var ii=0; ii<allDd.length; ii++) {
					if ($(allDd[ii]).attr('id') != multipleSel.attr('id')) {
//						console.log ("here " + allDd[ii].val() + " " + allDd[ii].attr('id'));
						dd = new Object();
						dd.name = allDd[ii].attr('id');
						dd.array = allDd[ii].val() || [];
						dropdownsList[ddI++] = dd;
					}
				}
//				console.log("call with " + dropdownsList.length);
				refreshGenesPhenoFrag(dropdownsList);
			}, textFormatFunction: function(options) {
				var selectedOptions = options.filter(":selected");
		        var countOfSelected = selectedOptions.size();
		        var size = options.size();
		        var text = "";
		        if (size > 1){
		        	options.each(function() {
	                    if ($(this).prop("selected")) {
	                        if ( text != "" ) { text += ", "; }
	                        /* NOTE use of .html versus .text, which can screw up ampersands for IE */
	                        var optCss = $(this).attr('style');
	                        var tempspan = $('<span/>');
	                        tempspan.html( $(this).html() );
	                        if ( optCss == null ) {
	                                text += tempspan.html();
	                        } else {
	                                tempspan.attr('style',optCss);
	                                text += $("<span/>").append(tempspan).html();
	                        }
	                    }
	                });
		        }
		        switch(countOfSelected) {
		           case 0: return emptyText;
		           case 1: return selectedOptions.text();
		           case options.size(): return emptyText;
		           default: return text;
		        }
			}
		} );
	}
	//if filter parameters are already set then we need to set them as selected in the dropdowns
	var previousParams=$("#filterParams").html();

	function refreshGenesPhenoFrag(dropdownsList) {
		var rootUrl=window.location.href;
//		console.log("genesPhenFrag method (refreshGenesPhenoFrag) called with "+dropdownsList.length);
		var newUrl=rootUrl.replace("phenotypes", "geneVariantsWithPhenotypeTable");
		var output ='?';
		selectedFilters = "";
		for (var it = 0; it < dropdownsList.length; it++){
//			console.log(dropdownsList[it].array);
			if(dropdownsList[it].array.length == 1){//if only one entry for this parameter then don't use brackets and or
				selectedFilters += '&fq=' + dropdownsList[it].name + ':"' + dropdownsList[it].array+'"';
			}
			if(dropdownsList[it].array.length > 1)	{
				selectedFilters += '&fq='+dropdownsList[it].name+':(\"' + dropdownsList[it].array.join("\"OR\"") + '\")';
			}
		}
		newUrl+=output + selectedFilters;
		refreshPhenoTable(newUrl);
        console.log('refresh genes PhenoFrag called woth new url='+newUrl);
		return false;
	}
});

function ajaxToBe(phenotype, parameter){
	$( '#spinner-overview-charts' ).show();
	var chartUrl = document.URL.split("/phenotypes/")[0];
	chartUrl += "/overviewCharts/" + phenotype + "?parameter_id=" + parameter;
	console.log("parameter id " + parameter )
	$.ajax({
	  url: chartUrl,
	  cache: false
	})
	.done(function( html ) {
		$( '#spinner-overview-charts' ).hide();
		$( '#single-chart-div' ).html( html );
		$( '#single-chart-div' ).attr("parameter", parameter);
	});

}

/* new sorting functions */
//http://datatables.net/forums/discussion/5894/datatable-sorting-scientific-notation
jQuery.fn.dataTableExt.oSort['allnumeric-asc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? -1 : ((x > y) ?  1 : 0));
        };

jQuery.fn.dataTableExt.oSort['allnumeric-desc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
        };
 <commit_msg>removed console log<commit_after>$(document).ready(function(){

	function initPhenoDataTable(){
            var aDataTblCols = [0,1,2,3,4,5,6,7,8];
            var oDataTable = $.fn.initDataTable($('table#phenotypes'), {
		"aoColumns": [{ "sType": "html", "mRender":function( data, type, full ) {
      	  return (type === "filter") ? $(data).text() : data;
        }},

		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "html", "mRender":function( data, type, full ) {
		            	  return (type === "filter") ? $(data).text() : data;
		              }},
		              { "sType": "string"},
		              { "sType": "string"},
		              { "sType": "html"},
                              { "sType": "allnumeric", "aTargets": [ 3 ] },
		              { "sType": "string", "bSortable" : false }
		              ],
                               "aaSorting": [[ 7, 'asc' ]],//sort by the p value on init
		              "bDestroy": true,
		              "bFilter":false
            });
        }

	// AJAX calls for the overview charts
	$('.oChart').each(function(i, obj) {
		$( '#spinner-overview-charts' ).show();
		var mp = $(this).attr('mp');
		var id = $(this).attr('parameter');
		var chartUrl = document.URL.split("/phenotypes/")[0];
		chartUrl += "/overviewCharts/" + mp + "?parameter_id=" + id;
		console.log("request uri = " + chartUrl);
		$.ajax({
		  url: chartUrl,
		  cache: false
		})
		.done(function( html ) {
			$( '#spinner-overview-charts' ).hide();
			$( '#single-chart-div' ).html( html );
			$( '#single-chart-div' ).attr("parameter", id);
		});
	});

	// bubble popup for brief panel documentation
	$.fn.qTip({
		'pageName': 'phenotypes',
		'tip': 'top right',
		'corner' : 'right top'
	});

	$( "#show_other_procedures" ).click(function() {
		$( "#other_procedures" ).toggle( "slow", function() {
		// Animation complete.
		 });
	});

	//function to fire off a refresh of a table and it's dropdown filters
	var selectedFilters = "";
	var dropdownsList = new Array();
	// use jquery DataTable for table searching/sorting/pagination
        initPhenoDataTable();

	//$.fn.dataTableshowAllShowLess(oDataTable, aDataTblCols, null);
	$('div#exportIconsDiv').html($.fn.loadFileExporterUI({
		label: 'Export table as:',
		textPos : "textright",
		formatSelector: {
			TSV: 'tsv_phenoAssoc',
			XLS: 'xls_phenoAssoc'
		},
		class: 'fileIcon exportButton'
	}));

	var mpId = window.location.href.split("/")[window.location.href.split("/").length-1];
	mpId = mpId.split("#")[0];
	var windowLocation = window.location;

	initFileExporter();

	function initFileExporter() {
		var conf = {
			mpId: "\"" + mpId+ "\"",
			externalDbId: 3,
			fileName: 'gene_variants_with_phen_'+mpId.replace(/:/g,'_'),
			solrCoreName: 'genotype-phenotype',
			dumpMode: 'all',
			baseUrl: windowLocation,
			page:"phenotype",
			params: ""
           };

            var exportObj = buildExportUrl(conf);                                   // Build the export url, page url, and form strings.
            $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);    // Initialize the url.
// WARNING NOTE: FILTER CHANGES DO NOT UPDATE data-exporturl; THUS, THE data-exporturl VALUE WILL BE OUT-OF-SYNC SHOULD
// THE USER CHANGE FILTERS. THIS WILL LIKELY RESULT IN A HARD-TO-FIND BUG.
// RECOMMENDATION: ANY FILTER CHANGES SHOULD TRIGGER AN UPDATE OF THE data-exporturl.

            $('button.fileIcon').click(function() {
                var exportObj = buildExportUrl(conf, $(this).text());                       // Build the export url, page url, and form strings.
                $('div#exportIconsDiv').attr("data-exporturl", exportObj.exportUrl);        // Update the url in case the filters changed.
                _doDataExport(exportObj.url, exportObj.form);
            });
	}

        function buildExportUrl(conf, fileType) {
            if (fileType === undefined)
                fileType = '';
            var url = baseUrl + '/export';
            var sInputs = '';
            for ( var k in conf ){
                    if (k === "params"){
                            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + selectedFilters + "'>";
                    }
                    else {
                            sInputs += "<input type='text' name='" + k + "' value='" + conf[k] + "'>";
                    }
            }
            sInputs += "<input type='text' name='fileType' value='" + fileType.toLowerCase() + "'>";
            var form = $("<form action='"+ url + "' method=get>" + sInputs + "</form>");
            var exportUrl = url + '?' + $(form).serialize();

            var retVal = new Object();
            retVal.url = url;
            retVal.form = form;
            retVal.exportUrl = exportUrl;
            return retVal;
        }

	 function _doDataExport(url, form){
	    	$.ajax({
				type: 'GET',
				url: url,
				cache: false,
				data: $(form).serialize(),
				success:function(data){
					$(form).appendTo('body').submit().remove();
				},
				error:function(){
					//alert("Oops, there is error during data export..");
				}
			});
	 }
	function refreshPhenoTable(newUrl){
		//alert(newUrl);
		$.ajax({
			url: newUrl,
			cache: false
		}).done(function( html ) {
                    console.log('refreshPhenotable called');
			$("#phenotypes_wrapper").html(html);//phenotypes wrapper div has been created by the original datatable so we need to replace this div with the new table and content
			initPhenoDataTable();
		});
	}
	//http://stackoverflow.com/questions/5990386/datatables-search-box-outside-datatable
	//to move the input text or reassign the div that does it and hide the other one??
	//put filtering in another text field than the default so we can position it with the other controls like dropdown ajax filters for project etc

	//stuff for dropdown tick boxes here
	var allDropdowns = new Array();
	allDropdowns[0] = $('#resource_fullname');
	allDropdowns[1] = $('#procedure_name');
	allDropdowns[2] = $('#marker_symbol');
	allDropdowns[3] = $('#mp_term_name');
	// the phenptype dropdown should only be shown on the top level terms pages

	createDropdown(allDropdowns[3].sort(), "Phenotype: All", allDropdowns);
	createDropdown(allDropdowns[0],"Source: All", allDropdowns);
	createDropdown(allDropdowns[1], "Procedure: All", allDropdowns);
	createDropdown(allDropdowns[2].sort(), "Gene: All", allDropdowns);

	function createDropdown(multipleSel, emptyText,  allDd){
		$(multipleSel).dropdownchecklist( { firstItemChecksAll: false, emptyText: emptyText, icon: {},
			minWidth: 150, onItemClick: function(checkbox, selector){
				var justChecked = checkbox.prop("checked");
//				console.log("justChecked="+justChecked);
//				console.log("checked="+ checkbox.val());
				var values = [];

				for(var  i=0; i < selector.options.length; i++ ) {
					if (selector.options[i].selected && (selector.options[i].value != "")) {
						values .push(selector.options[i].value);
					}
				}

				if(justChecked){
					values.push( checkbox.val());
				}else{//just unchecked value is in the array so we remove it as already ticked
					var index = $.inArray(checkbox.val(), values);
					values.splice(index, 1);
				}

				console.log("values="+values );
				// add current one and create dropdown object
				dd1 = new Object();
				dd1.name = multipleSel.attr('id');
				dd1.array = values; // selected values
				dropdownsList[0] = dd1;

				var ddI  = 1;
				for (var ii=0; ii<allDd.length; ii++) {
					if ($(allDd[ii]).attr('id') != multipleSel.attr('id')) {
//						console.log ("here " + allDd[ii].val() + " " + allDd[ii].attr('id'));
						dd = new Object();
						dd.name = allDd[ii].attr('id');
						dd.array = allDd[ii].val() || [];
						dropdownsList[ddI++] = dd;
					}
				}
//				console.log("call with " + dropdownsList.length);
				refreshGenesPhenoFrag(dropdownsList);
			}, textFormatFunction: function(options) {
				var selectedOptions = options.filter(":selected");
		        var countOfSelected = selectedOptions.size();
		        var size = options.size();
		        var text = "";
		        if (size > 1){
		        	options.each(function() {
	                    if ($(this).prop("selected")) {
	                        if ( text != "" ) { text += ", "; }
	                        /* NOTE use of .html versus .text, which can screw up ampersands for IE */
	                        var optCss = $(this).attr('style');
	                        var tempspan = $('<span/>');
	                        tempspan.html( $(this).html() );
	                        if ( optCss == null ) {
	                                text += tempspan.html();
	                        } else {
	                                tempspan.attr('style',optCss);
	                                text += $("<span/>").append(tempspan).html();
	                        }
	                    }
	                });
		        }
		        switch(countOfSelected) {
		           case 0: return emptyText;
		           case 1: return selectedOptions.text();
		           case options.size(): return emptyText;
		           default: return text;
		        }
			}
		} );
	}
	//if filter parameters are already set then we need to set them as selected in the dropdowns
	var previousParams=$("#filterParams").html();

	function refreshGenesPhenoFrag(dropdownsList) {
		var rootUrl=window.location.href;
//		console.log("genesPhenFrag method (refreshGenesPhenoFrag) called with "+dropdownsList.length);
		var newUrl=rootUrl.replace("phenotypes", "geneVariantsWithPhenotypeTable");
		var output ='?';
		selectedFilters = "";
		for (var it = 0; it < dropdownsList.length; it++){
//			console.log(dropdownsList[it].array);
			if(dropdownsList[it].array.length == 1){//if only one entry for this parameter then don't use brackets and or
				selectedFilters += '&fq=' + dropdownsList[it].name + ':"' + dropdownsList[it].array+'"';
			}
			if(dropdownsList[it].array.length > 1)	{
				selectedFilters += '&fq='+dropdownsList[it].name+':(\"' + dropdownsList[it].array.join("\"OR\"") + '\")';
			}
		}
		newUrl+=output + selectedFilters;
		refreshPhenoTable(newUrl);
        console.log('refresh genes PhenoFrag called woth new url='+newUrl);
		return false;
	}
});

function ajaxToBe(phenotype, parameter){
	$( '#spinner-overview-charts' ).show();
	var chartUrl = document.URL.split("/phenotypes/")[0];
	chartUrl += "/overviewCharts/" + phenotype + "?parameter_id=" + parameter;
	$.ajax({
	  url: chartUrl,
	  cache: false
	})
	.done(function( html ) {
		$( '#spinner-overview-charts' ).hide();
		$( '#single-chart-div' ).html( html );
		$( '#single-chart-div' ).attr("parameter", parameter);
	});

}

/* new sorting functions */
//http://datatables.net/forums/discussion/5894/datatable-sorting-scientific-notation
jQuery.fn.dataTableExt.oSort['allnumeric-asc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? -1 : ((x > y) ?  1 : 0));
        };

jQuery.fn.dataTableExt.oSort['allnumeric-desc']  = function(a,b) {
          var x = parseFloat(a);
          var y = parseFloat(b);
          return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
        };
 <|endoftext|>


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

  function Even(config) {
    this.config = config;
  }

  Even.prototype.setup = function() {
    var leancloud = this.config.leancloud;

    this.navbar();
    this.responsiveTable();

    if (this.config.toc) {
      this.scrollToc();
      this.tocFollow();
    }
    if (this.config.fancybox) {
      this.fancybox();
    }
    if (leancloud.app_id && leancloud.app_key) {
      this.recordReadings();
    }
    if (this.config.pjax) {
      this.pjax();
    }
    if(this.config.latex) {
      this.renderLaTeX();
    }
    this.backToTop();
  };

  Even.prototype.navbar = function () {
    var $nav = $('#mobile-navbar');
    var $navIcon = $('.mobile-navbar-icon');

    var slideout = new Slideout({
      'panel': document.getElementById('mobile-panel'),
      'menu': document.getElementById('mobile-menu'),
      'padding': 180,
      'tolerance': 70
    });
    slideout.disableTouch();

    $navIcon.click(function () {
      slideout.toggle();
    });

    slideout.on('beforeopen', function () {
      $nav.addClass('fixed-open');
      $navIcon.addClass('icon-click').removeClass('icon-out');
    });

    slideout.on('beforeclose', function () {
      $nav.removeClass('fixed-open');
      $navIcon.addClass('icon-out').removeClass('icon-click');
    });

    $('#mobile-panel').on('touchend', function () {
      slideout.isOpen() && $navIcon.click();
    });
  };

  Even.prototype.responsiveTable = function () {
    var tables = $('.post-content > table')
    tables.wrap('
')
  };

  Even.prototype.scrollToc = function () {
    var SPACING = 20;
    var $toc = $('.post-toc');
    var $footer = $('.post-footer');

    if ($toc.length) {
      var minScrollTop = $toc.offset().top - SPACING;
      var maxScrollTop = $footer.offset().top - $toc.height() - SPACING;

      var tocState = {
        start: {
          'position': 'absolute',
          'top': minScrollTop
        },
        process: {
          'position': 'fixed',
          'top': SPACING
        },
        end: {
          'position': 'absolute',
          'top': maxScrollTop
        }
      }

      $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();

        if (scrollTop < minScrollTop) {
          $toc.css(tocState.start);
        } else if (scrollTop > maxScrollTop) {
          $toc.css(tocState.end);
        } else {
          $toc.css(tocState.process);
        }
      })
    }
  };

  Even.prototype.tocFollow = function () {
    var HEADERFIX = 30;
    var $toclink = $('.toc-link'),
      $headerlink = $('.headerlink');

    var headerlinkTop = $.map($headerlink, function (link) {
      return $(link).offset().top;
    });

    $(window).scroll(function () {
      var scrollTop = $(window).scrollTop();

      for (var i = 0; i < $toclink.length; i++) {
        var isLastOne = i + 1 === $toclink.length,
          currentTop = headerlinkTop[i] - HEADERFIX,
          nextTop = isLastOne ? Infinity : headerlinkTop[i + 1] - HEADERFIX;

        if (currentTop < scrollTop && scrollTop <= nextTop) {
          $($toclink[i]).addClass('active');
        } else {
          $($toclink[i]).removeClass('active');
        }
      }
    });
  };

  Even.prototype.fancybox = function () {
    if ($.fancybox) {
      $('.post').each(function () {
        $(this).find('img').each(function () {
          var href = 'href="' + this.src + '"';
          var title = 'title="' + this.alt + '"';
          $(this).wrap('');
        });
      });

      $('.fancybox').fancybox({
        openEffect: 'elastic',
        closeEffect: 'elastic'
      });
    }
  };

  Even.prototype.recordReadings = function () {
    if (typeof AV !== 'object') return;

    var $visits = $('.post-visits');
    var Counter = AV.Object.extend('Counter');
    if ($visits.length === 1) {
      addCounter(Counter);
    } else {
      showTime(Counter);
    }

    function updateVisits(dom, time) {
      var readText = dom.text().replace(/(\d+)/i, time)
      dom.text(readText);
    }

    function addCounter(Counter) {
      var query = new AV.Query(Counter);

      var url = $visits.data('url').trim();
      var title = $visits.data('title').trim();

      query.equalTo('url', url);
      query.find().then(function (results) {
        if (results.length > 0) {
          var counter = results[0];
          counter.save(null, {
            fetchWhenSave: true
          }).then(function (counter) {
            counter.increment('time', 1);
            return counter.save();
          }).then(function (counter) {
            updateVisits($visits, counter.get('time'));
          });
        } else {
          var newcounter = new Counter();
          newcounter.set('title', title);
          newcounter.set('url', url);
          newcounter.set('time', 1);

          var acl = new AV.ACL();
          acl.setWriteAccess('*', true)
          acl.setReadAccess('*', true)
          newcounter.setACL(acl)

          newcounter.save().then(function () {
            updateVisits($visits, newcounter.get('time'));
          });
        }
      }, function (error) {
        // eslint-disable-next-line
        console.log('Error:' + error.code + " " + error.message);
      });
    }

    function showTime(Counter) {
      $visits.each(function () {
        var $this = $(this);
        var query = new AV.Query(Counter);
        var url = $this.data('url').trim();

        query.equalTo('url', url);
        query.find().then(function (results) {
          if (results.length === 0) {
            updateVisits($this, 0);
          } else {
            var counter = results[0];
            updateVisits($this, counter.get('time'));
          }
        }, function (error) {
          // eslint-disable-next-line
          console.log('Error:' + error.code + " " + error.message);
        });
      })
    }
  };

  Even.prototype.pjax = function () {
    if (location.hostname === 'localhost' || this.hasPjax) return;
    this.hasPjax = true;
    this._fancybox = $.fancybox;
    this._fancyboxProto = $.prototype.fancybox;

    var that = this;
    $(document).pjax('a', 'body', { fragment: 'body' });
    $(document).on('pjax:send', function () {
      NProgress.start();
      $('body').addClass('hide-top');
    });
    $(document).on('pjax:complete', function () {
      NProgress.done();
      $('body').removeClass('hide-top');
      $.fancybox = that._fancybox;
      $.prototype.fancybox = that._fancyboxProto;
      that.setup();
    });
  };

  Even.prototype.backToTop = function () {
    var $backToTop = $('#back-to-top');

    $(window).scroll(function () {
      if ($(window).scrollTop() > 100) {
        $backToTop.fadeIn(1000);
      } else {
        $backToTop.fadeOut(1000);
      }
    });

    $backToTop.click(function () {
      $('body,html').animate({ scrollTop: 0 });
    });
  };

  Even.prototype.renderLaTeX = function () {
    var loopID = setInterval(function () {
      if(window.MathJax) {
        var jax = window.MathJax;
        jax.Hub.Config({ tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] }});
        jax.Hub.Queue(["Typeset", jax.Hub, $(document.body)[0]]);
        clearInterval(loopID);
      }
    }, 500);
  }

  var config = window.config;
  var even = new Even(config);
  even.setup();
}(window))
<commit_msg>fix: code style<commit_after>(function (window) {
  'use strict';

  function Even(config) {
    this.config = config;
  }

  Even.prototype.setup = function() {
    var leancloud = this.config.leancloud;

    this.navbar();
    this.responsiveTable();

    if (this.config.toc) {
      this.scrollToc();
      this.tocFollow();
    }
    if (this.config.fancybox) {
      this.fancybox();
    }
    if (leancloud.app_id && leancloud.app_key) {
      this.recordReadings();
    }
    if (this.config.pjax) {
      this.pjax();
    }
    if(this.config.latex) {
      this.renderLaTeX();
    }
    this.backToTop();
  };

  Even.prototype.navbar = function () {
    var $nav = $('#mobile-navbar');
    var $navIcon = $('.mobile-navbar-icon');

    var slideout = new Slideout({
      'panel': document.getElementById('mobile-panel'),
      'menu': document.getElementById('mobile-menu'),
      'padding': 180,
      'tolerance': 70
    });
    slideout.disableTouch();

    $navIcon.click(function () {
      slideout.toggle();
    });

    slideout.on('beforeopen', function () {
      $nav.addClass('fixed-open');
      $navIcon.addClass('icon-click').removeClass('icon-out');
    });

    slideout.on('beforeclose', function () {
      $nav.removeClass('fixed-open');
      $navIcon.addClass('icon-out').removeClass('icon-click');
    });

    $('#mobile-panel').on('touchend', function () {
      slideout.isOpen() && $navIcon.click();
    });
  };

  Even.prototype.responsiveTable = function () {
    var tables = $('.post-content > table')
    tables.wrap('
')
  };

  Even.prototype.scrollToc = function () {
    var SPACING = 20;
    var $toc = $('.post-toc');
    var $footer = $('.post-footer');

    if ($toc.length) {
      var minScrollTop = $toc.offset().top - SPACING;
      var maxScrollTop = $footer.offset().top - $toc.height() - SPACING;

      var tocState = {
        start: {
          'position': 'absolute',
          'top': minScrollTop
        },
        process: {
          'position': 'fixed',
          'top': SPACING
        },
        end: {
          'position': 'absolute',
          'top': maxScrollTop
        }
      }

      $(window).scroll(function () {
        var scrollTop = $(window).scrollTop();

        if (scrollTop < minScrollTop) {
          $toc.css(tocState.start);
        } else if (scrollTop > maxScrollTop) {
          $toc.css(tocState.end);
        } else {
          $toc.css(tocState.process);
        }
      })
    }
  };

  Even.prototype.tocFollow = function () {
    var HEADERFIX = 30;
    var $toclink = $('.toc-link'),
      $headerlink = $('.headerlink');

    var headerlinkTop = $.map($headerlink, function (link) {
      return $(link).offset().top;
    });

    $(window).scroll(function () {
      var scrollTop = $(window).scrollTop();

      for (var i = 0; i < $toclink.length; i++) {
        var isLastOne = i + 1 === $toclink.length,
          currentTop = headerlinkTop[i] - HEADERFIX,
          nextTop = isLastOne ? Infinity : headerlinkTop[i + 1] - HEADERFIX;

        if (currentTop < scrollTop && scrollTop <= nextTop) {
          $($toclink[i]).addClass('active');
        } else {
          $($toclink[i]).removeClass('active');
        }
      }
    });
  };

  Even.prototype.fancybox = function () {
    if ($.fancybox) {
      $('.post').each(function () {
        $(this).find('img').each(function () {
          var href = 'href="' + this.src + '"';
          var title = 'title="' + this.alt + '"';
          $(this).wrap('');
        });
      });

      $('.fancybox').fancybox({
        openEffect: 'elastic',
        closeEffect: 'elastic'
      });
    }
  };

  Even.prototype.recordReadings = function () {
    if (typeof AV !== 'object') return;

    var $visits = $('.post-visits');
    var Counter = AV.Object.extend('Counter');
    if ($visits.length === 1) {
      addCounter(Counter);
    } else {
      showTime(Counter);
    }

    function updateVisits(dom, time) {
      var readText = dom.text().replace(/(\d+)/i, time)
      dom.text(readText);
    }

    function addCounter(Counter) {
      var query = new AV.Query(Counter);

      var url = $visits.data('url').trim();
      var title = $visits.data('title').trim();

      query.equalTo('url', url);
      query.find().then(function (results) {
        if (results.length > 0) {
          var counter = results[0];
          counter.save(null, {
            fetchWhenSave: true
          }).then(function (counter) {
            counter.increment('time', 1);
            return counter.save();
          }).then(function (counter) {
            updateVisits($visits, counter.get('time'));
          });
        } else {
          var newcounter = new Counter();
          newcounter.set('title', title);
          newcounter.set('url', url);
          newcounter.set('time', 1);

          var acl = new AV.ACL();
          acl.setWriteAccess('*', true)
          acl.setReadAccess('*', true)
          newcounter.setACL(acl)

          newcounter.save().then(function () {
            updateVisits($visits, newcounter.get('time'));
          });
        }
      }, function (error) {
        // eslint-disable-next-line
        console.log('Error:' + error.code + ' ' + error.message);
      });
    }

    function showTime(Counter) {
      $visits.each(function () {
        var $this = $(this);
        var query = new AV.Query(Counter);
        var url = $this.data('url').trim();

        query.equalTo('url', url);
        query.find().then(function (results) {
          if (results.length === 0) {
            updateVisits($this, 0);
          } else {
            var counter = results[0];
            updateVisits($this, counter.get('time'));
          }
        }, function (error) {
          // eslint-disable-next-line
          console.log('Error:' + error.code + ' ' + error.message);
        });
      })
    }
  };

  Even.prototype.pjax = function () {
    if (location.hostname === 'localhost' || this.hasPjax) return;
    this.hasPjax = true;
    this._fancybox = $.fancybox;
    this._fancyboxProto = $.prototype.fancybox;

    var that = this;
    $(document).pjax('a', 'body', { fragment: 'body' });
    $(document).on('pjax:send', function () {
      NProgress.start();
      $('body').addClass('hide-top');
    });
    $(document).on('pjax:complete', function () {
      NProgress.done();
      $('body').removeClass('hide-top');
      $.fancybox = that._fancybox;
      $.prototype.fancybox = that._fancyboxProto;
      that.setup();
    });
  };

  Even.prototype.backToTop = function () {
    var $backToTop = $('#back-to-top');

    $(window).scroll(function () {
      if ($(window).scrollTop() > 100) {
        $backToTop.fadeIn(1000);
      } else {
        $backToTop.fadeOut(1000);
      }
    });

    $backToTop.click(function () {
      $('body,html').animate({ scrollTop: 0 });
    });
  };

  Even.prototype.renderLaTeX = function () {
    var loopID = setInterval(function () {
      if(window.MathJax) {
        var jax = window.MathJax;
        jax.Hub.Config({ tex2jax: { inlineMath: [['$', '$'], ['\\(', '\\)']] }});
        jax.Hub.Queue(['Typeset', jax.Hub, $(document.body)[0]]);
        clearInterval(loopID);
      }
    }, 500);
  }

  var config = window.config;
  var even = new Even(config);
  even.setup();
}(window))
<|endoftext|>


<commit_before>// data.json:
// [
//     {name:, x1:, x2: },
//     ...
// ]

var default_filename = 0,
x_axis_label = 'x',
y_axis_label = 'frequency';

// setup dropdown menu
$.ajax({
    dataType: "json",
    url: 'http://zak.ucsd.edu/git/histogram/getdatafiles',
    success:function(json){
        $('#dropdown-menu').change( function() {
            console.log('value: ' + $(this).val());
            load_datafile($(this).val());
        });
        update_dropdown(json.data)
        d3.json(json.data[default_filename], function(error, data) {
            if (error) return console.warn(error);
            setup_plot(data);
        });
    },
    error:function(error) { console.log(error); }
});

// functions
function load_datafile(this_file) {
    d3.json(this_file, function(error, data) {
        if (error) {
            return console.warn(error);
            $('body').append('error loading');
        } else {
            $('svg').remove();
            setup_plot(data);
        }
    });
}

function update_dropdown(list) {
    var menu = $('#dropdown-menu');
    menu.empty();
    for (var i=0; i<list.length; i++) {
        menu.append("<option value="+list[i]+">"+list[i]+"</option>");
    }
    menu.focus();
}

function setup_plot(f) {
    this_d = f

    var margin = {top: 30, right: 20, bottom: 30, left: 40},
    width = $(window).width() - 20 - margin.left - margin.right,
    height = $(window).height() - 20 - margin.top - margin.bottom;

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // var
    x_dom = [d3.min([d3.min(f, function (d) { return d.x1; }), d3.min(f, function (d) { return d.x2; })]),
                 d3.max([d3.max(f, function (d) { return d.x1; }), d3.max(f, function (d) { return d.x2; })]) ];

    // var
    x = d3.scale.linear()
        .range([0, width])
        .domain(x_dom);

    x_size_scale = d3.scale.linear()
        .range([0, width])
	.domain([0, x_dom[1] - x_dom[0]]);

    // Generate a histogram using twenty uniformly-spaced bins.

    // var
    data1 = d3.layout.histogram()
        .value(function (d) { return d.x1; })
        .bins(x.ticks(20))
    (f);
    var data2 = d3.layout.histogram()
        .value(function (d) { return d.x2; })
        .bins(x.ticks(20))
    (f);

    // var
    y = d3.scale.linear()
        .domain([0, d3.max([data1, data2],
                           function (a) {
                               return d3.max(a, function(d) { return d.y; });
                           })
                ])
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
	.ticks(20);

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(20);

    var diff = 10;
    var bar_w = x_size_scale(data1[0].dx) - diff - 8;

    var bar1 = svg.selectAll(".bar1")
        .data(data1)
        .enter().append("g")
        .attr("class", "bar1")
        .attr("transform", function(d) { return "translate(" + (x(d.x)+4) + "," + y(d.y) + ")"; });

    bar1.append("rect")
        .attr("x", 1)
        .attr("width", bar_w)
        .attr("height", function(d) { return height - y(d.y); });

    var bar2 = svg.selectAll(".bar2")
        .data(data2)
        .enter().append("g")
        .attr("class", "bar2")
        .attr("transform", function(d) { return "translate(" + (x(d.x)+diff+4) + "," + y(d.y) + ")"; });

    bar2.append("rect")
        .attr("x", 1)
        .attr("width", bar_w)
        .attr("height", function(d) { return height - y(d.y); });

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .append("text")
        .attr("class", "label")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text(x_axis_label);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("class", "label")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text(y_axis_label)

    var g = svg.append("g")
	.attr("class", "legend")
	.attr("transform", "translate(" + width/10 + ", 80)")
	.attr("width", "300px")
	.attr("height", "200px");

    add_legend(g, '10x', 0, 'bar1');
    add_legend(g, '100x', 1, 'bar2');
    function add_legend(a, t, i, cl) {
	var g = a.append("g")
	    .attr("transform", "translate(0,"+i*40+")");
	g.append("text")
	    .text(t)
	    .attr("transform", "translate(30, 14)");
	g.append("rect")
	    .attr("width", 15)
	    .attr("height", 15)
	    .attr("class", cl);
    }

}
<commit_msg>Using new data format with options entry<commit_after>// data.json:
//
// {data: [
//      {name:, x1:, x2: },
//      ...
//  ],
//  options: {
//      x_axis_label: ,
//      y_axis_label: ,
//      x_data_label: ,
//      y_data_label: ,
//  }
// }

var default_filename = 0,
def_x_axis_label = 'x',
def_y_axis_label = 'count',
def_x_data_label = '1',
def_y_data_label = '2';

// setup dropdown menu
$.ajax({
    dataType: "json",
    url: 'http://zak.ucsd.edu/git/visbio/vis/histogram/getdatafiles',
    success:function(json){
        $('#dropdown-menu').change( function() {
            console.log('value: ' + $(this).val());
            load_datafile($(this).val());
        });
        update_dropdown(json.data)
        d3.json(json.data[default_filename], function(error, data) {
            if (error) return console.warn(error);
            setup_plot(data);
        });
    },
    error:function(error) { console.log(error); }
});

// functions
function load_datafile(this_file) {
    d3.json(this_file, function(error, data) {
        if (error) {
            return console.warn(error);
            $('body').append('error loading');
        } else {
            $('svg').remove();
            setup_plot(data);
        }
    });
}

function update_dropdown(list) {
    var menu = $('#dropdown-menu');
    menu.empty();
    for (var i=0; i<list.length; i++) {
        menu.append("<option value="+list[i]+">"+list[i]+"</option>");
    }
    menu.focus();
}

function setup_plot(json) {
    f = json.data;
    o = json.options;
    x_axis_label = o.hasOwnProperty('x_axis_label') ? o.x_axis_label : def_x_axis_label;
    y_axis_label = o.hasOwnProperty('y_axis_label') ? o.y_axis_label : def_y_axis_label;
    x_data_label = o.hasOwnProperty('x_data_label') ? o.x_data_label : def_x_data_label;
    y_data_label = o.hasOwnProperty('y_data_label') ? o.y_data_label : def_y_data_label;

    var margin = {top: 30, right: 20, bottom: 30, left: 40},
    width = $(window).width() - 20 - margin.left - margin.right,
    height = $(window).height() - 20 - margin.top - margin.bottom;

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // var
    x_dom = [d3.min([d3.min(f, function (d) { return d.x1; }), d3.min(f, function (d) { return d.x2; })]),
                 d3.max([d3.max(f, function (d) { return d.x1; }), d3.max(f, function (d) { return d.x2; })]) ];

    // var
    x = d3.scale.linear()
        .range([0, width])
        .domain(x_dom);

    x_size_scale = d3.scale.linear()
        .range([0, width])
	.domain([0, x_dom[1] - x_dom[0]]);

    // Generate a histogram using twenty uniformly-spaced bins.

    // var
    data1 = d3.layout.histogram()
        .value(function (d) { return d.x1; })
        .bins(x.ticks(20))
    (f);
    var data2 = d3.layout.histogram()
        .value(function (d) { return d.x2; })
        .bins(x.ticks(20))
    (f);

    // var
    y = d3.scale.linear()
        .domain([0, d3.max([data1, data2],
                           function (a) {
                               return d3.max(a, function(d) { return d.y; });
                           })
                ])
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
	.ticks(20);

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(20);

    var diff = 10;
    var bar_w = x_size_scale(data1[0].dx) - diff - 8;

    var bar1 = svg.selectAll(".bar1")
        .data(data1)
        .enter().append("g")
        .attr("class", "bar1")
        .attr("transform", function(d) { return "translate(" + (x(d.x)+4) + "," + y(d.y) + ")"; });

    bar1.append("rect")
        .attr("x", 1)
        .attr("width", bar_w)
        .attr("height", function(d) { return height - y(d.y); });

    var bar2 = svg.selectAll(".bar2")
        .data(data2)
        .enter().append("g")
        .attr("class", "bar2")
        .attr("transform", function(d) { return "translate(" + (x(d.x)+diff+4) + "," + y(d.y) + ")"; });

    bar2.append("rect")
        .attr("x", 1)
        .attr("width", bar_w)
        .attr("height", function(d) { return height - y(d.y); });

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .append("text")
        .attr("class", "label")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text(x_axis_label);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("class", "label")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text(y_axis_label)

    var g = svg.append("g")
	.attr("class", "legend")
	.attr("transform", "translate(" + width/10 + ", 80)")
	.attr("width", "300px")
	.attr("height", "200px");

    add_legend(g, x_data_label, 0, 'bar1');
    add_legend(g, y_data_label, 1, 'bar2');
    function add_legend(a, t, i, cl) {
	var g = a.append("g")
	    .attr("transform", "translate(0,"+i*40+")");
	g.append("text")
	    .text(t)
	    .attr("transform", "translate(30, 14)");
	g.append("rect")
	    .attr("width", 15)
	    .attr("height", 15)
	    .attr("class", cl);
    }

}
<|endoftext|>


<commit_before>
var START = 1;
var PENDING = 2;
var DONE = 4;

/*-----------------------------------------------------------------------*/
function process_ajax_queue() {

   if (window.ajax_queue.length == 0)
     return;

   if (window.ajax_queue[0].state == PENDING)
     return;

   if (window.ajax_queue[0].state == DONE) {
     window.ajax_queue.splice(0,1);
     return;
   }

   if (window.ajax_queue[0].state == START)
     start_next(window.ajax_queue[0]);

}
/*-----------------------------------------------------------------------*/
function start_next(ticket) {

  ticket.state = PENDING;

  ticket.xmlhttp = get_xmlhttp();

  // Run ticket.done when request is complete.
  ticket.xmlhttp.onreadystatechange = function() {

    console.log(ticket.xmlhttp);
    console.log(['ReadyState', ticket.xmlhttp.readyState]);
    console.log(['status', ticket.xmlhttp.status]);

    if (ticket.xmlhttp.readyState==4 && ticket.xmlhttp.status==200) {
      // Run done function.
      ticket.done(jQuery.parseJSON(ticket.xmlhttp.responseText));
      ticket.state = DONE;
    }
  };

  // Timeout
  ticket.xmlhttp.timeout = 9000;
  ticket.xmlhttp.ontimeout = function() {
    ticket.state = START;
    console.log("Request timed out");
  };

  // If there's an error reset to START
  ticket.xmlhttp.onerror = function() {
    ticket.state = START;
  };

  // Send request
  post_async(ticket.xmlhttp, ticket.url, ticket.get_params());

}
/*-----------------------------------------------------------------------*/
// Returns an empty ticket. Tickets go on to the queue.
// See send_echo_request() to see how this is done.

function new_ticket() {
  return {state: START, url: '', get_params: null, done: null};
}

/*-----------------------------------------------------------------------*/

function send_echo_request(sentence) {

  var ticket = new_ticket();

  ticket.url = "/competition/echo";

  ticket.get_params = function () {return {"sentence": sentence};};

  ticket.done = function(response_json) {console.log(response_json);};

  window.ajax_queue.push(ticket);
}
/*-----------------------------------------------------------------------*/
<commit_msg>reseting state to START if nothing happens<commit_after>
var START = 1;
var PENDING = 2;
var DONE = 4;

/*-----------------------------------------------------------------------*/
function process_ajax_queue() {

   if (window.ajax_queue.length == 0)
     return;

   if (window.ajax_queue[0].state == PENDING) {
     window.ajax_queue[0].clicks++;

     // Experimental
     if (window.ajax_queue[0].clicks == 9000)
       window.ajax_queue[0].state = START;

     return;
   }

   if (window.ajax_queue[0].state == DONE) {
     window.ajax_queue.splice(0,1);
     return;
   }

   if (window.ajax_queue[0].state == START)
     start_next(window.ajax_queue[0]);

}
/*-----------------------------------------------------------------------*/
function start_next(ticket) {

  ticket.state = PENDING;
  ticket.clicks = 0;

  ticket.xmlhttp = get_xmlhttp();

  // Run ticket.done when request is complete.
  ticket.xmlhttp.onreadystatechange = function() {

    console.log(ticket.xmlhttp);
    console.log(['ReadyState', ticket.xmlhttp.readyState]);
    console.log(['status', ticket.xmlhttp.status]);

    if (ticket.xmlhttp.readyState==4 && ticket.xmlhttp.status==200) {
      // Run done function.
      ticket.done(jQuery.parseJSON(ticket.xmlhttp.responseText));
      ticket.state = DONE;
    }
  };

  // Timeout
  ticket.xmlhttp.timeout = 9000;
  ticket.xmlhttp.ontimeout = function() {
    ticket.state = START;
    console.log("Request timed out");
  };

  // If there's an error reset to START
  ticket.xmlhttp.onerror = function() {
    ticket.state = START;
  };

  // Send request
  post_async(ticket.xmlhttp, ticket.url, ticket.get_params());

}
/*-----------------------------------------------------------------------*/
// Returns an empty ticket. Tickets go on to the queue.
// See send_echo_request() to see how this is done.

function new_ticket() {
  return {state: START, url: '', get_params: null, done: null};
}

/*-----------------------------------------------------------------------*/

function send_echo_request(sentence) {

  var ticket = new_ticket();

  ticket.url = "/competition/echo";

  ticket.get_params = function () {return {"sentence": sentence};};

  ticket.done = function(response_json) {console.log(response_json);};

  window.ajax_queue.push(ticket);
}
/*-----------------------------------------------------------------------*/
<|endoftext|>


<commit_before>(function () {
    'use strict';
    describe('Testing game cell directive', function() {
        var compile,
            rootScope,
            element,
            directiveElement,
            insideElement;

        beforeEach(function () {
            module('Tombola.NoughtAndCrosses.gameboard');

            inject(function ($compile, $rootScope) {
                compile = $compile;
                rootScope = $rootScope;
            });

            directiveElement = '<game-cell square-number="4"></game-cell>';
            element = compile(directiveElement)(rootScope);
            rootScope.$digest();
            insideElement = element.find('div');
        });

        it('Ensures game-cell directives works', function () {
            element[0].toString().should.be.equal('[object HTMLElement]');
            element[0].children.length.should.be.equal(1);
        });

        it('Ensures game-cell directives has the correct class', function () {
            insideElement.attr('class').should.be.equal('gameCells player');
        });

        it('Ensures game-cell directives has the correct square number attribute', function () {
            element.attr('square-number').should.be.equal('4');
        });

        it('Ensures game-cell directives has the correct ng-click function', function () {
            insideElement.attr('ng-click').should.be.equal('game.gameboardTapped(4)');
        });
    });
})();<commit_msg>added local mock to test ng-click function, will add into mock file later on<commit_after>(function () {
    'use strict';
    describe('Testing game cell directive', function() {
        var compile,
            rootScope,
            element,
            directiveElement,
            insideElement,
            spyTappedFunction,
            sandbox,
            mock;

        beforeEach(function () {
            module('Tombola.NoughtAndCrosses.gameboard');

            inject(function ($compile, $rootScope) {
                compile = $compile;
                rootScope = $rootScope;
            });

            mock = {
                game : {
                    gameboardTapped : function (number) {}
                }
            };

            directiveElement = '<game-cell square-number="4"></game-cell>';
            element = compile(directiveElement)(rootScope);
            rootScope.$digest();
            insideElement = element.find('div');
            sandbox = sinon.sandbox.create();
            spyTappedFunction = sinon.sandbox.spy(mock.game, 'gameboardTapped');
        });

        it('Ensures game-cell directives works', function () {
            element[0].toString().should.be.equal('[object HTMLElement]');
            element[0].children.length.should.be.equal(1);
        });

        it('Ensures game-cell directives has the correct class', function () {
            insideElement.attr('class').should.be.equal('gameCells player');
        });

        it('Ensures game-cell directives has the correct square number attribute', function () {
            element.attr('square-number').should.be.equal('4');
        });

        it('Ensures game-cell directives has the correct ng-click function', function () {
            insideElement.attr('ng-click').should.be.equal('game.gameboardTapped(4)');
        });

        it('Ensures game-cell directives fires the gameboardTapped function once', function () {
            rootScope.game = mock.game;
            insideElement.triggerHandler('click');
            spyTappedFunction.should.have.been.calledOnce.calledWithExactly(4);
        });
    });
})();<|endoftext|>


<commit_before>
// Writing script. Automatically pushes changes to server.

var save_timer = null;
window.update_interval = null;
window.old_content = null;
var cur_date = "{{ g.date.strftime('%Y%m%d') }}";
window.last_timestamp = null;
var writing = false;

var CHAR_LIMIT = 10000;

function confess() {
    $('#save_status').html('saving...');
    content = textarea.val();
    $.post('/confess', { content: content, cur_date: cur_date },
        function (data) {
            d = JSON.parse(data);
            $('#save_status').html(d['message']);
            last_timestamp = d['timestamp'];
            //$('#num_entries').html(d['num_entries']);
            console.log('last timestamp updated to ', last_timestamp);
            writing = false;
        }
    );
}

function prime_update() {
    $('#save_status').html('writing...')
    writing = true;
    save_timer = setTimeout(function() {
        $('#save_status').html('saving...')
        confess();
    }, 500);
}

function update_char_count() {
    var count = unescape(encodeURIComponent(textarea.val())).length;
    if (count > 0) {
        $('#char_count').html(count);
    } else {
        $('#char_count').html(' ');
    }

    // Scale textarea
    var orig_scroll = $(document).scrollTop();
    textarea.css("height", "5em");
    textarea.css("height", textarea[0].scrollHeight + "px");
    $(document).scrollTop(orig_scroll);

    return count;
}

window.content_changed = function() {
    var count = update_char_count();
    update_char_count();
    clearTimeout(save_timer);

    if (count <= CHAR_LIMIT) {
        //$('#char_count').removeClass('error');
        old_content = textarea.val();
    }
    else {
        //$('#char_count').addClass('error');
        //$('#save_status').html('too long');
        textarea.val(old_content);
        update_char_count();
    }
    prime_update();
}

window.get_updates = function() {
    $.getJSON('/api/my_current_entry', function(data) {
        if (!writing) {
            if ('datestamp' in data) {
                cur_date = data['datestamp'];
            }
            var mydate = new Date(data['timestamp']*1000);
            var myts = mydate.getTime()/1000;
            if (myts > last_timestamp + 0.5) {
                $('#edit_area').val(data['content']);
                $('#save_status').html('synced!');
                last_timestamp = myts;
                update_char_count();
            }
        }
    });
}

InstantClick.on('change', function (isInitialLoad) {
    //update_char_count();
});

//window.onload = function () {
//    update_char_count();
//    textarea.bind('input propertychange', content_changed);
//    setInterval(get_updates, 1000);
//};

// Infinite scrolling script.
// Currently unused.

var processScroll = true;
var last_date = '{{ posts[-1].posted_date }}';
function proc_scroll () {
    if (processScroll && $(window).scrollTop() > $(document).height() - $(window).height() - 1000) {
        processScroll = false;
        $.get('/+{{ author.sid }}/' + last_date,
          function (data) {
            new_post = $(data)
            last_date = new_post.data('date');
            if (last_date) {
              $('#posts').append(new_post);
              processScroll = true;
              proc_scroll(); // If this wasn't enough, load even more!
            }
          }
        );
    }
}
/*
$(window).scroll(proc_scroll);
proc_scroll();
*/
<commit_msg>update char count whenever get_updatesi s called<commit_after>
// Writing script. Automatically pushes changes to server.

var save_timer = null;
window.update_interval = null;
window.old_content = null;
var cur_date = "{{ g.date.strftime('%Y%m%d') }}";
window.last_timestamp = null;
var writing = false;

var CHAR_LIMIT = 10000;

function confess() {
    $('#save_status').html('saving...');
    content = textarea.val();
    $.post('/confess', { content: content, cur_date: cur_date },
        function (data) {
            d = JSON.parse(data);
            $('#save_status').html(d['message']);
            last_timestamp = d['timestamp'];
            //$('#num_entries').html(d['num_entries']);
            console.log('last timestamp updated to ', last_timestamp);
            writing = false;
        }
    );
}

function prime_update() {
    $('#save_status').html('writing...')
    writing = true;
    save_timer = setTimeout(function() {
        $('#save_status').html('saving...')
        confess();
    }, 500);
}

function update_char_count() {
    var count = unescape(encodeURIComponent(textarea.val())).length;
    if (count > 0) {
        $('#char_count').html(count);
    } else {
        $('#char_count').html(' ');
    }

    // Scale textarea
    var orig_scroll = $(document).scrollTop();
    textarea.css("height", "5em");
    textarea.css("height", textarea[0].scrollHeight + "px");
    $(document).scrollTop(orig_scroll);

    return count;
}

window.content_changed = function() {
    var count = update_char_count();
    update_char_count();
    clearTimeout(save_timer);

    if (count <= CHAR_LIMIT) {
        //$('#char_count').removeClass('error');
        old_content = textarea.val();
    }
    else {
        //$('#char_count').addClass('error');
        //$('#save_status').html('too long');
        textarea.val(old_content);
        update_char_count();
    }
    prime_update();
}

window.get_updates = function() {
    $.getJSON('/api/my_current_entry', function(data) {
        if (!writing) {
            if ('datestamp' in data) {
                cur_date = data['datestamp'];
            }
            var mydate = new Date(data['timestamp']*1000);
            var myts = mydate.getTime()/1000;
            if (myts > last_timestamp + 0.5) {
                $('#edit_area').val(data['content']);
                $('#save_status').html('synced!');
                last_timestamp = myts;
                update_char_count();
            }
        }
    });

    // for good measure
    update_char_count();
}

InstantClick.on('change', function (isInitialLoad) {
    //update_char_count();
});

//window.onload = function () {
//    update_char_count();
//    textarea.bind('input propertychange', content_changed);
//    setInterval(get_updates, 1000);
//};

// Infinite scrolling script.
// Currently unused.

var processScroll = true;
var last_date = '{{ posts[-1].posted_date }}';
function proc_scroll () {
    if (processScroll && $(window).scrollTop() > $(document).height() - $(window).height() - 1000) {
        processScroll = false;
        $.get('/+{{ author.sid }}/' + last_date,
          function (data) {
            new_post = $(data)
            last_date = new_post.data('date');
            if (last_date) {
              $('#posts').append(new_post);
              processScroll = true;
              proc_scroll(); // If this wasn't enough, load even more!
            }
          }
        );
    }
}
/*
$(window).scroll(proc_scroll);
proc_scroll();
*/
<|endoftext|>


<commit_before>// IE<9 lacks Array.prototype.indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for (i=0, l=this.length; i<l; ++i) {
            if (this[i] === needle) return i;
        }
        return -1;
    }
}

django.jQuery(function($){
    // Patch up urlify maps to generate nicer slugs in german
    if(typeof(Downcoder) != "undefined"){
        Downcoder.Initialize() ;
        Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe";
        Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae";
        Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue";
    }

    /* .dataset.context instead of getAttribute would be nicer */
    var ItemEditor = JSON.parse(
        document.getElementById('item-editor-script').getAttribute('data-context'));

    $('h2:contains(' + ItemEditor.feincmsContentFieldsetName + ')').parent().replaceWith($('#main_wrapper'));

    var inlineGroups = (function() {
        var selector = [];
        $.each(ItemEditor.plugins, function(key, value) {
            selector.push('#' + key + '_set-group');
        });
        return $(selector.join(', '));
    })();

    var inlines = inlineGroups.find('.inline-related').detach();
    inlines.sort(function inlinesCompareFunction(a, b) {
        var aOrdering = $(a).find('.field-ordering input').val() || 1e9;
        var bOrdering = $(b).find('.field-ordering input').val() || 1e9;
        return Math.sign(aOrdering - bOrdering);
    });
    $('.order-machine').append(inlines);

    $('.order-machine .inline-related').not('.empty-form').each(function assignRegionDataAttribute() {
        var $this = $(this),
            region = $this.find('.field-region input').val();

        // Have to use attr() here because we want the data attribute to
        // be visible to selectors.
        $this.attr('data-region', region);
    });

    function moveEmptyFormsToEnd() {
        $('.order-machine').append(
            $('.order-machine .empty-form').detach()
        );
    }
    moveEmptyFormsToEnd();

    $(document).on('formset:added', function newForm(event, row, optionsPrefix) {
        moveEmptyFormsToEnd();

        var currentRegion = $('.tabs>.active').data('region');
        row.find('.field-region input').val(currentRegion);
        row.attr('data-region', currentRegion);
    });

    function selectRegion(name) {
        $('.tabs>div').removeClass('active').filter('[data-region="' + name + '"]').addClass('active');
        $('.order-machine .inline-related').not('.empty-form').hide().filter('[data-region="' + name + '"]').show();
    }

    $(document).on('click', '.tabs>div', function() {
        selectRegion($(this).data('region'));
    });

    $('.tabs>div:first').trigger('click');

    $('.order-machine').sortable({
        handle: 'h3',
        placeholder: 'placeholder'
    });
    $('.order-machine').on('click', '.delete>input[type=checkbox]', function() {
        $(this).closest('.inline-related')[this.checked ? 'addClass' : 'removeClass']('for-deletion');
    });

    $('form').submit(function(){
        $('.field-ordering input').each(function assignOrdering(index) {
            this.value = index;
        });

        var form = $(this);
        form.attr('action', form.attr('action') + window.location.hash);
        return true;
    });

    $(document).keydown(function handleKeys(event) {
        if (event.which == 83 && event.metaKey) {
            $('form input[name=' + (event.shiftKey ? '_continue' : '_save') + ']').click();
            return false;
        } else if (event.which == 27) {
            $('.order-machine').sortable('cancel');
        }
    });

})
<commit_msg>Hide fieldsets when dragging<commit_after>// IE<9 lacks Array.prototype.indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for (i=0, l=this.length; i<l; ++i) {
            if (this[i] === needle) return i;
        }
        return -1;
    }
}

django.jQuery(function($){
    // Patch up urlify maps to generate nicer slugs in german
    if(typeof(Downcoder) != "undefined"){
        Downcoder.Initialize() ;
        Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe";
        Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae";
        Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue";
    }

    /* .dataset.context instead of getAttribute would be nicer */
    var ItemEditor = JSON.parse(
        document.getElementById('item-editor-script').getAttribute('data-context'));

    $('h2:contains(' + ItemEditor.feincmsContentFieldsetName + ')').parent().replaceWith($('#main_wrapper'));

    var inlineGroups = (function() {
        var selector = [];
        $.each(ItemEditor.plugins, function(key, value) {
            selector.push('#' + key + '_set-group');
        });
        return $(selector.join(', '));
    })();

    var inlines = inlineGroups.find('.inline-related').detach();
    inlines.sort(function inlinesCompareFunction(a, b) {
        var aOrdering = $(a).find('.field-ordering input').val() || 1e9;
        var bOrdering = $(b).find('.field-ordering input').val() || 1e9;
        return Math.sign(aOrdering - bOrdering);
    });
    $('.order-machine').append(inlines);

    $('.order-machine .inline-related').not('.empty-form').each(function assignRegionDataAttribute() {
        var $this = $(this),
            region = $this.find('.field-region input').val();

        // Have to use attr() here because we want the data attribute to
        // be visible to selectors.
        $this.attr('data-region', region);
    });

    function moveEmptyFormsToEnd() {
        $('.order-machine').append(
            $('.order-machine .empty-form').detach()
        );
    }
    moveEmptyFormsToEnd();

    $(document).on('formset:added', function newForm(event, row, optionsPrefix) {
        moveEmptyFormsToEnd();

        var currentRegion = $('.tabs>.active').data('region');
        row.find('.field-region input').val(currentRegion);
        row.attr('data-region', currentRegion);
    });

    function selectRegion(name) {
        $('.tabs>div').removeClass('active').filter('[data-region="' + name + '"]').addClass('active');
        $('.order-machine .inline-related').not('.empty-form').hide().filter('[data-region="' + name + '"]').show();
    }

    $(document).on('click', '.tabs>div', function() {
        selectRegion($(this).data('region'));
    });

    $('.tabs>div:first').trigger('click');

    $('.order-machine').sortable({
        handle: 'h3',
        placeholder: 'placeholder',
        start: function(event, ui) {
            ui.item.find('fieldset').hide();
        },
        stop: function(event, ui) {
            ui.item.find('fieldset').show();
        }
    });
    $('.order-machine').on('click', '.delete>input[type=checkbox]', function() {
        $(this).closest('.inline-related')[this.checked ? 'addClass' : 'removeClass']('for-deletion');
    });

    $('form').submit(function(){
        $('.field-ordering input').each(function assignOrdering(index) {
            this.value = index;
        });

        var form = $(this);
        form.attr('action', form.attr('action') + window.location.hash);
        return true;
    });

    $(document).keydown(function handleKeys(event) {
        if (event.which == 83 && event.metaKey) {
            $('form input[name=' + (event.shiftKey ? '_continue' : '_save') + ']').click();
            return false;
        } else if (event.which == 27) {
            $('.order-machine').sortable('cancel');
        }
    });

})
<|endoftext|>


<commit_before>var CU = require('../compilerUtils'),
	U = require('../../../utils'),
	styler = require('../styler'),
	CONST = require('../../../common/constants'),
	_ = require('../../../lib/alloy/underscore')._;

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var fullname = CU.getNodeFullname(node),
		parts = fullname.split('.'),
		extras = [];

	// is this just a proxy property?
	if (parts[0] === '_ProxyProperty') {
		return require('./_ProxyProperty.' + parts[1]).parse(node, state);
	}

	// special handling for touchEnabled per ALOY-911
	if (node.hasAttribute('touchEnabled')) {
		var attr = node.getAttribute('touchEnabled');
		extras.push(['touchEnabled', attr === 'true']);
	}
	//if (extras.length) { state.extraStyle = styler.createVariableStyle(extras); }

	if (extras.length) {
		state.extraStyle = state.extraStyle || {};
		state.extraStyle = _.extend(state.extraStyle, styler.createVariableStyle(extras));
	}

	// start assembling a basic view creation
	var createFunc = 'create' + node.nodeName,
		isCollectionBound = args[CONST.BIND_COLLECTION] ? true : false,
		generatedStyle = styler.generateStyleParams(
			state.styles,
			args.classes,
			args.id,
			fullname,
			_.defaults(state.extraStyle || {}, args.createArgs || {}),
			state
		),
		code = '';

	// make symbol a local variable if necessary
	if (state.local) {
		args.symbol = CU.generateUniqueId();
	}

	// Generate runtime code
	if (state.isViewTemplate) {
		var bindId = node.getAttribute('bindId');
		code += (state.local ? 'var ' : '') + args.symbol + '={';
		code += "type:'" + fullname + "',";
		if (bindId) {
			code += "bindId:'" + bindId + "',";
		}

		// apply usual style properties
		var argsObject = { properties: generatedStyle };

		// add in any events on the ItemTemplate
		if (args.events && args.events.length > 0) {
			argsObject.events = '{' + _.reduce(args.events, function(memo,o) {
				return memo + o.name + ':' + o.value + ',';
			}, '') + '}';
		}

		var children = U.XML.getElementsFromNodes(node.childNodes);
		var childTemplates;
		if (children.length > 0) {
			childTemplates = CU.generateUniqueId();

			code += 'childTemplates: (function() {';
			code += 'var ' + childTemplates + '=[];';

			_.each(children, function(child) {
				code += CU.generateNodeExtended(child, state, {
					parent: {},
					local: true,
					isViewTemplate: true,
					post: function(node, state, args) {
						return childTemplates + '.push(' + state.item.symbol + ');';
					}
				});
			});

			code += 'return ' + childTemplates + ';';
			code += '})(),';
		}

		// add the additional arguments to the code
		code += _.reduce(argsObject, function(memo,v,k) {
			return memo + k + ':' + v + ',';
		}, '');

		code += '};';
	} else {
		var module = node.getAttribute('module');
		if (module) {
			createFunc = node.getAttribute('method') || createFunc;
			args.ns = 'require("'+module+'")';
			delete args.createArgs['module'];
			delete args.createArgs['method'];
		}

		code += (state.local ? 'var ' : '') + args.symbol + " = " + args.ns + "." + createFunc + "(\n";
		code += styler.generateStyleParams(
			state.styles,
			args.classes,
			args.id,
			fullname,
			_.defaults(state.extraStyle || {}, args.createArgs || {}),
			state
		) + '\n';
		code += ");\n";
		if (args.parent.symbol) {
			code += args.parent.symbol + ".add(" + args.symbol + ");\n";
		}

		if (isCollectionBound) {
			var localModel = CU.generateUniqueId();
			var itemCode = '';

			_.each(U.XML.getElementsFromNodes(node.childNodes), function(child) {
				itemCode += CU.generateNodeExtended(child, state, {
					parent: {
						node: node,
						symbol: args.symbol
					},
					local: true,
					model: localModel
				});
			});

			var pre = "var children = " + args.symbol + ".children;" +
				"for (var d = children.length-1; d >= 0; d--) {" +
				"	" + args.symbol + ".remove(children[d]);" +
				"}";

			code += _.template(CU.generateCollectionBindingTemplate(args), {
				localModel: localModel,
				pre: pre,
				items: itemCode,
				post: ''
			});
		}
	}

	// Update the parsing state
	var ret = {
		isViewTemplate: state.isViewTemplate || false,
		local: state.local || false,
		model: state.model || undefined,
		condition: state.condition || undefined,
		styles: state.styles,
		code: code
	};
	var nextObj = {
		node: node,
		symbol: args.symbol
	};

	if (state.isViewTemplate) {
		return _.extend(ret, { item: nextObj });
	} else {
		return _.extend(ret, { parent: isCollectionBound ? {} : nextObj });
	}

	return ret;
}
<commit_msg>remove code comment<commit_after>var CU = require('../compilerUtils'),
	U = require('../../../utils'),
	styler = require('../styler'),
	CONST = require('../../../common/constants'),
	_ = require('../../../lib/alloy/underscore')._;

exports.parse = function(node, state) {
	return require('./base').parse(node, state, parse);
};

function parse(node, state, args) {
	var fullname = CU.getNodeFullname(node),
		parts = fullname.split('.'),
		extras = [];

	// is this just a proxy property?
	if (parts[0] === '_ProxyProperty') {
		return require('./_ProxyProperty.' + parts[1]).parse(node, state);
	}

	// special handling for touchEnabled per ALOY-911
	if (node.hasAttribute('touchEnabled')) {
		var attr = node.getAttribute('touchEnabled');
		extras.push(['touchEnabled', attr === 'true']);
	}

	if (extras.length) {
		state.extraStyle = state.extraStyle || {};
		state.extraStyle = _.extend(state.extraStyle, styler.createVariableStyle(extras));
	}

	// start assembling a basic view creation
	var createFunc = 'create' + node.nodeName,
		isCollectionBound = args[CONST.BIND_COLLECTION] ? true : false,
		generatedStyle = styler.generateStyleParams(
			state.styles,
			args.classes,
			args.id,
			fullname,
			_.defaults(state.extraStyle || {}, args.createArgs || {}),
			state
		),
		code = '';

	// make symbol a local variable if necessary
	if (state.local) {
		args.symbol = CU.generateUniqueId();
	}

	// Generate runtime code
	if (state.isViewTemplate) {
		var bindId = node.getAttribute('bindId');
		code += (state.local ? 'var ' : '') + args.symbol + '={';
		code += "type:'" + fullname + "',";
		if (bindId) {
			code += "bindId:'" + bindId + "',";
		}

		// apply usual style properties
		var argsObject = { properties: generatedStyle };

		// add in any events on the ItemTemplate
		if (args.events && args.events.length > 0) {
			argsObject.events = '{' + _.reduce(args.events, function(memo,o) {
				return memo + o.name + ':' + o.value + ',';
			}, '') + '}';
		}

		var children = U.XML.getElementsFromNodes(node.childNodes);
		var childTemplates;
		if (children.length > 0) {
			childTemplates = CU.generateUniqueId();

			code += 'childTemplates: (function() {';
			code += 'var ' + childTemplates + '=[];';

			_.each(children, function(child) {
				code += CU.generateNodeExtended(child, state, {
					parent: {},
					local: true,
					isViewTemplate: true,
					post: function(node, state, args) {
						return childTemplates + '.push(' + state.item.symbol + ');';
					}
				});
			});

			code += 'return ' + childTemplates + ';';
			code += '})(),';
		}

		// add the additional arguments to the code
		code += _.reduce(argsObject, function(memo,v,k) {
			return memo + k + ':' + v + ',';
		}, '');

		code += '};';
	} else {
		var module = node.getAttribute('module');
		if (module) {
			createFunc = node.getAttribute('method') || createFunc;
			args.ns = 'require("'+module+'")';
			delete args.createArgs['module'];
			delete args.createArgs['method'];
		}

		code += (state.local ? 'var ' : '') + args.symbol + " = " + args.ns + "." + createFunc + "(\n";
		code += styler.generateStyleParams(
			state.styles,
			args.classes,
			args.id,
			fullname,
			_.defaults(state.extraStyle || {}, args.createArgs || {}),
			state
		) + '\n';
		code += ");\n";
		if (args.parent.symbol) {
			code += args.parent.symbol + ".add(" + args.symbol + ");\n";
		}

		if (isCollectionBound) {
			var localModel = CU.generateUniqueId();
			var itemCode = '';

			_.each(U.XML.getElementsFromNodes(node.childNodes), function(child) {
				itemCode += CU.generateNodeExtended(child, state, {
					parent: {
						node: node,
						symbol: args.symbol
					},
					local: true,
					model: localModel
				});
			});

			var pre = "var children = " + args.symbol + ".children;" +
				"for (var d = children.length-1; d >= 0; d--) {" +
				"	" + args.symbol + ".remove(children[d]);" +
				"}";

			code += _.template(CU.generateCollectionBindingTemplate(args), {
				localModel: localModel,
				pre: pre,
				items: itemCode,
				post: ''
			});
		}
	}

	// Update the parsing state
	var ret = {
		isViewTemplate: state.isViewTemplate || false,
		local: state.local || false,
		model: state.model || undefined,
		condition: state.condition || undefined,
		styles: state.styles,
		code: code
	};
	var nextObj = {
		node: node,
		symbol: args.symbol
	};

	if (state.isViewTemplate) {
		return _.extend(ret, { item: nextObj });
	} else {
		return _.extend(ret, { parent: isCollectionBound ? {} : nextObj });
	}

	return ret;
}
<|endoftext|>


<commit_before>/**
	_moon.SearchHeader_ extends moon.Header, combining
	a search box with a narrow title.
*/
enyo.kind({
    //* @public
    name: "moon.SearchHeader",
    kind: "moon.Header",
    events: {
        "onSearch": ""
    },
    //* @protected
    classes: "moon-searchheader",
    components: [
        {name: "titleAbove", classes: "moon-searchheader-title-above"},
        {name: "title", classes: "moon-searchheader-title"},
        {name: "titleBelow", kind: "moon.Item", spotlight: false, classes: "moon-searchheader-title-below"},
        {name: "searchInputContainer", kind: "FittableColumns", classes: "moon-searchheader-container", style: "width: 100%;", components: [
            {classes: "moon-searchheader-search-left"},
            {kind: "moon.InputDecorator", layoutKind: "FittableColumnsLayout", fit: true, components: [
                {name: "searchInput", kind: "moon.Input", oninput: "search", fit: true, placeholder: "Search term"},
                {kind: "Image", src: "../samples/assets/search-input-search.png", style: "width: 20px;height:20px;margin-left:10px;"}
            ]},
            {classes: "moon-searchheader-search-right"},
        ]},
        {name: "client", classes: "moon-header-client"},
        {name: "animator", kind: "StyleAnimator", onComplete: "animationComplete"}
    ],

    //* @public

    search: function() {
        this.doSearch({"keyword": this.$.searchInput.getValue()});
    }
});
<commit_msg>GF-7977: Change relative path to $lib path<commit_after>/**
	_moon.SearchHeader_ extends moon.Header, combining
	a search box with a narrow title.
*/
enyo.kind({
    //* @public
    name: "moon.SearchHeader",
    kind: "moon.Header",
    events: {
        "onSearch": ""
    },
    //* @protected
    classes: "moon-searchheader",
    components: [
        {name: "titleAbove", classes: "moon-searchheader-title-above"},
        {name: "title", classes: "moon-searchheader-title"},
        {name: "titleBelow", kind: "moon.Item", spotlight: false, classes: "moon-searchheader-title-below"},
        {name: "searchInputContainer", kind: "FittableColumns", classes: "moon-searchheader-container", style: "width: 100%;", components: [
            {classes: "moon-searchheader-search-left"},
            {kind: "moon.InputDecorator", layoutKind: "FittableColumnsLayout", fit: true, components: [
                {name: "searchInput", kind: "moon.Input", oninput: "search", fit: true, placeholder: "Search term"},
                {kind: "Image", src: "$lib/moonstone/samples/assets/search-input-search.png", style: "width: 20px;height:20px;margin-left:10px;"}
            ]},
            {classes: "moon-searchheader-search-right"}
        ]},
        {name: "client", classes: "moon-header-client"},
        {name: "animator", kind: "StyleAnimator", onComplete: "animationComplete"}
    ],

    //* @public

    search: function() {
        this.doSearch({"keyword": this.$.searchInput.getValue()});
    }
});
<|endoftext|>