<commit_before>
function dxf_wrapInputWithSectionDeclaration(inp){
  var out = "";
  out += "0\n";
  out += "SECTION\n";
  out += inp;
  out += "0\n";
  out += "ENDSEC\n";
  return out;
}

function genDxfHeader(bounds, options){
  var unit = 4;//4==mm, 1==in, 2==ft, 5==cm, 6==m.

  var out = "";
  out += "2\n";
  out += "HEADER\n";

  out += "9\n"
  out += "$INSUNITS\n";
  out += "70\n";
  out += String(unit) + "\n";
  return dxf_wrapInputWithSectionDeclaration(out);
}

function genDxfEntityForPath(bounds, options, path, pathName){
  var s = '';
  var layer = 0;//default layer

  for(var i = 0; i < path.length; i++) {
    var op = path[i];
    switch (op.type) {

      case 'line':
        s += '0\n';
        s += "LINE\n";
        s += "8\n";
        s += String(layer) + "\n";

        s += "10\n";
        s += String(op.startx) + "\n";
        s += "20\n";
        s += String(op.starty) + "\n";
        s += "11\n";
        s += String(op.endx) + "\n";
        s += "21\n";
        s += String(op.endy) + "\n";
        break;

      case 'circle':
        s += '0\n';
        s += "CIRCLE\n";
        s += "8\n";
        s += String(layer) + "\n";

        s += "10\n";
        s += String(op.x) + "\n";
        s += "20\n";
        s += String(op.y) + "\n";
        s += "40\n";
        s += String(op.radius) + "\n";
        break;
    }
  }

  return s;
}

function genDxfTrailer(bounds, options) {

  return "0\nEOF";
}

function genDxfEntitiesFromPaths(bounds, options, paths) {
  var out = "";
  out += "2\n";
  out += "ENTITIES\n";

  for (var pathName in paths) {
    if (paths.hasOwnProperty(pathName)) {
      var path = paths[pathName];
      out += genDxfEntityForPath(bounds, options, path, pathName);
    }
  }

  return dxf_wrapInputWithSectionDeclaration(out);
}

(function(){
  ddlRenderTargets['dxf'] = function(execOutputContext, options){
    var bounds = parsePathsForMaxMin(execOutputContext);
    var content_out = genDxfHeader(bounds, options);
    //TODO: Generate layer declaration content (if needed)

    var paths = execOutputContext.paths;
    content_out += genDxfEntitiesFromPaths(bounds, options, paths)

    content_out += genDxfTrailer(bounds, options);
    console.log(content_out);
    return content_out;
  }
})();
<commit_msg>Set the file as MM in another way?<commit_after>
function dxf_wrapInputWithSectionDeclaration(inp){
  var out = "";
  out += "0\n";
  out += "SECTION\n";
  out += inp;
  out += "0\n";
  out += "ENDSEC\n";
  return out;
}

function genDxfHeader(bounds, options){
  var unit = 4;//4==mm, 1==in, 2==ft, 5==cm, 6==m.

  var out = "";
  out += "2\n";
  out += "HEADER\n";

  out += "9\n"
  out += "$INSUNITS\n";
  out += "70\n";
  out += String(unit) + "\n";

  //lmn-laser utility seems to do this:
  out += "9\n"
  out += "$MEASUREMENT\n";
  out += "70\n";
  out += "1\n";

  return dxf_wrapInputWithSectionDeclaration(out);
}

function genDxfEntityForPath(bounds, options, path, pathName){
  var s = '';
  var layer = 0;//default layer

  for(var i = 0; i < path.length; i++) {
    var op = path[i];
    switch (op.type) {

      case 'line':
        s += '0\n';
        s += "LINE\n";
        s += "8\n";
        s += String(layer) + "\n";

        s += "10\n";
        s += String(op.startx) + "\n";
        s += "20\n";
        s += String(op.starty) + "\n";
        s += "11\n";
        s += String(op.endx) + "\n";
        s += "21\n";
        s += String(op.endy) + "\n";
        break;

      case 'circle':
        s += '0\n';
        s += "CIRCLE\n";
        s += "8\n";
        s += String(layer) + "\n";

        s += "10\n";
        s += String(op.x) + "\n";
        s += "20\n";
        s += String(op.y) + "\n";
        s += "40\n";
        s += String(op.radius) + "\n";
        break;
    }
  }

  return s;
}

function genDxfTrailer(bounds, options) {

  return "0\nEOF";
}

function genDxfEntitiesFromPaths(bounds, options, paths) {
  var out = "";
  out += "2\n";
  out += "ENTITIES\n";

  for (var pathName in paths) {
    if (paths.hasOwnProperty(pathName)) {
      var path = paths[pathName];
      out += genDxfEntityForPath(bounds, options, path, pathName);
    }
  }

  return dxf_wrapInputWithSectionDeclaration(out);
}

(function(){
  ddlRenderTargets['dxf'] = function(execOutputContext, options){
    var bounds = parsePathsForMaxMin(execOutputContext);
    var content_out = genDxfHeader(bounds, options);
    //TODO: Generate layer declaration content (if needed)

    var paths = execOutputContext.paths;
    content_out += genDxfEntitiesFromPaths(bounds, options, paths)

    content_out += genDxfTrailer(bounds, options);
    console.log(content_out);
    return content_out;
  }
})();
<|endoftext|>


<commit_before>function contextualizeNodes(cy){
    cy.startBatch()
    var cell_line = $('#cellSelectDynamic').val().substring(6, $('#cellSelectDynamic').val().length-5)
    var ctxt_exp = ctxt['CCLE']['bin_expression'][bins][cell_line]
    var ctxt_mut = ctxt['CCLE']['mutation'][cell_line]
    cy.nodes().forEach(function(n){
        var data = n.data()
        // if the node has members, build pie chart background arrays, qtips
        if (data.hasOwnProperty("members")){
          members = data.members;
          var fam_length = Object.keys(members).length
            if (fam_length > 0){
              var pie_sizes = new Array(16).fill(0);
              var pie_colors = new Array(16).fill(default_colors[5]);
              var current_slice = 0;
              for (var gene in members) {
                var ctxt_bin = ctxt_exp[gene]
                pie_sizes[current_slice] = (100*(1/fam_length));
                // if a gene exists in the context object, set its color
                // if a gene does not exist in context, it is already grey
                // as per the array conditions above
                if (ctxt_bin !== null){
                    if (((ctxt_mut[gene]) !== 1) && ((ctxt_exp[gene]) !== undefined)){
                      pie_colors[current_slice] = exp_colorscale[bins][(ctxt_exp[gene])]
                    }
                    if (((ctxt_mut[gene]) === 1) && ((ctxt_exp[gene]) !== undefined)){
                      pie_colors[current_slice] = mut_colorscale[bins][(ctxt_exp[gene])]
                    }
                }

                current_slice += 1;
              }
            n.data('pie_sizes', pie_sizes);
            n.data('pie_colors', pie_colors);

            n.addClass('hasMembers');

            }
        }// member check

        // call out to qtip api if node is not parent
        if (n.isParent() == false){
            var gene = n.data().name
            var ctxt_bin = ctxt_exp[gene]
            if (ctxt_bin !== null){
                var bkg_col = default_colors[5]
                if (((ctxt_mut[gene]) !== 1) && ((ctxt_exp[gene]) !== undefined)){
                   bkg_col = exp_colorscale[bins][(ctxt_exp[gene])]
                }
                if (((ctxt_mut[gene]) === 1) && ((ctxt_exp[gene]) !== undefined)){
                  bkg_col = mut_colorscale[bins][(ctxt_exp[gene])]
                }
                n.style({'background-color' : bkg_col})
            }
        }; // check if n.isParent()

      });
  cy.endBatch()
}
<commit_msg>Remove unused contextualizeNodes.js<commit_after><|endoftext|>


