<commit_before>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {
// ************************************************************************************************

// ************************************************************************************************
// Script Module

Firebug.Script = extend(Firebug.Module,
{
    getPanel: function()
    {
        return Firebug.chrome ? Firebug.chrome.getPanel("Script") : null;
    },

    selectSourceCode: function(index)
    {
        this.getPanel().selectSourceCode(index);
    }
});

Firebug.registerModule(Firebug.Script);

// ************************************************************************************************
// Script Panel

function ScriptPanel(){};

ScriptPanel.prototype = extend(Firebug.Panel,
{
    name: "Script",
    title: "Script",

    sourceIndex: 0,
    lastSourceIndex: -1,

    options: {
        hasToolButtons: true
    },

    create: function()
    {
        Firebug.Panel.create.apply(this, arguments);

        this.onChangeSelect = bind(this.onChangeSelect, this);

        var doc = Firebug.browser.document;
        var scripts = doc.getElementsByTagName("script");
        var selectNode = this.selectNode = createElement("select");

        for(var i=0, script; script=scripts[i]; i++)
        {
            var fileName = getFileName(script.src) || getFileName(doc.location.href);
            var option = createElement("option", {value:i});

            option.appendChild(Firebug.chrome.document.createTextNode(fileName));
            selectNode.appendChild(option);
        };

        this.toolButtonsNode.appendChild(selectNode);
    },

    initialize: function()
    {
        Firebug.Panel.initialize.apply(this, arguments);

        addEvent(this.selectNode, "change", this.onChangeSelect);

        this.selectSourceCode(this.sourceIndex);
    },

    detach: function(oldChrome, newChrome)
    {
        Firebug.Panel.detach.apply(this, arguments);

        var oldPanel = oldChrome.getPanel("Script");
        var index = oldPanel.sourceIndex;

        this.selectNode.selectedIndex = index;
        this.sourceIndex = index;
        this.lastSourceIndex = -1;
    },

    onChangeSelect: function(event)
    {
        event = event || window.event;
        var target = event.srcElement || event.currentTarget;
        var index = target.selectedIndex;

        this.renderSourceCode(index);
    },

    selectSourceCode: function(index)
    {
        this.selectNode.selectedIndex = index;
        this.renderSourceCode(index);
    },

    renderSourceCode: function(index)
    {
        if (this.lastSourceIndex != index)
        {
            var renderProcess = function renderProcess(src)
            {
                var html = [],
                    hl = 0,
                    s = [],
                    sl = 0;

                src = isIE && !isExternal ?
                        src+'\n' :  // IE put an extra line when reading source of local resources
                        '\n'+src;

                // find the number of lines of code
                var match = src.match(/\n/g);
                var lines=match ? match.length : 0;

                // render the line number divs
                for(var c=1, lines; c<=lines; c++)
                {
                    s[sl++] = '
';
                    s[sl++] = c;
                    s[sl++] = '
';
                }

                // render the full source code + line numbers html
                html[hl++] = '

';
                html[hl++] = escapeHTML(src);
                html[hl++] = '

';
                html = html.concat(s); // uses concat instead of string.join() to boost performance
                hl = html.length; // adjust the size index
                html[hl++] = '

';
                /**/

                updatePanel(html);
            };

            var updatePanel = function(html)
            {
                self.contentNode.innerHTML = html.join("");

                // IE needs this timeout, otherwise the panel won't scroll
                setTimeout(function(){
                    self.synchronizeUI();
                },0);
            };

            var onFailure = function()
            {
                renderProcess("Access to restricted URI denied");
            };

            var self = this;

            var doc = Firebug.browser.document;
            var script = doc.getElementsByTagName("script")[index];
            var url = getScriptURL(script);
            var isExternal = url && url != doc.location.href;

            try
            {
                if (isExternal)
                {
                    Ajax.request({url: url, onSuccess: renderProcess, onFailure: onFailure});
                }
                else
                {
                    var src = script.innerHTML;
                    renderProcess(src);
                }
            }
            catch(e)
            {
                renderProcess("Access to restricted URI denied");
            }

            this.sourceIndex = index;
            this.lastSourceIndex = index;
        }
    }
});

Firebug.registerPanel(ScriptPanel);

// ************************************************************************************************

var getScriptURL = function getScriptURL(script)
{
    var reFile = /([^\/\?#]+)(#.+)?$/;
    var rePath = /^(.*\/)/;
    var reProtocol = /^\w+:\/\//;
    var path = null;
    var doc = Firebug.browser.document;

    var file = reFile.exec(script.src);

    if (file)
    {
        var fileName = file[1];
        var fileOptions = file[2];

        // absolute path
        if (reProtocol.test(script.src)) {
            path = rePath.exec(script.src)[1];

        }
        // relative path
        else
        {
            var r = rePath.exec(script.src);
            var src = r ? r[1] : script.src;
            var backDir = /^((?:\.\.\/)+)(.*)/.exec(src);
            var reLastDir = /^(.*\/)[^\/]+\/$/;
            path = rePath.exec(doc.location.href)[1];

            // "../some/path"
            if (backDir)
            {
                var j = backDir[1].length/3;
                var p;
                while (j-- > 0)
                    path = reLastDir.exec(path)[1];

                path += backDir[2];
            }

            else if(src.indexOf("/") != -1)
            {
                // "./some/path"
                if(/^\.\/./.test(src))
                {
                    path += src.substring(2);
                }
                // "/some/path"
                else if(/^\/./.test(src))
                {
                    var domain = /^(\w+:\/\/[^\/]+)/.exec(path);
                    path = domain[1] + src;
                }
                // "some/path"
                else
                {
                    path += src;
                }
            }
        }
    }

    var m = path && path.match(/([^\/]+)\/$/) || null;

    if (path && m)
    {
        return path + fileName;
    }
};

var getFileName = function getFileName(path)
{
    if (!path) return "";

    var match = path && path.match(/[^\/]+(\?.*)?(#.*)?$/);

    return match && match[0] || path;
};

// ************************************************************************************************
}});<commit_msg>Fixed line count error, and improved renderSourceCode() function.<commit_after>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {
// ************************************************************************************************

// ************************************************************************************************
// Script Module

Firebug.Script = extend(Firebug.Module,
{
    getPanel: function()
    {
        return Firebug.chrome ? Firebug.chrome.getPanel("Script") : null;
    },

    selectSourceCode: function(index)
    {
        this.getPanel().selectSourceCode(index);
    }
});

Firebug.registerModule(Firebug.Script);

// ************************************************************************************************
// Script Panel

function ScriptPanel(){};

ScriptPanel.prototype = extend(Firebug.Panel,
{
    name: "Script",
    title: "Script",

    sourceIndex: 0,
    lastSourceIndex: -1,

    options: {
        hasToolButtons: true
    },

    create: function()
    {
        Firebug.Panel.create.apply(this, arguments);

        this.onChangeSelect = bind(this.onChangeSelect, this);

        var doc = Firebug.browser.document;
        var scripts = doc.getElementsByTagName("script");
        var selectNode = this.selectNode = createElement("select");

        for(var i=0, script; script=scripts[i]; i++)
        {
            var fileName = getFileName(script.src) || getFileName(doc.location.href);
            var option = createElement("option", {value:i});

            option.appendChild(Firebug.chrome.document.createTextNode(fileName));
            selectNode.appendChild(option);
        };

        this.toolButtonsNode.appendChild(selectNode);
    },

    initialize: function()
    {
        Firebug.Panel.initialize.apply(this, arguments);

        addEvent(this.selectNode, "change", this.onChangeSelect);

        this.selectSourceCode(this.sourceIndex);
    },

    detach: function(oldChrome, newChrome)
    {
        Firebug.Panel.detach.apply(this, arguments);

        var oldPanel = oldChrome.getPanel("Script");
        var index = oldPanel.sourceIndex;

        this.selectNode.selectedIndex = index;
        this.sourceIndex = index;
        this.lastSourceIndex = -1;
    },

    onChangeSelect: function(event)
    {
        event = event || window.event;
        var target = event.srcElement || event.currentTarget;
        var index = target.selectedIndex;

        this.renderSourceCode(index);
    },

    selectSourceCode: function(index)
    {
        this.selectNode.selectedIndex = index;
        this.renderSourceCode(index);
    },

    renderSourceCode: function(index)
    {
        if (this.lastSourceIndex != index)
        {
            var renderProcess = function renderProcess(src)
            {
                var html = [],
                    hl = 0;

                src = isIE && !isExternal ?
                        src+'\n' :  // IE put an extra line when reading source of local resources
                        '\n'+src;

                // find the number of lines of code
                src = src.replace(/\n\r|\r\n/g, "\n");
                var match = src.match(/[\n]/g);
                var lines=match ? match.length : 0;

                // render the full source code + line numbers html
                html[hl++] = '

';
                html[hl++] = escapeHTML(src);
                html[hl++] = '

';

                // render the line number divs
                for(var l=1, lines; l<=lines; l++)
                {
                    html[hl++] = '
';
                    html[hl++] = l;
                    html[hl++] = '
';
                }

                html[hl++] = '

';

                updatePanel(html);
            };

            var updatePanel = function(html)
            {
                self.contentNode.innerHTML = html.join("");

                // IE needs this timeout, otherwise the panel won't scroll
                setTimeout(function(){
                    self.synchronizeUI();
                },0);
            };

            var onFailure = function()
            {
                renderProcess("Access to restricted URI denied");
            };

            var self = this;

            var doc = Firebug.browser.document;
            var script = doc.getElementsByTagName("script")[index];
            var url = getScriptURL(script);
            var isExternal = url && url != doc.location.href;

            try
            {
                if (isExternal)
                {
                    Ajax.request({url: url, onSuccess: renderProcess, onFailure: onFailure});
                }
                else
                {
                    var src = script.innerHTML;
                    renderProcess(src);
                }
            }
            catch(e)
            {
                renderProcess("Access to restricted URI denied");
            }

            this.sourceIndex = index;
            this.lastSourceIndex = index;
        }
    }
});

Firebug.registerPanel(ScriptPanel);

// ************************************************************************************************

var getScriptURL = function getScriptURL(script)
{
    var reFile = /([^\/\?#]+)(#.+)?$/;
    var rePath = /^(.*\/)/;
    var reProtocol = /^\w+:\/\//;
    var path = null;
    var doc = Firebug.browser.document;

    var file = reFile.exec(script.src);

    if (file)
    {
        var fileName = file[1];
        var fileOptions = file[2];

        // absolute path
        if (reProtocol.test(script.src)) {
            path = rePath.exec(script.src)[1];

        }
        // relative path
        else
        {
            var r = rePath.exec(script.src);
            var src = r ? r[1] : script.src;
            var backDir = /^((?:\.\.\/)+)(.*)/.exec(src);
            var reLastDir = /^(.*\/)[^\/]+\/$/;
            path = rePath.exec(doc.location.href)[1];

            // "../some/path"
            if (backDir)
            {
                var j = backDir[1].length/3;
                var p;
                while (j-- > 0)
                    path = reLastDir.exec(path)[1];

                path += backDir[2];
            }

            else if(src.indexOf("/") != -1)
            {
                // "./some/path"
                if(/^\.\/./.test(src))
                {
                    path += src.substring(2);
                }
                // "/some/path"
                else if(/^\/./.test(src))
                {
                    var domain = /^(\w+:\/\/[^\/]+)/.exec(path);
                    path = domain[1] + src;
                }
                // "some/path"
                else
                {
                    path += src;
                }
            }
        }
    }

    var m = path && path.match(/([^\/]+)\/$/) || null;

    if (path && m)
    {
        return path + fileName;
    }
};

var getFileName = function getFileName(path)
{
    if (!path) return "";

    var match = path && path.match(/[^\/]+(\?.*)?(#.*)?$/);

    return match && match[0] || path;
};

// ************************************************************************************************
}});<|endoftext|>


<commit_before>Type.registerNamespace("ExoWeb.UI");

(function() {

	var undefined;

	var log = ExoWeb.trace.log;

	///////////////////////////////////////////////////////////////////////////////
	///
	/// In addition to defining template markup, also defines rules that are used
	/// to determine if it should be chosen as the template for a given element
	/// based on a CSS selector as well as a javascript filter that is evaluated
	/// against the element in question.
	///
	///
	/// <example>
	///		<div sys:attach="template" template:for="table.inputform tr" template:if="<some condition>">

	/// </example>
	Template = function(element) {
		Template.initializeBase(this, [element]);
	}

	Template.prototype = {
		// CSS Selectors
		///////////////////////////////////////////////////////////////////////////
		get_for: function() {
			return this._for;
		},
		set_for: function(value) {
			this._for = value;
		},
		matches: function(e) {
			return $(e).is(this._for);
		},

		// Arbitrary JavaScript
		///////////////////////////////////////////////////////////////////////////
		get_if: function() {
			return this._if;
		},
		set_if: function(value) {
			this._if = value;
		},
		satisfies: function(e) {
			// return true by default if no filter
			var result = true;

			if (this._if) {
				var func = null;

				try {
					// turn arbitrary javascript code into function
					func = new Function("$data", "$container", "return " + this._if + ";");
				}
				catch (e) {
					throw ("Statement \"" + this._if + "\" causes the following error: " + e);
				}

				if (func) {
					try {
						result = func.apply(this, [e.control.get_data(), e]);
					}
					catch (e) {
						result = false;
					}
				}
			}

			return result;
		},

		test: function(e) {
			// determines if the given element matches this template
			return this.matches(e) && this.satisfies(e);
		},

		initialize: function() {
			Template.callBaseMethod(this, "initialize");

			// add a class that can be used to search for templates
			// and make sure that the template element is hidden
			$(this.get_element()).addClass("vc3-template").hide();
		}
	}

	///
	/// Finds the first field template with a selector and filter that
	/// match the given element and returns the template.
	///
	Template.find = function(element) {
		var templates = $(".vc3-template");
		for (var t = 0; t < templates.length; t++) {
			var tmpl = templates[t];
			if (Template.isInstanceOfType(tmpl.control) && tmpl.control.test(element))
				return tmpl;
		}

		return null;
	}

	ExoWeb.UI.Template = Template;
	Template.registerClass("ExoWeb.UI.Template", Sys.UI.Control);

	// TODO: rename content

	///////////////////////////////////////////////////////////////////////////////
	///
	/// Finds its matching template and renders using the provided data as the
	/// binding context.  It can be used as a "field control", using part of the
	/// context data to select the appropriate control template.  Another common
	/// usage would be to select the appropriate template for a portion of the UI,
	/// as in the example where an objects meta type determines how it is
	/// displayed in the UI.
	///
	///
	/// <example>
	///

	/// </example>
	Content = function(element) {
		Content.initializeBase(this, [element]);
	}

	Content.prototype = {
		get_template: function() {
			if (!this._template) {
				var element = this.get_element();
				this._template = Template.find(element);

				if (!this._template) {
					throw ("This content region does not match any available templates.");
				}
			}

			if (!Sys.UI.Template.isInstanceOfType(this._template))
				this._template = new Sys.UI.Template(this._template);

			return this._template;
		},
		get_data: function() {
			return this._data;
		},
		set_data: function(value) {
			this._data = value;
			this.render();
		},
		get_context: function() {
			return this._context;
		},
		set_context: function(value) {
			this._context = value;
		},
		render: function() {
			if (this._data && this._initialized) {
				var tmpl = this.get_template();

				// get custom classes from template
				var classes = $.trim($(tmpl.get_element()).attr("class").replace("vc3-template", "").replace("sys-template", ""));

				this._context = tmpl.instantiateIn(this.get_element(), null, this.get_data());

				// copy custom classes from template to content control
				$(this.get_element()).addClass(classes);

				// necessary in order to render components found within the template (like a nested dataview)
				this._context.initializeComponents();
			}
		},
		initialize: function() {
			Content.callBaseMethod(this, "initialize");

			// TODO: include meta info about field?
			this._element._exowebcontent = {};

			this._initialized = true;

			this.render();
		}
	}

	ExoWeb.UI.Content = Content;
	Content.registerClass("ExoWeb.UI.Content", Sys.UI.Control);

	function getTemplateSubContainer(childElement) {
		var element = childElement;

		// find the first parent that has an attached ASP.NET Ajax dataview or ExoWeb content control
		while (element.parentNode && !element.parentNode._msajaxtemplate && !element.parentNode._exowebcontent)
			element = element.parentNode;

		// containing template was not found
		if (element.parentNode && (element.parentNode._msajaxtemplate || element.parentNode._exowebcontent))
			return element;

		return null;
	}

	function getParentContextData(elementOrControl, index, level) {

		if (elementOrControl.control instanceof Sys.UI.DataView)
			elementOrControl = elementOrControl.control;
		else if (elementOrControl instanceof Sys.UI.Template)
			elementOrControl = elementOrControl.get_element();

		if (!level)
			level = 1;

		var container;
		var subcontainer;
		for (var i = 0; i < level; i++) {
			// if we are starting out with a dataview then look at the parent context rather than walking
			// up the dom (since the element will probably not be present in the dom)
			if (!container && elementOrControl instanceof Sys.UI.DataView && elementOrControl._parentContext) {
				context = elementOrControl._parentContext;
				container = context.containerElement;
			}
			else {
				subcontainer = getTemplateSubContainer(container || elementOrControl);

				if (!subcontainer)
					throw Error.invalidOperation("Not within a container template.");

				container = subcontainer.parentNode;
			}
		}

		var data = null;

		if (container.control instanceof ExoWeb.UI.Content) {
			// content control doesn't currenlty support lists, so return the data object
			return container.control.get_data();
		}
		else if (container.control instanceof Sys.UI.DataView) {
			var containerContexts = container.control.get_contexts();
			var containerData = container.control.get_data();

			// ensure an array for conformity
			if (!(containerData instanceof Array))
				containerData = [containerData];

			if (containerContexts) {
				// if there is only one context in the array then the index must be zero
				if (containerContexts.length == 1)
					index = 0;

				if (index != undefined && index.constructor == Number) {
					if (index >= containerContexts.length)
						log("ui", "invalid index");
					else {
						var indexedContext = containerContexts[index];
						var indexedData = containerData[index];
						data = (indexedContext) ? indexedContext.dataItem : indexedData;
					}
				}
				else {
					// try to find the right context based on the element's position in the dom
					for (var i = 0, l = containerContexts.length; i < l; i++) {
						var childContext = containerContexts[i];
						if (childContext && childContext.containerElement === container && Sys._indexOf(childContext.nodes, subcontainer) > -1)
							data = childContext.dataItem;
					}
				}
			}
		}

		return data;
	}

	window.$parentContextData = getParentContextData;

	// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
	// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager
	// that this is the end of the script.
	if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

})();<commit_msg>add toggle control and islast function<commit_after>Type.registerNamespace("ExoWeb.UI");

(function() {

	var undefined;

	var log = ExoWeb.trace.log;

	///////////////////////////////////////////////////////////////////////////////
	Toggle = function(element) {
		Toggle.initializeBase(this, [element]);
	}

	Toggle.prototype = {
		set_action: function Toggle$set_action(value) {
			this._action = value;
		},
		get_action: function Toggle$get_action() {
			return this._action;
		},
		set_on: function Toggle$set_on(value) {
			this._on = value;
		},
		get_on: function Toggle$get_on() {
			return this._on;
		},
		set_when: function Toggle$set_when(value) {
			this._when = value;
		},
		get_when: function Toggle$get_when() {
			return this._when;
		},
		set_source: function Toggle$set_source(value) {
			this._source = value;
		},
		get_source: function Toggle$get_source() {
			return this._source;
		},
		get_value: function Toggle$get_value() {
			var getter = this._source["get_" + this._on];
			if (getter)
				return getter.call(this._source);
			else
				return this._source[this._on];
		},
		execute: function Toggle$execute() {
			var val = this.get_value();
			if (val == this._when) {
				if (this._action == "hide")
					$(this.get_element()).hide();
				else
					$(this.get_element()).show();
			}
			else {
				if (this._action == "hide")
					$(this.get_element()).show();
				else
					$(this.get_element()).hide();
			}
		},
		initialize: function Toggle$initialize() {
			Toggle.callBaseMethod(this, "initialize");

			if (!this._source)
				this._source = getParentContextData(this._element);

			this.execute();

			var _this = this;
			Sys.Observer.addSpecificPropertyChanged(this._source, this._on, function() {
				_this.execute();
			});
		}
	}

	ExoWeb.UI.Toggle = Toggle;
	Toggle.registerClass("ExoWeb.UI.Toggle", Sys.UI.Control);

	///////////////////////////////////////////////////////////////////////////////
	///
	/// In addition to defining template markup, also defines rules that are used
	/// to determine if it should be chosen as the template for a given element
	/// based on a CSS selector as well as a javascript filter that is evaluated
	/// against the element in question.
	///
	///
	/// <example>
	///		<div sys:attach="template" template:for="table.inputform tr" template:if="<some condition>">

	/// </example>
	Template = function(element) {
		Template.initializeBase(this, [element]);
	}

	Template.prototype = {
		// CSS Selectors
		///////////////////////////////////////////////////////////////////////////
		get_for: function() {
			return this._for;
		},
		set_for: function(value) {
			this._for = value;
		},
		matches: function(e) {
			return $(e).is(this._for);
		},

		// Arbitrary JavaScript
		///////////////////////////////////////////////////////////////////////////
		get_if: function() {
			return this._if;
		},
		set_if: function(value) {
			this._if = value;
		},
		satisfies: function(e) {
			// return true by default if no filter
			var result = true;

			if (this._if) {
				var func = null;

				try {
					// turn arbitrary javascript code into function
					func = new Function("$data", "$container", "return " + this._if + ";");
				}
				catch (e) {
					throw ("Statement \"" + this._if + "\" causes the following error: " + e);
				}

				if (func) {
					try {
						result = func.apply(this, [e.control.get_data(), e]);
					}
					catch (e) {
						result = false;
					}
				}
			}

			return result;
		},

		test: function(e) {
			// determines if the given element matches this template
			return this.matches(e) && this.satisfies(e);
		},

		initialize: function() {
			Template.callBaseMethod(this, "initialize");

			// add a class that can be used to search for templates
			// and make sure that the template element is hidden
			$(this.get_element()).addClass("vc3-template").hide();
		}
	}

	///
	/// Finds the first field template with a selector and filter that
	/// match the given element and returns the template.
	///
	Template.find = function(element) {
		var templates = $(".vc3-template");
		for (var t = 0; t < templates.length; t++) {
			var tmpl = templates[t];
			if (Template.isInstanceOfType(tmpl.control) && tmpl.control.test(element))
				return tmpl;
		}

		return null;
	}

	ExoWeb.UI.Template = Template;
	Template.registerClass("ExoWeb.UI.Template", Sys.UI.Control);

	// TODO: rename content

	///////////////////////////////////////////////////////////////////////////////
	///
	/// Finds its matching template and renders using the provided data as the
	/// binding context.  It can be used as a "field control", using part of the
	/// context data to select the appropriate control template.  Another common
	/// usage would be to select the appropriate template for a portion of the UI,
	/// as in the example where an objects meta type determines how it is
	/// displayed in the UI.
	///
	///
	/// <example>
	///

	/// </example>
	Content = function(element) {
		Content.initializeBase(this, [element]);
	}

	Content.prototype = {
		get_template: function() {
			if (!this._template) {
				var element = this.get_element();
				this._template = Template.find(element);

				if (!this._template) {
					throw ("This content region does not match any available templates.");
				}
			}

			if (!Sys.UI.Template.isInstanceOfType(this._template))
				this._template = new Sys.UI.Template(this._template);

			return this._template;
		},
		get_data: function() {
			return this._data;
		},
		set_data: function(value) {
			this._data = value;
			this.render();
		},
		get_context: function() {
			return this._context;
		},
		set_context: function(value) {
			this._context = value;
		},
		render: function() {
			if (this._data && this._initialized) {
				var tmpl = this.get_template();

				// get custom classes from template
				var classes = $.trim($(tmpl.get_element()).attr("class").replace("vc3-template", "").replace("sys-template", ""));

				this._context = tmpl.instantiateIn(this.get_element(), null, this.get_data());

				// copy custom classes from template to content control
				$(this.get_element()).addClass(classes);

				// necessary in order to render components found within the template (like a nested dataview)
				this._context.initializeComponents();
			}
		},
		initialize: function() {
			Content.callBaseMethod(this, "initialize");

			// TODO: include meta info about field?
			this._element._exowebcontent = {};

			this._initialized = true;

			this.render();
		}
	}

	ExoWeb.UI.Content = Content;
	Content.registerClass("ExoWeb.UI.Content", Sys.UI.Control);

	function getTemplateSubContainer(childElement) {
		var element = childElement;

		// find the first parent that has an attached ASP.NET Ajax dataview or ExoWeb content control
		while (element.parentNode && !element.parentNode._msajaxtemplate && !element.parentNode._exowebcontent)
			element = element.parentNode;

		// containing template was not found
		if (element.parentNode && (element.parentNode._msajaxtemplate || element.parentNode._exowebcontent))
			return element;

		return null;
	}

	function getParentContextData(elementOrControl, index, level) {

		if (elementOrControl.control instanceof Sys.UI.DataView)
			elementOrControl = elementOrControl.control;
		else if (elementOrControl instanceof Sys.UI.Template)
			elementOrControl = elementOrControl.get_element();

		if (!level)
			level = 1;

		var container;
		var subcontainer;
		for (var i = 0; i < level; i++) {
			// if we are starting out with a dataview then look at the parent context rather than walking
			// up the dom (since the element will probably not be present in the dom)
			if (!container && elementOrControl instanceof Sys.UI.DataView && elementOrControl._parentContext) {
				context = elementOrControl._parentContext;
				container = context.containerElement;
			}
			else {
				subcontainer = getTemplateSubContainer(container || elementOrControl);

				if (!subcontainer)
					throw Error.invalidOperation("Not within a container template.");

				container = subcontainer.parentNode;
			}
		}

		var data = null;

		if (container.control instanceof ExoWeb.UI.Content) {
			// content control doesn't currenlty support lists, so return the data object
			return container.control.get_data();
		}
		else if (container.control instanceof Sys.UI.DataView) {
			var containerContexts = container.control.get_contexts();
			var containerData = container.control.get_data();

			// ensure an array for conformity
			if (!(containerData instanceof Array))
				containerData = [containerData];

			if (containerContexts) {
				// if there is only one context in the array then the index must be zero
				if (containerContexts.length == 1)
					index = 0;

				if (index != undefined && index.constructor == Number) {
					if (index >= containerContexts.length)
						log("ui", "invalid index");
					else {
						var indexedContext = containerContexts[index];
						var indexedData = containerData[index];
						data = (indexedContext) ? indexedContext.dataItem : indexedData;
					}
				}
				else {
					// try to find the right context based on the element's position in the dom
					for (var i = 0, l = containerContexts.length; i < l; i++) {
						var childContext = containerContexts[i];
						if (childContext && childContext.containerElement === container && Sys._indexOf(childContext.nodes, subcontainer) > -1)
							data = childContext.dataItem;
					}
				}
			}
		}

		return data;
	}

	window.$parentContextData = getParentContextData;

	function getIsLast(control, index) {
		var len = control.get_element().control.get_contexts().length;
		return index == len - 1;
	}

	window.$isLast = getIsLast;

	// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
	// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager
	// that this is the end of the script.
	if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

})();<|endoftext|>


<commit_before>define(['views/form',
    'tpl!templates/login.html',
    'jquery',
    'backbone',

    'jquery-ui',
    'backbone-validation',

    ], function(FormView,
        template, $, Backbone) {

    var Login = Backbone.Model.extend({
        url: '/authenticate',
        validation: {
            login: {
                required: true,
            },

            password: {
                required: true
            },
        }
    })

    return FormView.extend({
        template: template,

        createModel: function() {
            this.model = new Login()
        },

        onRender: function() {
            this.checkExistingSession()
        },

        // Hack for CAS SSO
        checkExistingSession: function() {
            var self = this
            var fr = $('iframe')
            fr.load(function() {
                var content = fr.contents().text()
                if (content) {
                    try {
                        var response = JSON.parse(content)
                        if ('jwt' in response) {
                            app.alert({ message: 'Found a valid session, auto-logging you in' })
                            self.$el.find('form').addClass('loading')
                            setTimeout(function() {
                                self.setToken(response)
                            }, 2000)
                        }

                        if ('error' in response) {
                            self.redirect()

                        }
                    } catch(err) {
                        // Not valid JSON
                        console.log('catching error')
                        self.redirect()
                    }
                }
            })
            fr.attr('src',app.apiurl+'/authenticate/check')
        },

        redirect: function() {
            if (app.options.get('authentication_type') == 'cas')
                window.location.href='https://'+app.options.get('cas_url')+'/cas/login?service='+encodeURIComponent(window.location.href)
        },

        onShow: function() {
            if (app.token) {
                console.log('invald token alert')
                app.alert({ message: 'Your session has expired, please log in again', persist: 'login' })
            }
        },

        success: function(model, response, options) {
            this.setToken(response)
        },

        setToken: function(response) {
            app.token = response.jwt

            sessionStorage.setItem('token', app.token)
            this.$el.find('form').addClass('loading')
            app.getuser({
                callback: function() {
                    var url = window.location.pathname.substr(Backbone.history.root.length);
                    if (url) {
                        app.navigate('/', { trigger: false });
                        app.navigate(url, { trigger: true });
                    } else app.trigger('go:home')
                }
            })
        },

        failure: function(model, response, options) {
            console.log('failure from login')
            app.alert({ message: 'We couldnt log you in, maybe your password or username were incorrect?'})
        },
    })

})<commit_msg>dont endlessly loop if cas fails<commit_after>define(['views/form',
    'tpl!templates/login.html',
    'jquery',
    'backbone',

    'jquery-ui',
    'backbone-validation',

    ], function(FormView,
        template, $, Backbone) {

    var Login = Backbone.Model.extend({
        url: '/authenticate',
        validation: {
            login: {
                required: true,
            },

            password: {
                required: true
            },
        }
    })

    return FormView.extend({
        template: template,

        createModel: function() {
            this.model = new Login()
        },

        onRender: function() {
            this.checkExistingSession()
        },

        // Hack for CAS SSO
        checkExistingSession: function() {
            var self = this
            var fr = $('iframe')
            fr.load(function() {
                var content = fr.contents().text()
                if (content) {
                    try {
                        var response = JSON.parse(content)
                        if ('jwt' in response) {
                            app.alert({ message: 'Found a valid session, auto-logging you in' })
                            self.$el.find('form').addClass('loading')
                            setTimeout(function() {
                                self.setToken(response)
                            }, 2000)
                        }

                        if ('error' in response) {
                            self.redirect()

                        }
                    } catch(err) {
                        // Not valid JSON
                        console.log('catching error')
                        self.redirect()
                    }
                }
            })
            fr.attr('src',app.apiurl+'/authenticate/check')
        },

        redirect: function() {
            if (app.options.get('authentication_type') == 'cas' && app.options.get('cas_sso') == true && location.href.indexOf('?ticket=') == -1)
                window.location.href='https://'+app.options.get('cas_url')+'/cas/login?service='+encodeURIComponent(window.location.href)
        },

        onShow: function() {
            if (app.token) {
                console.log('invald token alert')
                app.alert({ message: 'Your session has expired, please log in again', persist: 'login' })
            }
        },

        success: function(model, response, options) {
            this.setToken(response)
        },

        setToken: function(response) {
            app.token = response.jwt

            sessionStorage.setItem('token', app.token)
            this.$el.find('form').addClass('loading')
            app.getuser({
                callback: function() {
                    var url = window.location.pathname.substr(Backbone.history.root.length);
                    if (url) {
                        app.navigate('/', { trigger: false });
                        app.navigate(url, { trigger: true });
                    } else app.trigger('go:home')
                }
            })
        },

        failure: function(model, response, options) {
            console.log('failure from login')
            app.alert({ message: 'We couldnt log you in, maybe your password or username were incorrect?'})
        },
    })

})<|endoftext|>


<commit_before>/*global $:false */
/*global jQuery:false */
/*global Backbone:false */
/*global jRespond:false */
/*global window:false */
/*global console:false */
/*global _:false */
var gc2table = (function () {
    "use strict";
    var host, js, isLoaded, object, init,
        scriptsLoaded = false,
        scriptSource = (function (scripts) {
            scripts = document.getElementsByTagName('script');
            var script = scripts[scripts.length - 1];
            if (script.getAttribute.length !== undefined) {
                return script.src;
            }
            return script.getAttribute('src', -1);
        }());

    // Try to set host from script if not set already
    if (typeof window.geocloud_host === "undefined") {
        host = (scriptSource.charAt(0) === "/") ? "" : scriptSource.split("/")[0] + "//" + scriptSource.split("/")[2];
    } else {
        host = window.geocloud_host;
    }

    if (typeof $ === "undefined") {
        js = document.createElement("script");
        js.type = "text/javascript";
        js.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js";
        document.getElementsByTagName("head")[0].appendChild(js);
    }
    (function pollForjQuery() {
        if (typeof jQuery !== "undefined") {
            if (typeof jQuery().typeahead === "undefined") {
                $.getScript(host + "/js/typeahead.js-0.10.5/dist/typeahead.bundle.js");
            }
            if (typeof jQuery().bootstrapTable === "undefined") {
                $.getScript(host + "/js/bootstrap-table/bootstrap-table.js");
            }
            if (typeof _ === "undefined") {
                $.getScript(host + "/js/underscore/underscore-min.js");
            }
            if (typeof jRespond === "undefined") {
                $.getScript(host + "/js/div/jRespond.js");
            }
            (function pollForDependencies() {
                if (typeof jQuery().typeahead !== "undefined" &&
                    typeof jQuery().bootstrapTable !== "undefined" &&
                    typeof jQuery().bootstrapTable.locales !== "undefined" &&
                    typeof _ !== 'undefined' &&
                    typeof jRespond !== "undefined") {
                    if (typeof jQuery().bootstrapTable.locales['da-DK'] === "undefined") {
                        $.getScript(host + "/js/bootstrap-table/bootstrap-table-locale-all.js");
                    }
                    if (typeof jQuery().bootstrapTable.defaults.filterControl === "undefined") {
                        $.getScript(host + "/js/bootstrap-table/extensions/filter-control/bootstrap-table-filter-control.js");
                    }
                    if (typeof jQuery().bootstrapTable.defaults.exportDataType === "undefined") {
                        $.getScript(host + "/js/bootstrap-table/extensions/export/bootstrap-table-export.min.js");
                    }
                    if (typeof jQuery().tableExport === "undefined") {
                        $.getScript(host + "/js/tableExport.jquery.plugin/tableExport.min.js");
                    }
                    if (typeof Backbone === "undefined") {
                        $.getScript("//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js");
                    }
                    (function pollForDependants() {
                        if (typeof jQuery().bootstrapTable.defaults.filterControl !== "undefined" &&
                            typeof jQuery().bootstrapTable.defaults.exportDataType !== "undefined" &&
                            typeof jQuery().tableExport !== "undefined" &&
                            typeof jQuery().bootstrapTable.locales['da-DK'] !== "undefined" &&
                            typeof Backbone !== "undefined") {
                            scriptsLoaded = true;
                        } else {
                            setTimeout(pollForDependants, 10);
                        }
                    }());
                } else {
                    setTimeout(pollForDependencies, 10);
                }
            }());

        } else {
            setTimeout(pollForjQuery, 10);
        }
    }());

    isLoaded = function () {
        return scriptsLoaded;
    };
    object = {};
    init = function (conf) {
        var defaults = {
                el: "#table",
                autoUpdate: false,
                height: 300,
                setSelectedStyle: true,
                openPopUp: false,
                setViewOnSelect: true,
                responsive: true,
                autoPan: false,
                locale: 'en-US',
                callCustomOnload: true,
                popupHtml: null,
                ns: "",
                template: null,
                usingCarto: false,
                onSelect: function () {
                },
                onMouseOver: function () {
                },
                styleSelected: {
                    weight: 5,
                    color: '#666',
                    dashArray: '',
                    fillOpacity: 0.7
                }
            }, prop,
            uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        if (conf) {
            for (prop in conf) {
                defaults[prop] = conf[prop];
            }
        }
        var data,
            m = defaults.geocloud2,
            store = defaults.store,
            cm = defaults.cm,
            autoUpdate = defaults.autoUpdate,
            height = defaults.height,
            tableBodyHeight = defaults.tableBodyHeight,
            styleSelected = defaults.styleSelected,
            el = defaults.el, click, loadDataInTable, moveEndOff, moveEndOn,
            setSelectedStyle = defaults.setSelectedStyle,
            setViewOnSelect = defaults.setViewOnSelect,
            onSelect = defaults.onSelect,
            onMouseOver = defaults.onMouseOver,
            openPopUp = defaults.openPopUp,
            autoPan = defaults.autoPan,
            responsive = defaults.responsive,
            callCustomOnload = defaults.callCustomOnload,
            locale = defaults.locale,
            popupHtml = defaults.popupHtml,
            ns = defaults.ns,
            template = defaults.template,
            usingCartodb = defaults.usingCartodb;

        $(el).parent("div").addClass("gc2map");

        (function poll() {
            if (scriptsLoaded) {
                var originalLayers, filters, filterControls;
                _.extend(object, Backbone.Events);
                object.on("selected" + "_" + uid, function (id) {

                    $(el + ' tr').removeClass("selected");
                    $.each(store.layer._layers, function (i, v) {
                        try {
                            store.layer.resetStyle(v);
                        } catch (e) {
                        }
                    });
                    var row = $('*[data-uniqueid="' + id + '"]');
                    row.addClass("selected");
                    if (setSelectedStyle) {
                        m.map._layers[id].setStyle(styleSelected);
                    }
                    if (openPopUp) {
                        var str = "
", renderedText;
                        $.each(cm, function (i, v) {
                            if (typeof v.showInPopup === "undefined" || (typeof v.showInPopup === "boolean" && v.showInPopup === true)) {
                                str = str + "
" + v.header + "	" + m.map._layers[id].feature.properties[v.dataIndex] + "
";
                            }
                        });
                        str = str + "
";

                        if (template) {
                            renderedText = Mustache.render(template, m.map._layers[id].feature.properties);
                            if (usingCartodb) {
                                renderedText = $.parseHTML(renderedText)[0].children[1].innerHTML
                            }
                        }

                        m.map._layers[id].bindPopup(renderedText || str, {
                            className: "custom-popup",
                            autoPan: autoPan,
                            closeButton: true
                        }).openPopup();

                        object.trigger("openpopup" + "_" + uid, m.map._layers[id]);
                    }

                });
                click = function (e) {
                    var row = $('*[data-uniqueid="' + e.target._leaflet_id + '"]');
                    $(ns + " .fixed-table-body").animate({
                        scrollTop: $(ns + " .fixed-table-body").scrollTop() + (row.offset().top - $(ns + " .fixed-table-body").offset().top)
                    }, 300);
                    object.trigger("selected" + "_" + uid, e.target._leaflet_id);
                };
                $(el).append("

");
                $.each(cm, function (i, v) {
                    $(el + ' thead tr').append("" + v.header + "	");
                });

                var filterMap =
                    _.debounce(function () {
                        var visibleRows = [];
                        $.each(store.layer._layers, function (i, v) {
                            m.map.removeLayer(v);
                        });
                        $.each(originalLayers, function (i, v) {
                            m.map.addLayer(v);
                        });
                        filters = {};
                        filterControls = {};
                        $.each(cm, function (i, v) {
                            if (v.filterControl) {
                                filters[v.dataIndex] = $(".bootstrap-table-filter-control-" + v.dataIndex).val();
                                filterControls[v.dataIndex] = v.filterControl;
                            }
                        });
                        $.each($(el + " tbody").children(), function (x, y) {
                            visibleRows.push($(y).attr("data-uniqueid"));
                        });
                        $.each(store.layer._layers, function (i, v) {
                            if (visibleRows.indexOf(v._leaflet_id + "") === -1) {
                                m.map.removeLayer(v);
                            }
                        });
                        bindEvent();
                    }, 500);

                var bindEvent = function (e) {
                    setTimeout(function () {

                        $(el + ' > tbody > tr').on("click", function (e) {
                            var id = $(this).data('uniqueid');
                            object.trigger("selected" + "_" + uid, id);
                            var layer = m.map._layers[id];
                            setTimeout(function () {
                                if (setViewOnSelect) {
                                    m.map.fitBounds(layer.getBounds());
                                }
                            }, 100);
                            onSelect(id, layer);
                        });

                        $(el + ' > tbody > tr').on("mouseover", function (e) {
                            var id = $(this).data('uniqueid');
                            object.trigger("selected" + "_" + uid, id);
                            var layer = m.map._layers[id];
                            onMouseOver(id, layer);
                        });

                    }, 100);
                };
                $(el).bootstrapTable({
                    uniqueId: "_id",
                    height: height,
                    locale: locale,
                    onToggle: bindEvent,
                    onSort: bindEvent,
                    onColumnSwitch: bindEvent,
                    onColumnSearch: filterMap
                });

                // Define a callback for when the SQL returns
                var customOnLoad = store.onLoad;
                store.onLoad = function () {
                    loadDataInTable();
                };
                loadDataInTable = function (doNotCallCustomOnload) {
                    data = [];
                    $.each(store.layer._layers, function (i, v) {
                        v.feature.properties._id = i;
                        $.each(v.feature.properties, function (n, m) {
                            $.each(cm, function (j, k) {
                                if (k.dataIndex === n && ((typeof k.link === "boolean" && k.link === true) || (typeof k.link === "string"))) {
                                    v.feature.properties[n] = "" + (typeof k.link === "string" ? k.link : "Link") + "";
                                }

                            });
                        });
                        data.push(v.feature.properties);
                        v.on({
                            click: click
                        });

                    });

                    originalLayers = jQuery.extend(true, {}, store.layer._layers);

                    $(el).bootstrapTable("load", data);

                    bindEvent();

                    if (callCustomOnload && !doNotCallCustomOnload) {
                        customOnLoad(store);
                    }

                    $(".fixed-table-body").css("overflow", "auto");
                    $(".fixed-table-body").css("max-height", tableBodyHeight + "px");
                    $(".fixed-table-body").css("height", tableBodyHeight + "px");

                };

                var moveEndEvent = function () {
                    store.reset();
                    store.load();
                };

                moveEndOff = function () {
                    m.map.off("moveend", moveEndEvent);
                };

                moveEndOn = function () {
                    m.on("moveend", moveEndEvent);
                };

                if (autoUpdate) {
                    m.on("moveend", moveEndEvent);
                }

                var jRes = jRespond([
                    {
                        label: 'handheld',
                        enter: 0,
                        exit: 400
                    },
                    {
                        label: 'desktop',
                        enter: 401,
                        exit: 100000
                    }
                ]);
                if (responsive) {
                    jRes.addFunc({
                        breakpoint: ['handheld'],
                        enter: function () {
                            $(el).bootstrapTable('toggleView');
                        },
                        exit: function () {
                            $(el).bootstrapTable('toggleView');
                        }
                    });
                    jRes.addFunc({
                        breakpoint: ['desktop'],
                        enter: function () {
                        },
                        exit: function () {
                        }
                    });
                }
            } else {
                setTimeout(poll, 20);
            }
        }());
        return {
            loadDataInTable: loadDataInTable,
            object: object,
            uid: uid,
            store: store,
            moveEndOff: moveEndOff,
            moveEndOn: moveEndOn
        };
    };
    return {
        init: init,
        isLoaded: isLoaded
    };
}());
<commit_msg>Removed mouseover<commit_after>/*global $:false */
/*global jQuery:false */
/*global Backbone:false */
/*global jRespond:false */
/*global window:false */
/*global console:false */
/*global _:false */
var gc2table = (function () {
    "use strict";
    var host, js, isLoaded, object, init,
        scriptsLoaded = false,
        scriptSource = (function (scripts) {
            scripts = document.getElementsByTagName('script');
            var script = scripts[scripts.length - 1];
            if (script.getAttribute.length !== undefined) {
                return script.src;
            }
            return script.getAttribute('src', -1);
        }());

    // Try to set host from script if not set already
    if (typeof window.geocloud_host === "undefined") {
        host = (scriptSource.charAt(0) === "/") ? "" : scriptSource.split("/")[0] + "//" + scriptSource.split("/")[2];
    } else {
        host = window.geocloud_host;
    }

    if (typeof $ === "undefined") {
        js = document.createElement("script");
        js.type = "text/javascript";
        js.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js";
        document.getElementsByTagName("head")[0].appendChild(js);
    }
    (function pollForjQuery() {
        if (typeof jQuery !== "undefined") {
            if (typeof jQuery().typeahead === "undefined") {
                $.getScript(host + "/js/typeahead.js-0.10.5/dist/typeahead.bundle.js");
            }
            if (typeof jQuery().bootstrapTable === "undefined") {
                $.getScript(host + "/js/bootstrap-table/bootstrap-table.js");
            }
            if (typeof _ === "undefined") {
                $.getScript(host + "/js/underscore/underscore-min.js");
            }
            if (typeof jRespond === "undefined") {
                $.getScript(host + "/js/div/jRespond.js");
            }
            (function pollForDependencies() {
                if (typeof jQuery().typeahead !== "undefined" &&
                    typeof jQuery().bootstrapTable !== "undefined" &&
                    typeof jQuery().bootstrapTable.locales !== "undefined" &&
                    typeof _ !== 'undefined' &&
                    typeof jRespond !== "undefined") {
                    if (typeof jQuery().bootstrapTable.locales['da-DK'] === "undefined") {
                        $.getScript(host + "/js/bootstrap-table/bootstrap-table-locale-all.js");
                    }
                    if (typeof jQuery().bootstrapTable.defaults.filterControl === "undefined") {
                        $.getScript(host + "/js/bootstrap-table/extensions/filter-control/bootstrap-table-filter-control.js");
                    }
                    if (typeof jQuery().bootstrapTable.defaults.exportDataType === "undefined") {
                        $.getScript(host + "/js/bootstrap-table/extensions/export/bootstrap-table-export.min.js");
                    }
                    if (typeof jQuery().tableExport === "undefined") {
                        $.getScript(host + "/js/tableExport.jquery.plugin/tableExport.min.js");
                    }
                    if (typeof Backbone === "undefined") {
                        $.getScript("//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js");
                    }
                    (function pollForDependants() {
                        if (typeof jQuery().bootstrapTable.defaults.filterControl !== "undefined" &&
                            typeof jQuery().bootstrapTable.defaults.exportDataType !== "undefined" &&
                            typeof jQuery().tableExport !== "undefined" &&
                            typeof jQuery().bootstrapTable.locales['da-DK'] !== "undefined" &&
                            typeof Backbone !== "undefined") {
                            scriptsLoaded = true;
                        } else {
                            setTimeout(pollForDependants, 10);
                        }
                    }());
                } else {
                    setTimeout(pollForDependencies, 10);
                }
            }());

        } else {
            setTimeout(pollForjQuery, 10);
        }
    }());

    isLoaded = function () {
        return scriptsLoaded;
    };
    object = {};
    init = function (conf) {
        var defaults = {
                el: "#table",
                autoUpdate: false,
                height: 300,
                setSelectedStyle: true,
                openPopUp: false,
                setViewOnSelect: true,
                responsive: true,
                autoPan: false,
                locale: 'en-US',
                callCustomOnload: true,
                popupHtml: null,
                ns: "",
                template: null,
                usingCarto: false,
                onSelect: function () {
                },
                onMouseOver: function () {
                },
                styleSelected: {
                    weight: 5,
                    color: '#666',
                    dashArray: '',
                    fillOpacity: 0.7
                }
            }, prop,
            uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        if (conf) {
            for (prop in conf) {
                defaults[prop] = conf[prop];
            }
        }
        var data,
            m = defaults.geocloud2,
            store = defaults.store,
            cm = defaults.cm,
            autoUpdate = defaults.autoUpdate,
            height = defaults.height,
            tableBodyHeight = defaults.tableBodyHeight,
            styleSelected = defaults.styleSelected,
            el = defaults.el, click, loadDataInTable, moveEndOff, moveEndOn,
            setSelectedStyle = defaults.setSelectedStyle,
            setViewOnSelect = defaults.setViewOnSelect,
            onSelect = defaults.onSelect,
            onMouseOver = defaults.onMouseOver,
            openPopUp = defaults.openPopUp,
            autoPan = defaults.autoPan,
            responsive = defaults.responsive,
            callCustomOnload = defaults.callCustomOnload,
            locale = defaults.locale,
            popupHtml = defaults.popupHtml,
            ns = defaults.ns,
            template = defaults.template,
            usingCartodb = defaults.usingCartodb;

        $(el).parent("div").addClass("gc2map");

        (function poll() {
            if (scriptsLoaded) {
                var originalLayers, filters, filterControls;
                _.extend(object, Backbone.Events);
                object.on("selected" + "_" + uid, function (id) {

                    $(el + ' tr').removeClass("selected");
                    $.each(store.layer._layers, function (i, v) {
                        try {
                            store.layer.resetStyle(v);
                        } catch (e) {
                        }
                    });
                    var row = $('*[data-uniqueid="' + id + '"]');
                    row.addClass("selected");
                    if (setSelectedStyle) {
                        m.map._layers[id].setStyle(styleSelected);
                    }
                    if (openPopUp) {
                        var str = "
", renderedText;
                        $.each(cm, function (i, v) {
                            if (typeof v.showInPopup === "undefined" || (typeof v.showInPopup === "boolean" && v.showInPopup === true)) {
                                str = str + "
" + v.header + "	" + m.map._layers[id].feature.properties[v.dataIndex] + "
";
                            }
                        });
                        str = str + "
";

                        if (template) {
                            renderedText = Mustache.render(template, m.map._layers[id].feature.properties);
                            if (usingCartodb) {
                                renderedText = $.parseHTML(renderedText)[0].children[1].innerHTML
                            }
                        }

                        m.map._layers[id].bindPopup(renderedText || str, {
                            className: "custom-popup",
                            autoPan: autoPan,
                            closeButton: true
                        }).openPopup();

                        object.trigger("openpopup" + "_" + uid, m.map._layers[id]);
                    }

                });
                click = function (e) {
                    var row = $('*[data-uniqueid="' + e.target._leaflet_id + '"]');
                    $(ns + " .fixed-table-body").animate({
                        scrollTop: $(ns + " .fixed-table-body").scrollTop() + (row.offset().top - $(ns + " .fixed-table-body").offset().top)
                    }, 300);
                    object.trigger("selected" + "_" + uid, e.target._leaflet_id);
                };
                $(el).append("

");
                $.each(cm, function (i, v) {
                    $(el + ' thead tr').append("" + v.header + "	");
                });

                var filterMap =
                    _.debounce(function () {
                        var visibleRows = [];
                        $.each(store.layer._layers, function (i, v) {
                            m.map.removeLayer(v);
                        });
                        $.each(originalLayers, function (i, v) {
                            m.map.addLayer(v);
                        });
                        filters = {};
                        filterControls = {};
                        $.each(cm, function (i, v) {
                            if (v.filterControl) {
                                filters[v.dataIndex] = $(".bootstrap-table-filter-control-" + v.dataIndex).val();
                                filterControls[v.dataIndex] = v.filterControl;
                            }
                        });
                        $.each($(el + " tbody").children(), function (x, y) {
                            visibleRows.push($(y).attr("data-uniqueid"));
                        });
                        $.each(store.layer._layers, function (i, v) {
                            if (visibleRows.indexOf(v._leaflet_id + "") === -1) {
                                m.map.removeLayer(v);
                            }
                        });
                        bindEvent();
                    }, 500);

                var bindEvent = function (e) {
                    setTimeout(function () {

                        $(el + ' > tbody > tr').on("click", function (e) {
                            var id = $(this).data('uniqueid');
                            object.trigger("selected" + "_" + uid, id);
                            var layer = m.map._layers[id];
                            setTimeout(function () {
                                if (setViewOnSelect) {
                                    m.map.fitBounds(layer.getBounds());
                                }
                            }, 100);
                            onSelect(id, layer);
                        });

                    }, 100);
                };
                $(el).bootstrapTable({
                    uniqueId: "_id",
                    height: height,
                    locale: locale,
                    onToggle: bindEvent,
                    onSort: bindEvent,
                    onColumnSwitch: bindEvent,
                    onColumnSearch: filterMap
                });

                // Define a callback for when the SQL returns
                var customOnLoad = store.onLoad;
                store.onLoad = function () {
                    loadDataInTable();
                };
                loadDataInTable = function (doNotCallCustomOnload) {
                    data = [];
                    $.each(store.layer._layers, function (i, v) {
                        v.feature.properties._id = i;
                        $.each(v.feature.properties, function (n, m) {
                            $.each(cm, function (j, k) {
                                if (k.dataIndex === n && ((typeof k.link === "boolean" && k.link === true) || (typeof k.link === "string"))) {
                                    v.feature.properties[n] = "" + (typeof k.link === "string" ? k.link : "Link") + "";
                                }

                            });
                        });
                        data.push(v.feature.properties);
                        v.on({
                            click: click
                        });

                    });

                    originalLayers = jQuery.extend(true, {}, store.layer._layers);

                    $(el).bootstrapTable("load", data);

                    bindEvent();

                    if (callCustomOnload && !doNotCallCustomOnload) {
                        customOnLoad(store);
                    }

                    $(".fixed-table-body").css("overflow", "auto");
                    $(".fixed-table-body").css("max-height", tableBodyHeight + "px");
                    $(".fixed-table-body").css("height", tableBodyHeight + "px");

                };

                var moveEndEvent = function () {
                    store.reset();
                    store.load();
                };

                moveEndOff = function () {
                    m.map.off("moveend", moveEndEvent);
                };

                moveEndOn = function () {
                    m.on("moveend", moveEndEvent);
                };

                if (autoUpdate) {
                    m.on("moveend", moveEndEvent);
                }

                var jRes = jRespond([
                    {
                        label: 'handheld',
                        enter: 0,
                        exit: 400
                    },
                    {
                        label: 'desktop',
                        enter: 401,
                        exit: 100000
                    }
                ]);
                if (responsive) {
                    jRes.addFunc({
                        breakpoint: ['handheld'],
                        enter: function () {
                            $(el).bootstrapTable('toggleView');
                        },
                        exit: function () {
                            $(el).bootstrapTable('toggleView');
                        }
                    });
                    jRes.addFunc({
                        breakpoint: ['desktop'],
                        enter: function () {
                        },
                        exit: function () {
                        }
                    });
                }
            } else {
                setTimeout(poll, 20);
            }
        }());
        return {
            loadDataInTable: loadDataInTable,
            object: object,
            uid: uid,
            store: store,
            moveEndOff: moveEndOff,
            moveEndOn: moveEndOn
        };
    };
    return {
        init: init,
        isLoaded: isLoaded
    };
}());
<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd}).bindPopup('to').addTo(map);

    this.polyline_creadas.push(markerform);
    this.polyline_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];

        var circle = L.circle([to[0], to[1]], 50, {
        color: 'blue',
        fillColor: '#000bcb',
        fillOpacity: 0.5
    }).bindPopup(name).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<commit_msg>crea circulo pequeno<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd}).bindPopup('to').addTo(map);

    this.polyline_creadas.push(markerform);
    this.polyline_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];

        var circle = L.circle([to[0], to[1]], 10, {
        color: 'white',
        fillColor: '#000000',
        fillOpacity: 0.5
    }).bindPopup(name).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<|endoftext|>