<commit_before>$(function() {
	// Hide unnecessary divs for DTM
	var newLabelsLocation = $("#normalize-options").parent();
	var newNormalizeLocation = $("#temp-label-div").parent();
	var tempNormalize = $("#normalize-options").html();
	var tempLabels = $("#temp-label-div").html();
	$("#normalize-options").remove();
	$("#temp-label-div").remove();
	newLabels = $('<fieldset class="analyze-advanced-options" id="temp-label-div"></fieldset>').append(tempLabels);
	newNormalize = $('<fieldset class="analyze-advanced-options" id="normalize-options"></fieldset>').append(tempNormalize);
	newLabelsLocation.append(newLabels);
	newNormalizeLocation.append(newNormalize);

	$("#normalize-options").hide();
	/*$("#culling-options").hide();*/

//   $("#normalize-options").empty().html($("#temp-label-div").html());
//   $("#temp-label-div").empty().html(tempContent);
	//$("#temp-label-div").css("position","relative").css("left","-10px").css("top","0px");

	// Error handling before submit
	$('#getsims').click( function() {
		if ($('#num_active_files').val() < 2) {
			$('#error-message').text("You must have at least 2 active documents to proceed!");
			$('#error-message').show().fadeOut(3000);
			return false;
		} else {
			$("#status-analyze").css({"visibility":"visible", "z-index": "400000"});
			return true;
		}
	});

	// Display selected document name on screen
	function makeFilenameStr(fileID) {
		var selectedFilename = "Selected Document: " + documentLabels[fileID];
		$("#selectedDocument").text(selectedFilename);
	}

	if ($("input[type=radio]").is(':checked')) {
		makeFilenameStr($("input[type=radio]:checked").val());
	}

	function createList() {
		var columnValues = [];
		var rows = (docsListScore.length - 1);
		for (i = 0; i < rows; i++) {
			j = i + 1;
			columnValues[i] = [j.toString(), docsListName[i], docsListScore[i].toString()];
			valStr = '
'+j.toString()+'	'+docsListName[i]+'	'+docsListScore[i].toString()+'
';
			$("#simtable tbody").append(valStr);
		}
		// $("#status-analyze").css({"visibility":"hidden"});

	    $('#simtable').DataTable({
	        "paging": true,
	        "searching": true,
	        "ordering": true,
	        "info": true
	    });
	}

	if (docsListScore  != "") {
		createList();
	}
});

	// Code to try and make the tokenize box look pretty on simQ page.  Only works in firefox? Makes templabels disappear in chromium
	// var brow, usrAG = navigator.userAgent;		// Catch browser info
	// if (usrAG.indexOf("Firefox") > -1) {        // if 'firefox' in browser name then apply this style stuff
	// 	$("#temp-label-div").css("position","relative").css("top","-126px").css("left","-10px");
	// 	$("#analyze-advanced").css("max-height","150px").css("overflow","hidden");

	// 	$("input[name='tokenType']").click(function(){
	// 		if ($(this).val() == 'word'){
	// 			$("#temp-label-div").css("top","-126px");
	// 		} else {
	// 			$("#temp-label-div").css("top","-161px");
	// 		}
	// 	});
	// }

// Old createList function
/*	function createList() {

		mytable = $('

').attr({id: "basicTable"});

		// title row
		var titleRow = $('

').appendTo(mytable);
		$('	').text("Rank").appendTo(titleRow);
		$('	').text("Filename").appendTo(titleRow);
		$('	').text("Cosine Similarity").appendTo(titleRow);

		// rankings
		var rows = (docsListScore.length - 1);
		var cols = 3;
		var tr = [];
		for (var i = 0; i < rows; i++) {
			var row = $('

').appendTo(mytable);
			for (var j = 0; j < cols; j++) {

				if (j == 0) {
					$('	').text(i + 1).appendTo(row);
				} else if (j == 1) {
					$('	').text(docsListName[i]).appendTo(row);
				} else {
					$('	').text(docsListScore[i]).appendTo(row);
				}
			}//for
		}//for

		mytable.appendTo("#simstable");
	}*/
// End old createList function

<commit_msg>Fixed display label<commit_after>$(function() {
	// Hide unnecessary divs for DTM
	var newLabelsLocation = $("#normalize-options").parent();
	var newNormalizeLocation = $("#temp-label-div").parent();
	var tempNormalize = $("#normalize-options").html();
	var tempLabels = $("#temp-label-div").html();
	$("#normalize-options").remove();
	$("#temp-label-div").remove();
	newLabels = $('<fieldset class="analyze-advanced-options" id="temp-label-div"></fieldset>').append(tempLabels);
	newNormalize = $('<fieldset class="analyze-advanced-options" id="normalize-options"></fieldset>').append(tempNormalize);
	newLabelsLocation.append(newLabels);
	newNormalizeLocation.append(newNormalize);

	$("#normalize-options").hide();
	/*$("#culling-options").hide();*/

//   $("#normalize-options").empty().html($("#temp-label-div").html());
//   $("#temp-label-div").empty().html(tempContent);
	//$("#temp-label-div").css("position","relative").css("left","-10px").css("top","0px");

	// Error handling before submit
	$('#getsims').click( function() {
		if ($('#num_active_files').val() < 2) {
			$('#error-message').text("You must have at least 2 active documents to proceed!");
			$('#error-message').show().fadeOut(3000);
			return false;
		} else {
			$("#status-analyze").css({"visibility":"visible", "z-index": "400000"});
			return true;
		}
	});

	// Display selected document name on screen
	function makeFilenameStr(fileID) {
		var selectedFilename = "Selected Document: " + documentLabels[fileID];
		$("#selectedDocument").text(selectedFilename);
	}

	if ($("input[type=radio]").is(':checked')) {
		makeFilenameStr($("input[type=radio]:checked").val());
	}

	function createList() {
		var columnValues = [];
		var rows = (docsListScore.length - 1);
		for (i = 0; i < rows; i++) {
			j = i + 1;
			columnValues[i] = [j.toString(), docsListName[i], docsListScore[i].toString()];
			valStr = '
'+j.toString()+'	'+docsListName[i]+'	'+docsListScore[i].toString()+'
';
			$("#simtable tbody").append(valStr);
		}
		// $("#status-analyze").css({"visibility":"hidden"});

	    $('#simtable').DataTable({
	        "paging": true,
	        "searching": true,
	        "ordering": true,
	        "info": true,
	        "language": {
				"lengthMenu": "Display _MENU_ documents per page",
    		}
	    });
	}

	if (docsListScore  != "") {
		createList();
	}
});

	// Code to try and make the tokenize box look pretty on simQ page.  Only works in firefox? Makes templabels disappear in chromium
	// var brow, usrAG = navigator.userAgent;		// Catch browser info
	// if (usrAG.indexOf("Firefox") > -1) {        // if 'firefox' in browser name then apply this style stuff
	// 	$("#temp-label-div").css("position","relative").css("top","-126px").css("left","-10px");
	// 	$("#analyze-advanced").css("max-height","150px").css("overflow","hidden");

	// 	$("input[name='tokenType']").click(function(){
	// 		if ($(this).val() == 'word'){
	// 			$("#temp-label-div").css("top","-126px");
	// 		} else {
	// 			$("#temp-label-div").css("top","-161px");
	// 		}
	// 	});
	// }

// Old createList function
/*	function createList() {

		mytable = $('

').attr({id: "basicTable"});

		// title row
		var titleRow = $('

').appendTo(mytable);
		$('	').text("Rank").appendTo(titleRow);
		$('	').text("Filename").appendTo(titleRow);
		$('	').text("Cosine Similarity").appendTo(titleRow);

		// rankings
		var rows = (docsListScore.length - 1);
		var cols = 3;
		var tr = [];
		for (var i = 0; i < rows; i++) {
			var row = $('

').appendTo(mytable);
			for (var j = 0; j < cols; j++) {

				if (j == 0) {
					$('	').text(i + 1).appendTo(row);
				} else if (j == 1) {
					$('	').text(docsListName[i]).appendTo(row);
				} else {
					$('	').text(docsListScore[i]).appendTo(row);
				}
			}//for
		}//for

		mytable.appendTo("#simstable");
	}*/
// End old createList function

<|endoftext|>


<commit_before>lock = false;

// Add new (not yet released) code from Dallinger.
Dallinger.submitQuestionnaire = function (name) {
  var formSerialized = $("form").serializeArray(),
      formDict = {},
      deferred = $.Deferred();

  formSerialized.forEach(function (field) {
      formDict[field.name] = field.value;
  });

  reqwest({
    method: "post",
    url: "/question/" + participantId,
    data: {
      question: name || "questionnaire",
      number: 1,
      response: JSON.stringify(formDict),
    },
    type: "json",
    success: function (resp) {
      deferred.resolve();
    },
    error: function (err) {
      deferred.reject();
      var errorResponse = JSON.parse(err.response);
      $("body").html(errorResponse.html);
    }
  });

  return deferred;
};

// Cribbed from Dallinger Griduniverse repo:
// https://github.com/Dallinger/Griduniverse/blob/master/dlgr/griduniverse/static/scripts/questionnaire.js
$(document).ready( function() {

  // Submit the questionnaire.
  $("#submit-questionnaire").click(function() {
    var $elements = [$("form :input"), $(this)],
        questionSubmission = Dallinger.submitQuestionnaire("questionnaire");
        console.log("Submitting questionnaire.");
    questionSubmission.done(function()
        {
          go_to_page('debriefing');
        });
  });
});
<commit_msg>Linter fixes: Using single quotes<commit_after>lock = false;

// Add new (not yet released) code from Dallinger.
Dallinger.submitQuestionnaire = function (name) {
  var formSerialized = $("form").serializeArray(),
      formDict = {},
      deferred = $.Deferred();

  formSerialized.forEach(function (field) {
      formDict[field.name] = field.value;
  });

  reqwest({
    method: 'post',
    url: '/question/' + participantId,
    data: {
      question: name || 'questionnaire',
      number: 1,
      response: JSON.stringify(formDict),
    },
    type: 'json',
    success: function (resp) {
      deferred.resolve();
    },
    error: function (err) {
      deferred.reject();
      var errorResponse = JSON.parse(err.response);
      $('body').html(errorResponse.html);
    }
  });

  return deferred;
};

// Cribbed from Dallinger Griduniverse repo:
// https://github.com/Dallinger/Griduniverse/blob/master/dlgr/griduniverse/static/scripts/questionnaire.js
$(document).ready( function() {

  // Submit the questionnaire.
  $("#submit-questionnaire").click(function() {
    var $elements = [$("form :input"), $(this)],
        questionSubmission = Dallinger.submitQuestionnaire("questionnaire");
        console.log("Submitting questionnaire.");
    questionSubmission.done(function()
        {
          go_to_page('debriefing');
        });
  });
});
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2007 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control/ZoomBox.js
 * @requires OpenLayers/Control/DragPan.js
 * @requires OpenLayers/Handler/MouseWheel.js
 */

/**
 * Class: OpenLayers.Control.Navigation
 * The navigation control handles map browsing with mouse events (dragging,
 *     double-clicking, and scrolling the wheel).  Create a new navigation
 *     control with the <OpenLayers.Control.Navigation> control.
 *
 *     Note that this control is added to the map by default (if no controls
 *     array is sent in the options object to the <OpenLayers.Map>
 *     constructor).
 *
 * Inherits:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, {

    /**
     * Property: dragPan
     * {<OpenLayers.Control.DragPan>}
     */
    dragPan: null,

    /**
     * Property: zoomBox
     * {<OpenLayers.Control.ZoomBox>}
     */
    zoomBox: null,

    /**
     * Property: wheelHandler
     * {<OpenLayers.Handler.MouseWheel>}
     */
    wheelHandler: null,

    /**
     * Constructor: OpenLayers.Control.Navigation
     * Create a new navigation control
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *                    the control
     */
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
    },

    /**
     * Method: activate
     */
    activate: function() {
        this.dragPan.activate();
        this.wheelHandler.activate();
        this.clickHandler.activate();
        this.zoomBox.activate();
        return OpenLayers.Control.prototype.activate.apply(this,arguments);
    },

    /**
     * Method: deactivate
     */
    deactivate: function() {
        this.zoomBox.deactivate();
        this.dragPan.deactivate();
        this.clickHandler.deactivate();
        this.wheelHandler.deactivate();
        return OpenLayers.Control.prototype.deactivate.apply(this,arguments);
    },

    /**
     * Method: draw
     */
    draw: function() {
        this.clickHandler = new OpenLayers.Handler.Click(this,
                                        { 'dblclick': this.defaultDblClick },
                                        {
                                          'double': true,
                                          'stopDouble': true
                                        });
        this.dragPan = new OpenLayers.Control.DragPan({map: this.map});
        this.zoomBox = new OpenLayers.Control.ZoomBox(
                    {map: this.map, keyMask: OpenLayers.Handler.MOD_SHIFT});
        this.dragPan.draw();
        this.zoomBox.draw();
        this.wheelHandler = new OpenLayers.Handler.MouseWheel(
                                    this, {"up"  : this.wheelUp,
                                           "down": this.wheelDown} );
        this.activate();
    },

    /**
     * Method: defaultDblClick
     *
     * Parameters:
     * evt - {Event}
     */
    defaultDblClick: function (evt) {
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
    },

    /**
     * Method: wheelChange
     *
     * Parameters:
     * evt - {Event}
     */
    wheelChange: function(evt, deltaZ) {
        var newZoom = this.map.getZoom() + deltaZ;
        if (!this.map.isValidZoomLevel(newZoom)) {
            return;
        }
        var size    = this.map.getSize();
        var deltaX  = size.w/2 - evt.xy.x;
        var deltaY  = evt.xy.y - size.h/2;
        var newRes  = this.map.baseLayer.resolutions[newZoom];
        var zoomPoint = this.map.getLonLatFromPixel(evt.xy);
        var newCenter = new OpenLayers.LonLat(
                            zoomPoint.lon + deltaX * newRes,
                            zoomPoint.lat + deltaY * newRes );
        this.map.setCenter( newCenter, newZoom );
    },

    /**
     * Method: wheelUp
     * User spun scroll wheel up
     *
     * Parameters:
     * evt - {Event}
     */
    wheelUp: function(evt) {
        this.wheelChange(evt, 1);
    },

    /**
     * Method: wheelDown
     * User spun scroll wheel down
     *
     * Parameters:
     * evt - {Event}
     */
    wheelDown: function(evt) {
        this.wheelChange(evt, -1);
    },

    CLASS_NAME: "OpenLayers.Control.Navigation"
});
<commit_msg>adding click handler as dependency to navigation control<commit_after>/* Copyright (c) 2006-2007 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control/ZoomBox.js
 * @requires OpenLayers/Control/DragPan.js
 * @requires OpenLayers/Handler/MouseWheel.js
 * @requires OpenLayers/Handler/Click.js
 */

/**
 * Class: OpenLayers.Control.Navigation
 * The navigation control handles map browsing with mouse events (dragging,
 *     double-clicking, and scrolling the wheel).  Create a new navigation
 *     control with the <OpenLayers.Control.Navigation> control.
 *
 *     Note that this control is added to the map by default (if no controls
 *     array is sent in the options object to the <OpenLayers.Map>
 *     constructor).
 *
 * Inherits:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, {

    /**
     * Property: dragPan
     * {<OpenLayers.Control.DragPan>}
     */
    dragPan: null,

    /**
     * Property: zoomBox
     * {<OpenLayers.Control.ZoomBox>}
     */
    zoomBox: null,

    /**
     * Property: wheelHandler
     * {<OpenLayers.Handler.MouseWheel>}
     */
    wheelHandler: null,

    /**
     * Constructor: OpenLayers.Control.Navigation
     * Create a new navigation control
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *                    the control
     */
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
    },

    /**
     * Method: activate
     */
    activate: function() {
        this.dragPan.activate();
        this.wheelHandler.activate();
        this.clickHandler.activate();
        this.zoomBox.activate();
        return OpenLayers.Control.prototype.activate.apply(this,arguments);
    },

    /**
     * Method: deactivate
     */
    deactivate: function() {
        this.zoomBox.deactivate();
        this.dragPan.deactivate();
        this.clickHandler.deactivate();
        this.wheelHandler.deactivate();
        return OpenLayers.Control.prototype.deactivate.apply(this,arguments);
    },

    /**
     * Method: draw
     */
    draw: function() {
        this.clickHandler = new OpenLayers.Handler.Click(this,
                                        { 'dblclick': this.defaultDblClick },
                                        {
                                          'double': true,
                                          'stopDouble': true
                                        });
        this.dragPan = new OpenLayers.Control.DragPan({map: this.map});
        this.zoomBox = new OpenLayers.Control.ZoomBox(
                    {map: this.map, keyMask: OpenLayers.Handler.MOD_SHIFT});
        this.dragPan.draw();
        this.zoomBox.draw();
        this.wheelHandler = new OpenLayers.Handler.MouseWheel(
                                    this, {"up"  : this.wheelUp,
                                           "down": this.wheelDown} );
        this.activate();
    },

    /**
     * Method: defaultDblClick
     *
     * Parameters:
     * evt - {Event}
     */
    defaultDblClick: function (evt) {
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
    },

    /**
     * Method: wheelChange
     *
     * Parameters:
     * evt - {Event}
     */
    wheelChange: function(evt, deltaZ) {
        var newZoom = this.map.getZoom() + deltaZ;
        if (!this.map.isValidZoomLevel(newZoom)) {
            return;
        }
        var size    = this.map.getSize();
        var deltaX  = size.w/2 - evt.xy.x;
        var deltaY  = evt.xy.y - size.h/2;
        var newRes  = this.map.baseLayer.resolutions[newZoom];
        var zoomPoint = this.map.getLonLatFromPixel(evt.xy);
        var newCenter = new OpenLayers.LonLat(
                            zoomPoint.lon + deltaX * newRes,
                            zoomPoint.lat + deltaY * newRes );
        this.map.setCenter( newCenter, newZoom );
    },

    /**
     * Method: wheelUp
     * User spun scroll wheel up
     *
     * Parameters:
     * evt - {Event}
     */
    wheelUp: function(evt) {
        this.wheelChange(evt, 1);
    },

    /**
     * Method: wheelDown
     * User spun scroll wheel down
     *
     * Parameters:
     * evt - {Event}
     */
    wheelDown: function(evt) {
        this.wheelChange(evt, -1);
    },

    CLASS_NAME: "OpenLayers.Control.Navigation"
});
<|endoftext|>


<commit_before>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */
// @require: OpenLayers/Layer/EventPane.js

/**
 * @class
 */
OpenLayers.Layer.VirtualEarth = Class.create();
OpenLayers.Layer.VirtualEarth.prototype =
  Object.extend( new OpenLayers.Layer.EventPane(), {
    /** @type VEMap */
    vemap: null,

    /**
     * @constructor
     *
     * @param {String} name
     */
    initialize:function(name) {
        OpenLayers.Layer.EventPane.prototype.initialize.apply(this, arguments);
    },

    /**
     * @param {OpenLayers.Map} map
     */
    setMap:function(map) {
        OpenLayers.Layer.EventPane.prototype.setMap.apply(this, arguments);

        // once our layer has been added to the map, we can load the vemap
        this.loadVEMap();
    },

    /**
     * @param {OpenLayers.Bounds} bounds
     * @param {Boolean} zoomChanged
     * @param {Boolean} minor
     */
    moveTo:function(bounds, zoomChanged, minor) {

        if (this.vemap != null) {
            var olCenter = this.map.getCenter();
            var olZoom = this.map.getZoom();

            var veCenter = this.getVELatLongFromOLLonLat(olCenter);
            var veZoom = this.getVEZoomFromOLZoom(olZoom);

            this.vemap.SetCenterAndZoom(veCenter, veZoom);
        }
    },

    /**
     *
     */
    loadVEMap:function() {
        // create div and set to same size as map
        var veDiv = OpenLayers.Util.createDiv(this.name);
        var sz = this.map.getSize();
        veDiv.style.width = sz.w;
        veDiv.style.height = sz.h;
        this.div.appendChild(veDiv);

        try {

            // create VEMap, hide nav controls
            this.vemap = new VEMap(this.name);
        } catch (e) {
            // do nothing this is to keep from crashing
            // if the VE library was not loaded.
        }

        if (this.vemap == null) {
            this.loadWarningMessage();
        } else {

            try {
                this.vemap.LoadMap();
            } catch (e) {
                // this is to catch a Mozilla bug without falling apart
            }

            this.vemap.HideDashboard();

            // catch pans and zooms from VE Map
            //this.vemap.AttachEvent("onendcontinuouspan",
            //                       this.catchPanZoom.bindAsEventListener(this));
            //this.vemap.AttachEvent("onendzoom",
            //                       this.catchPanZoom.bindAsEventListener(this));
        }

    },

    /** If we can't load the vemap, then display an error message to the
     *   user and tell them where to go for help.
     *
     * @private
     *
     */
    loadWarningMessage:function() {

        this.div.style.backgroundColor = "darkblue";

        var html = "";
        html += "The VE Layer was unable to load correctly.
";
        html += "
";
        html += "To get rid of this message, click on the VE Layer's "
        html += "tab in the layer switcher in the upper-right corner.
";
        html += "
";
        html += "Most likely, this is because the VE library";
        html += " script was either not correctly included.
";
        html += "
";
        html += "Developers: For help getting this working correctly, ";
        html += "";
        html +=     "click here";
        html += "";

        var viewSize = this.map.getSize();

        msgW = Math.min(viewSize.w, 300);
        msgH = Math.min(viewSize.h, 200);
        var size = new OpenLayers.Size(msgW, msgH);

        var centerPx = new OpenLayers.Pixel(viewSize.w/2, viewSize.h/2);

        var topLeft = centerPx.add(-size.w/2, -size.h/2);

        var div = OpenLayers.Util.createDiv("veWarning",
                                            topLeft,
                                            size,
                                            null,
                                            null,
                                            null,
                                            "auto");

        div.style.padding = "7px";
        div.style.backgroundColor = "yellow";

        div.innerHTML = html;
        this.div.appendChild(div);
    },

    /**
     * @param {Event} e
     */
    catchPanZoom: function(e) {

        var veCenter = this.vemap.GetCenter();
        var veZoom = this.vemap.GetZoomLevel();

        var olCenter = this.getOLLonLatFromVELatLong(veCenter);
        var olZoom = this.getOLZoomFromVEZoom(veZoom);

        this.map.setCenter(olCenter, olZoom);
    },

  /********************************************************/
  /*                                                      */
  /*                 Baselayer Functions                  */
  /*                                                      */
  /********************************************************/

    /**
     * @param {OpenLayers.Pixel} viewPortPx
     *
     * @returns An OpenLayers.LonLat which is the passed-in view port
     *          OpenLayers.Pixel, translated into lon/lat by VE
     *          If vemap is not loaded, returns null.
     * @type OpenLayers.LonLat
     */
    getLonLatFromViewPortPx: function (viewPortPx) {
        var lonlat = null;
        if (this.vemap != null) {
            var pixel = this.getPixelFromOLPixel(viewPortPx);
            var zoom = this.vemap.GetZoomLevel();
            var veLatLong = this.vemap.PixelToLatLong(pixel.x, pixel.y, zoom);
            lonlat = this.getOLLonLatFromVELatLong(veLatLong);
        }
        return lonlat;
    },

    /**
     * @param {OpenLayers.LonLat} lonlat
     *
     * @returns An OpenLayers.Pixel which is the passed-in OpenLayers.LonLat,
     *          translated into view port pixels BY VE
     *          If vemap is not loaded, returns null.
     * @type OpenLayers.Pixel
     */
    getViewPortPxFromLonLat: function (lonlat) {
        var viewPortPx = null;
        if (this.vemap != null) {
            var veLatLong = this.getVELatLongFromOLLonLat(lonlat);
            var pixel = this.vemap.LatLongToPixel(veLatLong);
            viewPortPx = this.getOLPixelFromPixel(pixel);
        }
        return viewPortPx;
    },

    /**
     * @param {OpenLayers.Bounds} bounds
     *
     * @returns Corresponding zoom level for a specified Bounds.
     *          If vemap is not loaded, returns null.
     * @type int
     */
    getZoomForExtent: function (bounds) {
        var zoom = null;
        if (this.vemap != null) {
            var gBounds = this.getVELatLongBoundsFromOLBounds(bounds);
            var gZoom = this.vemap.getBoundsZoomLevel(gBounds);
            zoom = this.getOLZoomFromGZoom(gZoom);
        }
        return zoom;
    },

  /********************************************************/
  /*                                                      */
  /*             Translation Functions                    */
  /*                                                      */
  /*    The following functions translate GMaps and OL    */
  /*     formats for Pixel, LonLat, Bounds, and Zoom      */
  /*                                                      */
  /********************************************************/

  //
  // TRANSLATION: GZoom <-> OpenLayers Zoom
  //

    /**
     * @param {int} veZoom
     *
     * @returns An OpenLayers Zoom level, translated from the passed in veZoom
     *          Returns null if null value is passed in
     * @type int
     */
    getOLZoomFromVEZoom: function(veZoom) {
        var zoom = null;
        if (veZoom != null) {
            zoom = veZoom;
        }
        return zoom;
    },

    /**
     * @param {int} olZoom
     *
     * @returns A VEZoom level, translated from the passed in olZoom
     *          Returns null if null value is passed in
     * @type int
     */
    getVEZoomFromOLZoom: function(olZoom) {
        var zoom = null;
        if (olZoom != null) {
            zoom = olZoom;
        }
        return zoom;
    },

  //
  // TRANSLATION: VELatLong <-> LonLat
  //

    /**
     * @param {VELatLong} veLatLong
     *
     * @returns An OpenLayers.LonLat, translated from the passed in VELatLong
     *          Returns null if null value is passed in
     * @type OpenLayers.LonLat
     */
    getOLLonLatFromVELatLong: function(veLatLong) {
        var olLonLat = null;
        if (veLatLong != null) {
            olLonLat = new OpenLayers.LonLat(veLatLong.Longitude,
                                             veLatLong.Latitude);
        }
        return olLonLat;
    },

    /**
     * @param {OpenLayers.LonLat} olLonLat
     *
     * @returns A VELatLong, translated from the passed in OpenLayers.LonLat
     *          Returns null if null value is passed in
     * @type VELatLong
     */
    getVELatLongFromOLLonLat: function(olLonLat) {
        var veLatLong = null;
        if (olLonLat != null) {
            veLatLong = new VELatLong(olLonLat.lat, olLonLat.lon);
        }
        return veLatLong;
    },

  //
  // TRANSLATION: Pixel <-> OpenLayers.Pixel
  //

    /**
     * @param {Pixel} pixel
     *
     * @returns An OpenLayers.Pixel, translated from the passed in Pixel
     *          Returns null if null value is passed in
     * @type OpenLayers.Pixel
     */
    getOLPixelFromPixel: function(pixel) {
        var olPixel = null;
        if (pixel != null) {
            olPixel = new OpenLayers.Pixel(pixel.x, pixel.y);
        }
        return olPixel;
    },

    /**
     * @param {OpenLayers.Pixel} olPixel
     *
     * @returns A Pixel, translated from the passed in OpenLayers.Pixel
     *          Returns null if null value is passed in
     *
     *          As it turns out, the only specifications we can see for the
     *          VE-compatible Pixel is an x & y property, which every
     *          OpenLayers.Pixel has by default. So just leave it as-is.
     *
     * @type Pixel
     */
    getPixelFromOLPixel: function(olPixel) {
        var pixel = null;
        if (olPixel != null) {
            pixel = new Msn.VE.Pixel(olPixel.x, olPixel.y);
        }
        return pixel;
    },

  //
  // TRANSLATION: VELatLongBounds <-> OpenLayers.Bounds
  //

    /**
     * @param {VELatLongBounds} veLatLongBounds
     *
     * @returns An OpenLayers.Bounds, translated from veLatLongBounds
     *          Returns null if null value is passed in
     * @type OpenLayers.Bounds
     */
    getOLBoundsFromVELatLongBounds: function(veLatLongBounds) {
        var olBounds = null;
        if (veLatLongBounds != null) {
            var sw = veLatLongBounds.getSouthWest();
            var ne = veLatLongBounds.getNorthEast();
            olBounds = new OpenLayers.Bounds(sw.lng(),
                                             sw.lat(),
                                             ne.lng(),
                                             ne.lat() );
        }
        return olBounds;
    },

    /**
     * @param {OpenLayers.Bounds} olBounds
     *
     * @returns A VELatLongBounds, translated from olBounds
     *          Returns null if null value is passed in
     * @type VELatLongBounds
     */
    getVELatLongBoundsFromOLBounds: function(olBounds) {
        var veLatLongBounds = null;
        if (olBounds != null) {
            var sw = new VELatLong(olBounds.bottom, olBounds.left);
            var ne = new VELatLong(olBounds.top, olBounds.right);
            veLatLongBounds = new VELatLongBounds(sw, ne);
        }
        return veLatLongBounds;
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Layer.VirtualEarth"
});
<commit_msg>Since VirtualEarth doesn't understand bounds at all, this function didn't work. This is not an ideal situation, becauuse it's not really 100% correct for a  mercator projection, but it does cause things to work.<commit_after>/* Copyright (c) 2006 MetaCarta, Inc., published under the BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the full
 * text of the license. */
// @require: OpenLayers/Layer/EventPane.js

/**
 * @class
 */
OpenLayers.Layer.VirtualEarth = Class.create();
OpenLayers.Layer.VirtualEarth.prototype =
  Object.extend( new OpenLayers.Layer.EventPane(), {
    /** @type VEMap */
    vemap: null,

    /**
     * @constructor
     *
     * @param {String} name
     */
    initialize:function(name) {
        OpenLayers.Layer.EventPane.prototype.initialize.apply(this, arguments);
    },

    /**
     * @param {OpenLayers.Map} map
     */
    setMap:function(map) {
        OpenLayers.Layer.EventPane.prototype.setMap.apply(this, arguments);

        // once our layer has been added to the map, we can load the vemap
        this.loadVEMap();
    },

    /**
     * @param {OpenLayers.Bounds} bounds
     * @param {Boolean} zoomChanged
     * @param {Boolean} minor
     */
    moveTo:function(bounds, zoomChanged, minor) {

        if (this.vemap != null) {
            var olCenter = this.map.getCenter();
            var olZoom = this.map.getZoom();

            var veCenter = this.getVELatLongFromOLLonLat(olCenter);
            var veZoom = this.getVEZoomFromOLZoom(olZoom);

            this.vemap.SetCenterAndZoom(veCenter, veZoom);
        }
    },

    /**
     *
     */
    loadVEMap:function() {
        // create div and set to same size as map
        var veDiv = OpenLayers.Util.createDiv(this.name);
        var sz = this.map.getSize();
        veDiv.style.width = sz.w;
        veDiv.style.height = sz.h;
        this.div.appendChild(veDiv);

        try {

            // create VEMap, hide nav controls
            this.vemap = new VEMap(this.name);
        } catch (e) {
            // do nothing this is to keep from crashing
            // if the VE library was not loaded.
        }

        if (this.vemap == null) {
            this.loadWarningMessage();
        } else {

            try {
                this.vemap.LoadMap();
            } catch (e) {
                // this is to catch a Mozilla bug without falling apart
            }

            this.vemap.HideDashboard();

            // catch pans and zooms from VE Map
            //this.vemap.AttachEvent("onendcontinuouspan",
            //                       this.catchPanZoom.bindAsEventListener(this));
            //this.vemap.AttachEvent("onendzoom",
            //                       this.catchPanZoom.bindAsEventListener(this));
        }

    },

    /** If we can't load the vemap, then display an error message to the
     *   user and tell them where to go for help.
     *
     * @private
     *
     */
    loadWarningMessage:function() {

        this.div.style.backgroundColor = "darkblue";

        var html = "";
        html += "The VE Layer was unable to load correctly.
";
        html += "
";
        html += "To get rid of this message, click on the VE Layer's "
        html += "tab in the layer switcher in the upper-right corner.
";
        html += "
";
        html += "Most likely, this is because the VE library";
        html += " script was either not correctly included.
";
        html += "
";
        html += "Developers: For help getting this working correctly, ";
        html += "";
        html +=     "click here";
        html += "";

        var viewSize = this.map.getSize();

        msgW = Math.min(viewSize.w, 300);
        msgH = Math.min(viewSize.h, 200);
        var size = new OpenLayers.Size(msgW, msgH);

        var centerPx = new OpenLayers.Pixel(viewSize.w/2, viewSize.h/2);

        var topLeft = centerPx.add(-size.w/2, -size.h/2);

        var div = OpenLayers.Util.createDiv("veWarning",
                                            topLeft,
                                            size,
                                            null,
                                            null,
                                            null,
                                            "auto");

        div.style.padding = "7px";
        div.style.backgroundColor = "yellow";

        div.innerHTML = html;
        this.div.appendChild(div);
    },

    /**
     * @param {Event} e
     */
    catchPanZoom: function(e) {

        var veCenter = this.vemap.GetCenter();
        var veZoom = this.vemap.GetZoomLevel();

        var olCenter = this.getOLLonLatFromVELatLong(veCenter);
        var olZoom = this.getOLZoomFromVEZoom(veZoom);

        this.map.setCenter(olCenter, olZoom);
    },

  /********************************************************/
  /*                                                      */
  /*                 Baselayer Functions                  */
  /*                                                      */
  /********************************************************/

    /**
     * @param {OpenLayers.Pixel} viewPortPx
     *
     * @returns An OpenLayers.LonLat which is the passed-in view port
     *          OpenLayers.Pixel, translated into lon/lat by VE
     *          If vemap is not loaded, returns null.
     * @type OpenLayers.LonLat
     */
    getLonLatFromViewPortPx: function (viewPortPx) {
        var lonlat = null;
        if (this.vemap != null) {
            var pixel = this.getPixelFromOLPixel(viewPortPx);
            var zoom = this.vemap.GetZoomLevel();
            var veLatLong = this.vemap.PixelToLatLong(pixel.x, pixel.y, zoom);
            lonlat = this.getOLLonLatFromVELatLong(veLatLong);
        }
        return lonlat;
    },

    /**
     * @param {OpenLayers.LonLat} lonlat
     *
     * @returns An OpenLayers.Pixel which is the passed-in OpenLayers.LonLat,
     *          translated into view port pixels BY VE
     *          If vemap is not loaded, returns null.
     * @type OpenLayers.Pixel
     */
    getViewPortPxFromLonLat: function (lonlat) {
        var viewPortPx = null;
        if (this.vemap != null) {
            var veLatLong = this.getVELatLongFromOLLonLat(lonlat);
            var pixel = this.vemap.LatLongToPixel(veLatLong);
            viewPortPx = this.getOLPixelFromPixel(pixel);
        }
        return viewPortPx;
    },

    /**
     * @param {OpenLayers.Bounds} bounds
     *
     * @returns Corresponding zoom level for a specified Bounds.
     *          If vemap is not loaded, returns null.
     * @type int
     */
    getZoomForExtent: function (bounds) {

        var maxRes = this.map.getMaxResolution();
        var viewSize = this.map.getSize();

        var width = bounds.getWidth();
        var height = bounds.getHeight();

        var degPerPixel = (width > height) ? width / viewSize.w
                                           : height / viewSize.h;

        var zoom = Math.floor( (Math.log(maxRes/degPerPixel)) / Math.log(2) );

        var maxZoomLevel = this.map.getMaxZoomLevel();
        var minZoomLevel = this.map.getMinZoomLevel();

        //make sure zoom is within bounds
        zoom = Math.min( Math.max(zoom, minZoomLevel),
                         maxZoomLevel );

        return zoom;
    },

  /********************************************************/
  /*                                                      */
  /*             Translation Functions                    */
  /*                                                      */
  /*    The following functions translate GMaps and OL    */
  /*     formats for Pixel, LonLat, Bounds, and Zoom      */
  /*                                                      */
  /********************************************************/

  //
  // TRANSLATION: GZoom <-> OpenLayers Zoom
  //

    /**
     * @param {int} veZoom
     *
     * @returns An OpenLayers Zoom level, translated from the passed in veZoom
     *          Returns null if null value is passed in
     * @type int
     */
    getOLZoomFromVEZoom: function(veZoom) {
        var zoom = null;
        if (veZoom != null) {
            zoom = veZoom;
        }
        return zoom;
    },

    /**
     * @param {int} olZoom
     *
     * @returns A VEZoom level, translated from the passed in olZoom
     *          Returns null if null value is passed in
     * @type int
     */
    getVEZoomFromOLZoom: function(olZoom) {
        var zoom = null;
        if (olZoom != null) {
            zoom = olZoom;
        }
        return zoom;
    },

  //
  // TRANSLATION: VELatLong <-> LonLat
  //

    /**
     * @param {VELatLong} veLatLong
     *
     * @returns An OpenLayers.LonLat, translated from the passed in VELatLong
     *          Returns null if null value is passed in
     * @type OpenLayers.LonLat
     */
    getOLLonLatFromVELatLong: function(veLatLong) {
        var olLonLat = null;
        if (veLatLong != null) {
            olLonLat = new OpenLayers.LonLat(veLatLong.Longitude,
                                             veLatLong.Latitude);
        }
        return olLonLat;
    },

    /**
     * @param {OpenLayers.LonLat} olLonLat
     *
     * @returns A VELatLong, translated from the passed in OpenLayers.LonLat
     *          Returns null if null value is passed in
     * @type VELatLong
     */
    getVELatLongFromOLLonLat: function(olLonLat) {
        var veLatLong = null;
        if (olLonLat != null) {
            veLatLong = new VELatLong(olLonLat.lat, olLonLat.lon);
        }
        return veLatLong;
    },

  //
  // TRANSLATION: Pixel <-> OpenLayers.Pixel
  //

    /**
     * @param {Pixel} pixel
     *
     * @returns An OpenLayers.Pixel, translated from the passed in Pixel
     *          Returns null if null value is passed in
     * @type OpenLayers.Pixel
     */
    getOLPixelFromPixel: function(pixel) {
        var olPixel = null;
        if (pixel != null) {
            olPixel = new OpenLayers.Pixel(pixel.x, pixel.y);
        }
        return olPixel;
    },

    /**
     * @param {OpenLayers.Pixel} olPixel
     *
     * @returns A Pixel, translated from the passed in OpenLayers.Pixel
     *          Returns null if null value is passed in
     *
     *          As it turns out, the only specifications we can see for the
     *          VE-compatible Pixel is an x & y property, which every
     *          OpenLayers.Pixel has by default. So just leave it as-is.
     *
     * @type Pixel
     */
    getPixelFromOLPixel: function(olPixel) {
        var pixel = null;
        if (olPixel != null) {
            pixel = new Msn.VE.Pixel(olPixel.x, olPixel.y);
        }
        return pixel;
    },

  //
  // TRANSLATION: VELatLongBounds <-> OpenLayers.Bounds
  //

    /**
     * @param {VELatLongBounds} veLatLongBounds
     *
     * @returns An OpenLayers.Bounds, translated from veLatLongBounds
     *          Returns null if null value is passed in
     * @type OpenLayers.Bounds
     */
    getOLBoundsFromVELatLongBounds: function(veLatLongBounds) {
        var olBounds = null;
        if (veLatLongBounds != null) {
            var sw = veLatLongBounds.getSouthWest();
            var ne = veLatLongBounds.getNorthEast();
            olBounds = new OpenLayers.Bounds(sw.lng(),
                                             sw.lat(),
                                             ne.lng(),
                                             ne.lat() );
        }
        return olBounds;
    },

    /**
     * @param {OpenLayers.Bounds} olBounds
     *
     * @returns A VELatLongBounds, translated from olBounds
     *          Returns null if null value is passed in
     * @type VELatLongBounds
     */
    getVELatLongBoundsFromOLBounds: function(olBounds) {
        var veLatLongBounds = null;
        if (olBounds != null) {
            var sw = new VELatLong(olBounds.bottom, olBounds.left);
            var ne = new VELatLong(olBounds.top, olBounds.right);
            veLatLongBounds = new VELatLongBounds(sw, ne);
        }
        return veLatLongBounds;
    },

    /** @final @type String */
    CLASS_NAME: "OpenLayers.Layer.VirtualEarth"
});
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var leanHighlightRules = function() {

    var keywordControls = (
        ["import", "tactic_hint", "protected", "find_decl",
         "private", "opaque", "definition", "renaming", "hiding", "exposing",
         "parameter", "parameters", "begin", "proof", "qed", "conjecture", "premise", "premises",
         "constant", "constants", "example", "attribute", "local",
         "hypothesis", "lemma", "corollary", "variable", "variables", "print",
         "theorem", "context", "open", "as", "export", "axiom", "inductive",
         "with", "structure", "record", "universe", "universes", "alias", "help", "environment",
         "options", "precedence", "postfix", "prefix", "calc_trans",
         "calc_subst", "calc_refl", "infix", "infixl", "infixr", "notation",
         "eval", "check", "exit", "end", "using", "namespace",
         "section", "set_option", "omit", "classes", "instances", "coercions", "raw",
         "add_rewrite", "extends", "calc", "have", "obtains", "show", "by", "in", "let",
         "forall", "fun", "exists", "if", "then", "else", "assume", "match",
         "take", "obtain", "from", "axioms", "fields"].join("|")
    );

    var storageType = (
        ["Prop", "Type", "Type'", "Type₊", "Type₁", "Type₂", "Type₃"].join("|")
    );

    var storageModifiers = (
        "\\[(" +
            ["persistent", "notation", "parsing-only", "visible", "instance", "class", "prefix", "axioms", "fields",
             "multiple-instances", "classes", "instances", "coercions", "options", "trust",
             "coercion", "reducible", "irreducible", "raw"].join("|") +
            ")\\]"
    );

    var keywordOperators = (
        [].join("|")
    );

    var builtinConstants = (
        "NULL|true|false|TRUE|FALSE"
    );

    var keywordMapper = this.$keywords = this.createKeywordMapper({
        "keyword.control" : keywordControls,
        "storage.type" : storageType,
        "keyword.operator" : keywordOperators,
        "variable.language": "sorry",
        "constant.language": builtinConstants
    }, "identifier");

    var identifierRe = "[A-Za-z_\u03b1-\u03ba\u03bc-\u03fb\u1f00-\u1ffe\u2100-\u214f][A-Za-z0-9_'\u03b1-\u03ba\u03bc-\u03fb\u1f00-\u1ffe\u2070-\u2079\u207f-\u2089\u2090-\u209c\u2100-\u214f]*";
    var operatorRe = new RegExp(["#", "@", "->", "∼", "↔", "/", "==", "=", ":=", "<->",
                                 "/\\", "\\/", "∧", "∨", "≠", "<", ">", "≤", "≥", "¬",
                                 "<=", ">=", "⁻¹", "⬝", "▸", "\\+", "\\*", "-", "/",
                                 "λ", "→", "∃", "∀", ":="].join("|"));
    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [
            {
                token : "comment", // single line comment "--"
                regex : "--.*$"
            },
            DocCommentHighlightRules.getStartRule("doc-start"),
            {
                token : "comment", // multi line comment "/-"
                regex : "\\/-",
                next : "comment"
            }, {
                token : "string", // single line
                regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
            }, {
                token : "string", // multi line string start
                regex : '["].*\\\\$',
                next : "qqstring"
            }, {
                token : "constant.numeric", // hex
                regex : "0[xX][0-9a-fA-F]+(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b"
            }, {
                token : "constant.numeric", // float
                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b"
            }, {
                token : "storage.modifier",
                regex : storageModifiers
            }, {
                token : "keyword", // pre-compiler directives
                regex : "#\\s*(?:include|import|pragma|line|define|undef|if|ifdef|else|elif|ifndef)\\b",
                next  : "directive"
            }, {
                token : "keyword", // special case pre-compiler directive
                regex : "(?:#\\s*endif)\\b"
            }, {
                token : keywordMapper,
                regex : identifierRe
            }, {
                token : "operator",
                regex : operatorRe
            }, {
              token : "punctuation.operator",
              regex : "\\?|\\:|\\,|\\;|\\."
            }, {
                token : "paren.lparen",
                regex : "[[({]"
            }, {
                token : "paren.rparen",
                regex : "[\\])}]"
            }, {
                token : "text",
                regex : "\\s+"
            }
        ],
        "comment" : [ {token: "comment", regex: "-/", next: "start"},
                      {defaultToken: "comment"} ],
        "qqstring" : [ {token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" },
                       {defaultToken: "qqstring"} ],
        "directive" : [
            {
                token : "constant.other.multiline",
                regex : /\\/
            },
            {
                token : "constant.other.multiline",
                regex : /.*\\/
            },
            {
                token : "constant.other",
                regex : "\\s*<.+?>",
                next : "start"
            },
            {
                token : "constant.other", // single line
                regex : '\\s*["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]',
                next : "start"
            },
            {
                token : "constant.other", // single line
                regex : "\\s*['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']",
                next : "start"
            },
            // "\" implies multiline, while "/" implies comment
            {
                token : "constant.other",
                regex : /[^\\\/]+/,
                next : "start"
            }
        ]
    };

    this.embedRules(DocCommentHighlightRules, "doc-",
        [ DocCommentHighlightRules.getEndRule("start") ]);
};

oop.inherits(leanHighlightRules, TextHighlightRules);

exports.leanHighlightRules = leanHighlightRules;
});
<commit_msg>clean up unused rules for lean-mode<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var leanHighlightRules = function() {

    var keywordControls = (
        ["import", "tactic_hint", "protected", "find_decl",
         "private", "opaque", "definition", "renaming", "hiding", "exposing",
         "parameter", "parameters", "begin", "proof", "qed", "conjecture", "premise", "premises",
         "constant", "constants", "example", "attribute", "local",
         "hypothesis", "lemma", "corollary", "variable", "variables", "print",
         "theorem", "context", "open", "as", "export", "axiom", "inductive",
         "with", "structure", "record", "universe", "universes", "alias", "help", "environment",
         "options", "precedence", "postfix", "prefix", "calc_trans",
         "calc_subst", "calc_refl", "infix", "infixl", "infixr", "notation",
         "eval", "check", "exit", "end", "using", "namespace",
         "section", "set_option", "omit", "classes", "instances", "coercions", "raw",
         "add_rewrite", "extends", "calc", "have", "obtains", "show", "by", "in", "let",
         "forall", "fun", "exists", "if", "then", "else", "assume", "match",
         "take", "obtain", "from", "axioms", "fields"].join("|")
    );

    var storageType = (
        ["Prop", "Type", "Type'", "Type₊", "Type₁", "Type₂", "Type₃"].join("|")
    );

    var storageModifiers = (
        "\\[(" +
            ["persistent", "notation", "parsing-only", "visible", "instance", "class", "prefix", "axioms", "fields",
             "multiple-instances", "classes", "instances", "coercions", "options", "trust",
             "coercion", "reducible", "irreducible", "raw"].join("|") +
            ")\\]"
    );

    var keywordOperators = (
        [].join("|")
    );

    var keywordMapper = this.$keywords = this.createKeywordMapper({
        "keyword.control" : keywordControls,
        "storage.type" : storageType,
        "keyword.operator" : keywordOperators,
        "variable.language": "sorry",
    }, "identifier");

    var identifierRe = "[A-Za-z_\u03b1-\u03ba\u03bc-\u03fb\u1f00-\u1ffe\u2100-\u214f][A-Za-z0-9_'\u03b1-\u03ba\u03bc-\u03fb\u1f00-\u1ffe\u2070-\u2079\u207f-\u2089\u2090-\u209c\u2100-\u214f]*";
    var operatorRe = new RegExp(["#", "@", "->", "∼", "↔", "/", "==", "=", ":=", "<->",
                                 "/\\", "\\/", "∧", "∨", "≠", "<", ">", "≤", "≥", "¬",
                                 "<=", ">=", "⁻¹", "⬝", "▸", "\\+", "\\*", "-", "/",
                                 "λ", "→", "∃", "∀", ":="].join("|"));
    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [
            {
                token : "comment", // single line comment "--"
                regex : "--.*$"
            },
            DocCommentHighlightRules.getStartRule("doc-start"),
            {
                token : "comment", // multi line comment "/-"
                regex : "\\/-",
                next : "comment"
            }, {
                token : "string", // single line
                regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
            }, {
                token : "string", // multi line string start
                regex : '["].*\\\\$',
                next : "qqstring"
            }, {
                token : "constant.numeric", // hex
                regex : "0[xX][0-9a-fA-F]+(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b"
            }, {
                token : "constant.numeric", // float
                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b"
            }, {
                token : "storage.modifier",
                regex : storageModifiers
            }, {
                token : keywordMapper,
                regex : identifierRe
            }, {
                token : "operator",
                regex : operatorRe
            }, {
              token : "punctuation.operator",
              regex : "\\?|\\:|\\,|\\;|\\."
            }, {
                token : "paren.lparen",
                regex : "[[({]"
            }, {
                token : "paren.rparen",
                regex : "[\\])}]"
            }, {
                token : "text",
                regex : "\\s+"
            }
        ],
        "comment" : [ {token: "comment", regex: "-/", next: "start"},
                      {defaultToken: "comment"} ]
    };

    this.embedRules(DocCommentHighlightRules, "doc-",
        [ DocCommentHighlightRules.getEndRule("start") ]);
};

oop.inherits(leanHighlightRules, TextHighlightRules);

exports.leanHighlightRules = leanHighlightRules;
});
<|endoftext|>


<commit_before>/*
---
script: template.js
license: MIT-style license.
description: Template - Context aware template engine with conditional replacement & iteration.
copyright: Copyright (c) 2011 Thierry Bela
authors: [Thierry Bela]

requires:
  core:1.3:
  - Class
  - Elements.from

provides: [Template]
...
*/

//TODO: use less regExp
!function (context, undefined) {

"use strict";

	function log() { if(context.console && context.console.log) context.console.log.apply(context.console, arguments) }

	context.Template = new Class({

		options: {

			debug: true,
			//handle unknown tag
			parse: function (tag, matches /*, name, data, string, regExp, replace, simplereg, options */) {

				/* if(options.debug)  */log('unknown tag: ' + tag, matches);

				return matches[3]
			},
			begin: '{',
			end: '}'
		},

		modifiers: {},

		initialize: function (options) {

			this.options = Object.append(this.options, options)
		},

		addModifier: function (name, fn) {

			if(typeof name == 'object') Object.each(function (name, value) { this.modifiers[name] = value }, this);

			else this.modifiers[name] = fn;

			return this
		},

		html: function () { return Elements.from(this.substitute.apply(this, arguments)) },

		substitute: function (string, data, options) {

			options = Object.append({}, this.options, options);

			var replace ={begin: options.begin.escapeRegExp(), end: options.end.escapeRegExp()},
				match = new RegExp('{begin}([a-z0-9][a-z0-9-_]*):([a-z0-9_.-]*){end}'.substitute(replace), 'i'),
				simplereg = new RegExp(('\\\\?{begin}([^\\s' + (['[', ']'].indexOf(options.begin) != -1 ? replace.begin : replace.begin.replace(/\\/g, '')) + ']+){end}').substitute(replace), 'g');

			return this.parse(string, replace, match, simplereg, data, options)
		},

		parse: function (string, replace, match, simplereg, data, options) {

			var matches;

			if(data != undefined) {

				do {

					matches = match.exec(string);

					if(matches) {

						var open,
							close,

							index, //index of the first match
							index2,//index of the last match
							index3,//index of the {else: ...} match
							tag,
							test,
							name,
							context,
							//el,
							elseif,
							html,
							subject,
							partial,
							substring;

						tag = matches[1];
						name = matches[2];

						open = options.begin + tag + ':' + name + options.end;
						close = options.begin + '/' + tag + ':' + name + options.end;

						index2 = string.indexOf(close);

						if(index2 == -1) {

							if(options.debug && name.indexOf(':') != -1) log('suspicious token found: "' + match + '", is the closing token missing ?', string);
							string = string.replace(open, '')
						}

						index = string.indexOf(open);

						substring = string.substring(index + open.length, index2);
						partial = open + substring + close;

						switch(tag) {

							case 'if':
							case 'defined':
							case 'empty':
							case 'not-empty':

									//switch context for object or array
									subject = this.evaluate(data, name);

									test = this.test(tag, subject);

									context = test && tag == 'if' && typeof subject == 'object';
									elseif = options.begin + 'else:' + name + options.end;

									//if-else or something like that
									index3 = string.indexOf(elseif);

									if(index3 != -1) {

										if(!test) string = string.replace(partial, this.parse(string.substring(index3 + elseif.length, index2), replace, match, simplereg, subject, options));

										else if(context) string = string.replace(partial, this.parse(string.substring(index3 + elseif.length, index2), replace, match, simplereg, subject, options));
										else string = string.replace(partial, this.parse(string.substring(index + open.length, index3), replace, match, simplereg, data, options));
									}

									else {

										if(!test) string = string.replace(partial, '');

										else if(context) string = string.replace(partial, this.parse(substring, replace, match, simplereg, subject, options));
										else string = this.parse(string.replace(partial, this.parse(substring, data, options)), replace, match, simplereg, data, options);
									}

								break;

							case 'repeat':
							case 'loop':

								html = '';
								subject = tag == 'loop' ? (typeof data == 'function' ? data() : data) : this.evaluate(data, name);

								if(!this.test(tag, subject)) string = string.replace(partial, '');

								else {

									var value, property, single = new RegExp(options.begin.escapeRegExp() + '\.' + options.end.escapeRegExp(), 'g');

									//iterable - Array or Hash like
									if(typeof subject.each == 'function')  subject.each(function (value) {

										if(typeof value == 'function') value = value();

										if(value == undefined) return;

										html += typeof value != 'object' ? substring.replace(single, value) : this.parse(substring, replace, match, simplereg, value, options)
									}, this);

									else for(property in subject) if(subject.hasOwnProperty(property)) {

										value = this.evaluate(subject, property);

										if(value == undefined) continue;

										//hopefully matches[3] should be a simple token. replace {.} by the property value
										html += typeof value != 'object' ? substring.replace(single, value) : this.parse(substring, replace, match, simplereg, value, options)
									}

									string = string.replace(partial, html)
								}

								break;

							default:

								var tmp = options.parse(tag, matches, name, data, string, options);

								string = string.replace(partial, tmp == undefined ? '' : tmp)
						}
					}
				}

				while(matches)
			}

			//log(simplereg)
			return string.replace(simplereg, function(match, name) {

				if (match.charAt(0) == '\\') return match.slice(1);

				if(options.debug && name.indexOf(':') != -1) console.log('suspicious token found: "' + match + '", is the opening token missing ?', string);

				var value = this.evaluate(data, name);

				return value == undefined ? '' : value

			}.bind(this))
		},

		test: function (tag, value) {

			switch(tag) {

				case 'if':
				case 'not-empty':
						return !!value;

				case 'defined':
						return value != undefined;
				case 'empty':
						return !value;

				case 'loop':
				case 'repeat':
						return value != undefined && ['object', 'function'].indexOf(typeof value)  != -1;
			}

			return true
		},

		evaluate: function (object, property) {

			if(object == undefined) return undefined;

			if(this.modifiers[property] != undefined) return this.modifiers[property](object, property);

			if(property.indexOf('.') != -1) {

				var value = typeof object == 'function' ? object() : object, paths = property.split('.'), key, i;

				for(i = 0; i < paths.length; i++) {

					key = paths[i];

					if(value[key] == undefined) return undefined;

					value = typeof value[key] == 'function' ? value[key]() : value[key]
				}

				return value
			}

			return typeof object[property] == 'function' ? object[property]() : object[property]
		}
	})

}(this);
<commit_msg>bug fix<commit_after>/*
---
script: template.js
license: MIT-style license.
description: Template - Context aware template engine with conditional replacement & iteration.
copyright: Copyright (c) 2011 Thierry Bela
authors: [Thierry Bela]

requires:
  core:1.3:
  - Class
  - Elements.from

provides: [Template]
...
*/

//TODO: use less regExp
!function (context, undefined) {

"use strict";

	function log() { if(context.console && context.console.log) context.console.log.apply(context.console, arguments) }

	context.Template = new Class({

		options: {

			debug: true,
			//handle unknown tag
			parse: function (tag, name, substring/* , partial, string, data, options */) {

				/* if(options.debug)  */log('unknown tag: ' + tag, name);

				return substring
			},
			begin: '{',
			end: '}'
		},

		modifiers: {},

		initialize: function (options) {

			this.options = Object.append(this.options, options)
		},

		addModifier: function (name, fn) {

			if(typeof name == 'object') Object.each(function (name, value) { this.modifiers[name] = value }, this);

			else this.modifiers[name] = fn;

			return this
		},

		html: function () { return Elements.from(this.substitute.apply(this, arguments)) },

		substitute: function (string, data, options) {

			options = Object.append({}, this.options, options);

			var replace ={begin: options.begin.escapeRegExp(), end: options.end.escapeRegExp()},
				match = new RegExp('{begin}([a-z0-9][a-z0-9-_]*):([a-z0-9_.-]*){end}'.substitute(replace), 'i'),
				simplereg = new RegExp(('\\\\?{begin}([^\\s' + (['[', ']'].indexOf(options.begin) != -1 ? replace.begin : replace.begin.replace(/\\/g, '')) + ']+){end}').substitute(replace), 'g');

			return this.parse(string, replace, match, simplereg, data, options)
		},

		parse: function (string, replace, match, simplereg, data, options) {

			var matches;

			if(data != undefined) {

				do {

					matches = match.exec(string);

					if(matches) {

						var open,
							close,

							index, //index of the first match
							index2,//index of the last match
							index3,//index of the {else: ...} match
							tag,
							test,
							name,
							context,
							//el,
							elseif,
							html,
							subject,
							partial,
							substring;

						tag = matches[1];
						name = matches[2];

						open = options.begin + tag + ':' + name + options.end;
						close = options.begin + '/' + tag + ':' + name + options.end;

						index2 = string.indexOf(close);

						if(index2 == -1) {

							if(options.debug && name.indexOf(':') != -1) log('suspicious token found: "' + match + '", is the closing token missing ?', string);
							string = string.replace(open, '')
						}

						index = string.indexOf(open);

						substring = string.substring(index + open.length, index2);
						partial = open + substring + close;

						switch(tag) {

							case 'if':
							case 'defined':
							case 'empty':
							case 'not-empty':

									//switch context for object or array
									subject = this.evaluate(data, name);

									test = this.test(tag, subject);

									context = test && tag == 'if' && typeof subject == 'object';
									elseif = options.begin + 'else:' + name + options.end;

									//if-else or something like that
									index3 = string.indexOf(elseif);

									if(index3 != -1) {

										if(!test) string = string.replace(partial, this.parse(string.substring(index3 + elseif.length, index2), replace, match, simplereg, subject, options));

										else if(context) string = string.replace(partial, this.parse(string.substring(index3 + elseif.length, index2), replace, match, simplereg, subject, options));
										else string = string.replace(partial, this.parse(string.substring(index + open.length, index3), replace, match, simplereg, data, options));
									}

									else {

										if(!test) string = string.replace(partial, '');

										else if(context) string = string.replace(partial, this.parse(substring, replace, match, simplereg, subject, options));
										else string = this.parse(string.replace(partial, this.parse(substring, data, options)), replace, match, simplereg, data, options);
									}

								break;

							case 'repeat':
							case 'loop':

								html = '';
								subject = tag == 'loop' ? (typeof data == 'function' ? data() : data) : this.evaluate(data, name);

								if(!this.test(tag, subject)) string = string.replace(partial, '');

								else {

									var value, property, single = new RegExp(options.begin.escapeRegExp() + '\.' + options.end.escapeRegExp(), 'g');

									//iterable - Array or Hash like
									if(typeof subject.each == 'function')  subject.each(function (value) {

										if(typeof value == 'function') value = value();

										if(value == undefined) return;

										html += typeof value != 'object' ? substring.replace(single, value) : this.parse(substring, replace, match, simplereg, value, options)
									}, this);

									else for(property in subject) if(subject.hasOwnProperty(property)) {

										value = this.evaluate(subject, property);

										if(value == undefined) continue;

										//hopefully matches[3] should be a simple token. replace {.} by the property value
										html += typeof value != 'object' ? substring.replace(single, value) : this.parse(substring, replace, match, simplereg, value, options)
									}

									string = string.replace(partial, html)
								}

								break;

							default:

								var tmp = options.parse(tag, name, substring, partial, string, data, options);

								string = string.replace(partial, tmp == undefined ? '' : tmp)
						}
					}
				}

				while(matches)
			}

			//log(simplereg)
			return string.replace(simplereg, function(match, name) {

				if (match.charAt(0) == '\\') return match.slice(1);

				if(options.debug && name.indexOf(':') != -1) console.log('suspicious token found: "' + match + '", is the opening token missing ?', string);

				var value = this.evaluate(data, name);

				return value == undefined ? '' : value

			}.bind(this))
		},

		test: function (tag, value) {

			switch(tag) {

				case 'if':
				case 'not-empty':
						return !!value;

				case 'defined':
						return value != undefined;
				case 'empty':
						return !value;

				case 'loop':
				case 'repeat':
						return value != undefined && ['object', 'function'].indexOf(typeof value)  != -1;
			}

			return true
		},

		evaluate: function (object, property) {

			if(object == undefined) return undefined;

			if(this.modifiers[property] != undefined) return this.modifiers[property](object, property);

			if(property.indexOf('.') != -1) {

				var value = typeof object == 'function' ? object() : object, paths = property.split('.'), key, i;

				for(i = 0; i < paths.length; i++) {

					key = paths[i];

					if(value[key] == undefined) return undefined;

					value = typeof value[key] == 'function' ? value[key]() : value[key]
				}

				return value
			}

			return typeof object[property] == 'function' ? object[property]() : object[property]
		}
	})

}(this);
<|endoftext|>