<commit_before>OpenLayers.ProxyHost = "proxy.cgi?url=";

var wps = "http://demo.opengeo.org/geoserver/wps",
    capabilities, // the capabilities, read by Format.WPSCapabilities::read
    process; // the process description from Format.WPSDescribeProcess::read

// get some capabilities
getCapabilities();

// create the UI
var layer = new OpenLayers.Layer.Vector("Scratchpad", {
    isBaseLayer: true
});
var toolbar = new OpenLayers.Control.EditingToolbar(layer);
toolbar.addControls([new OpenLayers.Control.ModifyFeature(layer, {
    title: "Select feature"
})]);
var map = new OpenLayers.Map('map', {
    controls: [
        toolbar,
        new OpenLayers.Control.ZoomPanel(),
        new OpenLayers.Control.PanPanel()
    ],
    layers: [
        new OpenLayers.Layer.WMS(
            "OSM", "http://maps.opengeo.org/geowebcache/service/wms",
            {layers: "openstreetmap", format: "image/png"}
        ), layer
    ]
});
map.zoomToMaxExtent();

// add behavior to html elements
document.getElementById("processes").onchange = describeProcess;

// using OpenLayers.Format.WPSCapabilities to read the capabilities
function getCapabilities() {
    OpenLayers.Request.GET({
        url: wps,
        params: {
            "SERVICE": "WPS",
            "REQUEST": "GetCapabilities"
        },
        success: function(response){
            capabilities = new OpenLayers.Format.WPSCapabilities().read(
                response.responseText
            );
            var dropdown = document.getElementById("processes");
            var offerings = capabilities.processOfferings, option;
            // populate the dropdown
            for (var p in offerings) {
                option = document.createElement("option");
                option.innerHTML = offerings[p].identifier;
                option.value = p;
                dropdown.appendChild(option);
            }
        }
    });
}

// using OpenLayers.Format.WPSDescribeProcess to get information about a
// process
function describeProcess() {
    var selection = this.options[this.selectedIndex].value;
    OpenLayers.Request.GET({
        url: wps,
        params: {
            "SERVICE": "WPS",
            "REQUEST": "DescribeProcess",
            "VERSION": capabilities.version,
            "IDENTIFIER": selection
        },
        success: function(response) {
            process = new OpenLayers.Format.WPSDescribeProcess().read(
                response.responseText
            ).processDescriptions[selection];
            buildForm();
        }
    });
}

// dynamically create a form from the process description
function buildForm() {
    document.getElementById("abstract").innerHTML = process["abstract"];
    document.getElementById("input").innerHTML = "
Input:
";
    document.getElementById("output").innerHTML = "";

    var inputs = process.dataInputs, supported = true,
        sld = "text/xml; subtype=sld/1.0.0",
        input;
    for (var i=0,ii=inputs.length; i<ii; ++i) {
        input = inputs[i];
        if (input.complexData) {
            var formats = input.complexData.supported.formats;
            if (formats["application/wkt"]) {
                addWKTInput(input);
            } else if (formats["text/xml; subtype=wfs-collection/1.0"]) {
                addWFSCollectionInput(input);
            } else if (formats["image/tiff"]) {
                addRasterInput(input);
            } else if (formats[sld]) {
                addXMLInput(input, sld);
            } else {
                supported = false;
            }
        } else if (input.boundingBoxData) {
            addBoundingBoxInput(input);
        } else if (input.literalData) {
            addLiteralInput(input);
        } else {
            supported = false;
        }
        if (input.minOccurs > 0) {
            document.getElementById("input").appendChild(document.createTextNode("* "));
        }
    }

    if (supported) {
        var executeButton = document.createElement("button");
        executeButton.innerHTML = "Execute";
        document.getElementById("input").appendChild(executeButton);
        executeButton.onclick = execute;
    } else {
        document.getElementById("input").innerHTML = '' +
            "Sorry, the WPS builder does not support the selected process." +
            "";
    }
}

// helper function to dynamically create a textarea for geometry (WKT) data
// input
function addWKTInput(input, previousSibling) {
    var name = input.identifier;
    var container = document.getElementById("input");
    var label = document.createElement("label");
    label["for"] = name;
    label.title = input["abstract"];
    label.innerHTML = name + " (select feature, then click field):";
    previousSibling && previousSibling.nextSibling ?
        container.insertBefore(label, previousSibling.nextSibling) :
        container.appendChild(label);
    var field = document.createElement("textarea");
    field.onclick = function () {
        if (layer.selectedFeatures.length) {
            this.innerHTML = new OpenLayers.Format.WKT().write(
                layer.selectedFeatures[0]
            );
        }
        createCopy(input, this, addWKTInput);
    };
    field.onblur = function() {
        input.data = field.value ? {
            complexData: {
                mimeType: "application/wkt",
                value: this.value
            }
        } : undefined;
    };
    field.title = input["abstract"];
    field.id = name;
    previousSibling && previousSibling.nextSibling ?
        container.insertBefore(field, previousSibling.nextSibling.nextSibling) :
        container.appendChild(field);
}

// helper function for xml input
function addXMLInput(input, type) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    field.value = name + " (" + type + ")";
    field.onblur = function() {
        input.data = field.value ? {
            complexData: {
                mimeType: type,
                value: this.value
            }
        } : undefined;
    };
    document.getElementById("input").appendChild(field);
}

// helper function to dynamically create a WFS collection reference input
function addWFSCollectionInput(input) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    field.value = name + " (layer on demo server)";
    addValueHandlers(field, function() {
        input.reference = field.value ? {
            mimeType: "text/xml; subtype=wfs-collection/1.0",
            href: "http://geoserver/wfs",
            method: "POST",
            body: {
                wfs: {
                    version: "1.0.0",
                    outputFormat: "GML2",
                    featureType: field.value
                }
            }
        } : undefined;
    });
    document.getElementById("input").appendChild(field);
}

// helper function to dynamically create a raster (GeoTIFF) url input
function addRasterInput(input) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    var url = window.location.href.split("?")[0];
    field.value = url.substr(0, url.lastIndexOf("/")+1) + "data/tazdem.tiff";
    document.getElementById("input").appendChild(field);
    (field.onblur = function() {
        input.reference = {
            mimeType: "image/tiff",
            href: field.value,
            method: "GET"
        };
    })();
}

// helper function to dynamically create a bounding box input
function addBoundingBoxInput(input) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    field.value = "left,bottom,right,top (EPSG:4326)";
    document.getElementById("input").appendChild(field);
    addValueHandlers(field, function() {
        input.boundingBoxData = {
            projection: "EPSG:4326",
            bounds: OpenLayers.Bounds.fromString(field.value)
        };
    });
}

// helper function to create a literal input textfield or dropdown
function addLiteralInput(input, previousSibling) {
    var name = input.identifier;
    var container = document.getElementById("input");
    var anyValue = input.literalData.anyValue;
    // anyValue means textfield, otherwise we create a dropdown
    var field = document.createElement(anyValue ? "input" : "select");
    field.id = name;
    field.title = input["abstract"];
    previousSibling && previousSibling.nextSibling ?
        container.insertBefore(field, previousSibling.nextSibling) :
        container.appendChild(field);
    if (anyValue) {
        var dataType = input.literalData.dataType;
        field.value = name + (dataType ? " (" + dataType + ")" : "");
        addValueHandlers(field, function() {
            input.data = field.value ? {
                literalData: {
                    value: field.value
                }
            } : undefined;
            createCopy(input, field, addLiteralInput);
        });
    } else {
        var option;
        option = document.createElement("option");
        option.innerHTML = name;
        field.appendChild(option);
        for (var v in input.literalData.allowedValues) {
            option = document.createElement("option");
            option.value = v;
            option.innerHTML = v;
            field.appendChild(option);
        }
        field.onchange = function() {
            createCopy(input, field, addLiteralInput);
            input.data = this.selectedIndex ? {
                literalData: {
                    value: this.options[this.selectedIndex].value
                }
            } : undefined;
        };
    }
}

// if maxOccurs is > 1, this will add a copy of the field
function createCopy(input, field, fn) {
    if (input.maxOccurs && input.maxOccurs > 1 && !field.userSelected) {
        // add another copy of the field - we don't check maxOccurs
        field.userSelected = true;
        var newInput = OpenLayers.Util.extend({}, input);
        // we recognize copies by the occurrence property
        newInput.occurrence = (input.occurrence || 0) + 1;
        process.dataInputs.push(newInput);
        fn(newInput, field);
    }
}

// helper function for adding events to form fields
function addValueHandlers(field, onblur) {
    field.onclick = function() {
        if (!this.initialValue) {
            this.initialValue = this.value;
            this.value = "";
        }
    };
    field.onblur = function() {
        if (!this.value) {
            this.value = this.initialValue;
            delete this.initialValue;
        }
        onblur.apply(this, arguments);
    };
}

// execute the process
function execute() {
    var output = process.processOutputs[0];
    var input;
    // remove occurrences that the user has not filled out
    for (var i=process.dataInputs.length-1; i>=0; --i) {
        input = process.dataInputs[i];
        if ((input.minOccurs === 0 || input.occurrence) && !input.data && !input.reference) {
            OpenLayers.Util.removeItem(process.dataInputs, input);
        }
    }
    process.responseForm = {
        rawDataOutput: {
            identifier: output.identifier
        }
    };
    if (output.complexOutput && output.complexOutput.supported.formats["application/wkt"]) {
        process.responseForm.rawDataOutput.mimeType = "application/wkt";
    }
    OpenLayers.Request.POST({
        url: wps,
        data: new OpenLayers.Format.WPSExecute().write(process),
        success: showOutput
    });
}

// add the process's output to the page
function showOutput(response) {
    var result = document.getElementById("output");
    result.innerHTML = "
Output:
";
    var features;
    var contentType = response.getResponseHeader("Content-Type");
    if (contentType == "application/wkt") {
        features = new OpenLayers.Format.WKT().read(response.responseText);
    } else if (contentType == "text/xml; subtype=wfs-collection/1.0") {
        features = new OpenLayers.Format.WFST.v1_0_0().read(response.responseText);
    }
    if (features && (features instanceof OpenLayers.Feature.Vector || features.length)) {
        layer.addFeatures(features);
        result.innerHTML += "The result should also be visible on the map.";
    }
    result.innerHTML += "<textarea>" + response.responseText + "</textarea>";
}<commit_msg>Vector layer should not be a base layer any more.<commit_after>OpenLayers.ProxyHost = "proxy.cgi?url=";

var wps = "http://demo.opengeo.org/geoserver/wps",
    capabilities, // the capabilities, read by Format.WPSCapabilities::read
    process; // the process description from Format.WPSDescribeProcess::read

// get some capabilities
getCapabilities();

// create the UI
var layer = new OpenLayers.Layer.Vector("Scratchpad");
var toolbar = new OpenLayers.Control.EditingToolbar(layer);
toolbar.addControls([new OpenLayers.Control.ModifyFeature(layer, {
    title: "Select feature"
})]);
var map = new OpenLayers.Map('map', {
    controls: [
        toolbar,
        new OpenLayers.Control.ZoomPanel(),
        new OpenLayers.Control.PanPanel()
    ],
    layers: [
        new OpenLayers.Layer.WMS(
            "OSM", "http://maps.opengeo.org/geowebcache/service/wms",
            {layers: "openstreetmap", format: "image/png"}
        ), layer
    ]
});
map.zoomToMaxExtent();

// add behavior to html elements
document.getElementById("processes").onchange = describeProcess;

// using OpenLayers.Format.WPSCapabilities to read the capabilities
function getCapabilities() {
    OpenLayers.Request.GET({
        url: wps,
        params: {
            "SERVICE": "WPS",
            "REQUEST": "GetCapabilities"
        },
        success: function(response){
            capabilities = new OpenLayers.Format.WPSCapabilities().read(
                response.responseText
            );
            var dropdown = document.getElementById("processes");
            var offerings = capabilities.processOfferings, option;
            // populate the dropdown
            for (var p in offerings) {
                option = document.createElement("option");
                option.innerHTML = offerings[p].identifier;
                option.value = p;
                dropdown.appendChild(option);
            }
        }
    });
}

// using OpenLayers.Format.WPSDescribeProcess to get information about a
// process
function describeProcess() {
    var selection = this.options[this.selectedIndex].value;
    OpenLayers.Request.GET({
        url: wps,
        params: {
            "SERVICE": "WPS",
            "REQUEST": "DescribeProcess",
            "VERSION": capabilities.version,
            "IDENTIFIER": selection
        },
        success: function(response) {
            process = new OpenLayers.Format.WPSDescribeProcess().read(
                response.responseText
            ).processDescriptions[selection];
            buildForm();
        }
    });
}

// dynamically create a form from the process description
function buildForm() {
    document.getElementById("abstract").innerHTML = process["abstract"];
    document.getElementById("input").innerHTML = "
Input:
";
    document.getElementById("output").innerHTML = "";

    var inputs = process.dataInputs, supported = true,
        sld = "text/xml; subtype=sld/1.0.0",
        input;
    for (var i=0,ii=inputs.length; i<ii; ++i) {
        input = inputs[i];
        if (input.complexData) {
            var formats = input.complexData.supported.formats;
            if (formats["application/wkt"]) {
                addWKTInput(input);
            } else if (formats["text/xml; subtype=wfs-collection/1.0"]) {
                addWFSCollectionInput(input);
            } else if (formats["image/tiff"]) {
                addRasterInput(input);
            } else if (formats[sld]) {
                addXMLInput(input, sld);
            } else {
                supported = false;
            }
        } else if (input.boundingBoxData) {
            addBoundingBoxInput(input);
        } else if (input.literalData) {
            addLiteralInput(input);
        } else {
            supported = false;
        }
        if (input.minOccurs > 0) {
            document.getElementById("input").appendChild(document.createTextNode("* "));
        }
    }

    if (supported) {
        var executeButton = document.createElement("button");
        executeButton.innerHTML = "Execute";
        document.getElementById("input").appendChild(executeButton);
        executeButton.onclick = execute;
    } else {
        document.getElementById("input").innerHTML = '' +
            "Sorry, the WPS builder does not support the selected process." +
            "";
    }
}

// helper function to dynamically create a textarea for geometry (WKT) data
// input
function addWKTInput(input, previousSibling) {
    var name = input.identifier;
    var container = document.getElementById("input");
    var label = document.createElement("label");
    label["for"] = name;
    label.title = input["abstract"];
    label.innerHTML = name + " (select feature, then click field):";
    previousSibling && previousSibling.nextSibling ?
        container.insertBefore(label, previousSibling.nextSibling) :
        container.appendChild(label);
    var field = document.createElement("textarea");
    field.onclick = function () {
        if (layer.selectedFeatures.length) {
            this.innerHTML = new OpenLayers.Format.WKT().write(
                layer.selectedFeatures[0]
            );
        }
        createCopy(input, this, addWKTInput);
    };
    field.onblur = function() {
        input.data = field.value ? {
            complexData: {
                mimeType: "application/wkt",
                value: this.value
            }
        } : undefined;
    };
    field.title = input["abstract"];
    field.id = name;
    previousSibling && previousSibling.nextSibling ?
        container.insertBefore(field, previousSibling.nextSibling.nextSibling) :
        container.appendChild(field);
}

// helper function for xml input
function addXMLInput(input, type) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    field.value = name + " (" + type + ")";
    field.onblur = function() {
        input.data = field.value ? {
            complexData: {
                mimeType: type,
                value: this.value
            }
        } : undefined;
    };
    document.getElementById("input").appendChild(field);
}

// helper function to dynamically create a WFS collection reference input
function addWFSCollectionInput(input) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    field.value = name + " (layer on demo server)";
    addValueHandlers(field, function() {
        input.reference = field.value ? {
            mimeType: "text/xml; subtype=wfs-collection/1.0",
            href: "http://geoserver/wfs",
            method: "POST",
            body: {
                wfs: {
                    version: "1.0.0",
                    outputFormat: "GML2",
                    featureType: field.value
                }
            }
        } : undefined;
    });
    document.getElementById("input").appendChild(field);
}

// helper function to dynamically create a raster (GeoTIFF) url input
function addRasterInput(input) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    var url = window.location.href.split("?")[0];
    field.value = url.substr(0, url.lastIndexOf("/")+1) + "data/tazdem.tiff";
    document.getElementById("input").appendChild(field);
    (field.onblur = function() {
        input.reference = {
            mimeType: "image/tiff",
            href: field.value,
            method: "GET"
        };
    })();
}

// helper function to dynamically create a bounding box input
function addBoundingBoxInput(input) {
    var name = input.identifier;
    var field = document.createElement("input");
    field.title = input["abstract"];
    field.value = "left,bottom,right,top (EPSG:4326)";
    document.getElementById("input").appendChild(field);
    addValueHandlers(field, function() {
        input.boundingBoxData = {
            projection: "EPSG:4326",
            bounds: OpenLayers.Bounds.fromString(field.value)
        };
    });
}

// helper function to create a literal input textfield or dropdown
function addLiteralInput(input, previousSibling) {
    var name = input.identifier;
    var container = document.getElementById("input");
    var anyValue = input.literalData.anyValue;
    // anyValue means textfield, otherwise we create a dropdown
    var field = document.createElement(anyValue ? "input" : "select");
    field.id = name;
    field.title = input["abstract"];
    previousSibling && previousSibling.nextSibling ?
        container.insertBefore(field, previousSibling.nextSibling) :
        container.appendChild(field);
    if (anyValue) {
        var dataType = input.literalData.dataType;
        field.value = name + (dataType ? " (" + dataType + ")" : "");
        addValueHandlers(field, function() {
            input.data = field.value ? {
                literalData: {
                    value: field.value
                }
            } : undefined;
            createCopy(input, field, addLiteralInput);
        });
    } else {
        var option;
        option = document.createElement("option");
        option.innerHTML = name;
        field.appendChild(option);
        for (var v in input.literalData.allowedValues) {
            option = document.createElement("option");
            option.value = v;
            option.innerHTML = v;
            field.appendChild(option);
        }
        field.onchange = function() {
            createCopy(input, field, addLiteralInput);
            input.data = this.selectedIndex ? {
                literalData: {
                    value: this.options[this.selectedIndex].value
                }
            } : undefined;
        };
    }
}

// if maxOccurs is > 1, this will add a copy of the field
function createCopy(input, field, fn) {
    if (input.maxOccurs && input.maxOccurs > 1 && !field.userSelected) {
        // add another copy of the field - we don't check maxOccurs
        field.userSelected = true;
        var newInput = OpenLayers.Util.extend({}, input);
        // we recognize copies by the occurrence property
        newInput.occurrence = (input.occurrence || 0) + 1;
        process.dataInputs.push(newInput);
        fn(newInput, field);
    }
}

// helper function for adding events to form fields
function addValueHandlers(field, onblur) {
    field.onclick = function() {
        if (!this.initialValue) {
            this.initialValue = this.value;
            this.value = "";
        }
    };
    field.onblur = function() {
        if (!this.value) {
            this.value = this.initialValue;
            delete this.initialValue;
        }
        onblur.apply(this, arguments);
    };
}

// execute the process
function execute() {
    var output = process.processOutputs[0];
    var input;
    // remove occurrences that the user has not filled out
    for (var i=process.dataInputs.length-1; i>=0; --i) {
        input = process.dataInputs[i];
        if ((input.minOccurs === 0 || input.occurrence) && !input.data && !input.reference) {
            OpenLayers.Util.removeItem(process.dataInputs, input);
        }
    }
    process.responseForm = {
        rawDataOutput: {
            identifier: output.identifier
        }
    };
    if (output.complexOutput && output.complexOutput.supported.formats["application/wkt"]) {
        process.responseForm.rawDataOutput.mimeType = "application/wkt";
    }
    OpenLayers.Request.POST({
        url: wps,
        data: new OpenLayers.Format.WPSExecute().write(process),
        success: showOutput
    });
}

// add the process's output to the page
function showOutput(response) {
    var result = document.getElementById("output");
    result.innerHTML = "
Output:
";
    var features;
    var contentType = response.getResponseHeader("Content-Type");
    if (contentType == "application/wkt") {
        features = new OpenLayers.Format.WKT().read(response.responseText);
    } else if (contentType == "text/xml; subtype=wfs-collection/1.0") {
        features = new OpenLayers.Format.WFST.v1_0_0().read(response.responseText);
    }
    if (features && (features instanceof OpenLayers.Feature.Vector || features.length)) {
        layer.addFeatures(features);
        result.innerHTML += "The result should also be visible on the map.";
    }
    result.innerHTML += "<textarea>" + response.responseText + "</textarea>";
}<|endoftext|>


<commit_before>import { SiteConf } from 'base';
import serviceWorkerTemplate from './sw';

export default function blog(params) {
  const state = JSON.stringify(params.state);

  return `
  <!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>${ SiteConf.BlogTitle }</title>
    <meta name="HandheldFriendly" content="True" />
    <link rel="alternate" hreflang="es" href="https://pablomagaz.com" />

    <meta name="description" content="${ SiteConf.BlogDescription }" />
    <meta name="referrer" content="no-referrer-when-downgrade" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="${ SiteConf.KeyWords }">
    <link rel="canonical" href="${ SiteConf.BlogUrl }" />

    ${ params.style }
    <link rel="manifest" href="${ SiteConf.SiteUrl }/manifest.webmanifest" />
    <meta name="theme-color" content="#f72354">
    <link rel="icon" href="${ SiteConf.SiteUrl }/assets/images/favicon.ico"/>
    <link rel="apple-touch-icon" sizes="180x180" href="${ SiteConf.SiteUrl }/assets/images/icons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="${ SiteConf.SiteUrl }/assets/images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="${ SiteConf.SiteUrl }/assets/images/icons/favicon-32x32.png">
    <link rel="mask-icon" href="${ SiteConf.SiteUrl }/assets/images/icons/safari-pinned-tab.svg" color="#f72354">
    <meta name="msapplication-TileColor" content="#f72354">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#f72354">
    <meta name="apple-mobile-web-app-title" content="${ SiteConf.BlogTitle }">
    <meta http-equiv="x-ua-compatible" content="IE=Edge">

    <meta property="og:locale" content="es_ES" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="${ SiteConf.BlogTitle }" />
    <meta property="og:site_name" content="${ SiteConf.BlogTitle }" />
    <meta property="og:url" content="${ SiteConf.BlogUrl }" />
    <meta property="og:description" content="${ SiteConf.BlogDescription }" />
    <meta property="og:image" content="${ SiteConf.ServerUrl }/${ SiteConf.blogTitleImage }" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="${ SiteConf.BlogTitle }" />
    <meta name="twitter:url" content="${ SiteConf.BlogUrl }" />
    <meta name="twitter:description" content="${ SiteConf.BlogDescription }" />
    <meta name="twitter:image" content="${ SiteConf.ServerUrl }/${ SiteConf.blogTitleImage }" />
    <meta name="google-site-verification" content="WPquQ1N8IxHd4sXYLzqumAtex4IlcULtupjrsaCZT7s" />

    ${ params.vendorScript }

${ params.container }

      ${ params.appScript }
      ${ serviceWorkerTemplate }

  `;
}
<commit_msg>Remove script<commit_after>import { SiteConf } from 'base';
import serviceWorkerTemplate from './sw';

export default function blog(params) {
  const state = JSON.stringify(params.state);

  return `
  <!doctype html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>${ SiteConf.BlogTitle }</title>
    <meta name="HandheldFriendly" content="True" />
    <link rel="alternate" hreflang="es" href="https://pablomagaz.com" />

    <meta name="description" content="${ SiteConf.BlogDescription }" />
    <meta name="referrer" content="no-referrer-when-downgrade" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="${ SiteConf.KeyWords }">
    <link rel="canonical" href="${ SiteConf.BlogUrl }" />
    ${ params.style }
    <link rel="manifest" href="${ SiteConf.SiteUrl }/manifest.webmanifest" />
    <meta name="theme-color" content="#f72354">
    <link rel="icon" href="${ SiteConf.SiteUrl }/assets/images/favicon.ico"/>
    <link rel="apple-touch-icon" sizes="180x180" href="${ SiteConf.SiteUrl }/assets/images/icons/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="${ SiteConf.SiteUrl }/assets/images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="${ SiteConf.SiteUrl }/assets/images/icons/favicon-32x32.png">
    <link rel="mask-icon" href="${ SiteConf.SiteUrl }/assets/images/icons/safari-pinned-tab.svg" color="#f72354">
    <meta name="msapplication-TileColor" content="#f72354">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#f72354">
    <meta name="apple-mobile-web-app-title" content="${ SiteConf.BlogTitle }">
    <meta http-equiv="x-ua-compatible" content="IE=Edge">

    <meta property="og:locale" content="es_ES" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="${ SiteConf.BlogTitle }" />
    <meta property="og:site_name" content="${ SiteConf.BlogTitle }" />
    <meta property="og:url" content="${ SiteConf.BlogUrl }" />
    <meta property="og:description" content="${ SiteConf.BlogDescription }" />
    <meta property="og:image" content="${ SiteConf.ServerUrl }/${ SiteConf.blogTitleImage }" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="${ SiteConf.BlogTitle }" />
    <meta name="twitter:url" content="${ SiteConf.BlogUrl }" />
    <meta name="twitter:description" content="${ SiteConf.BlogDescription }" />
    <meta name="twitter:image" content="${ SiteConf.ServerUrl }/${ SiteConf.blogTitleImage }" />
    <meta name="google-site-verification" content="WPquQ1N8IxHd4sXYLzqumAtex4IlcULtupjrsaCZT7s" />

    ${ params.vendorScript }

${ params.container }

      ${ params.appScript }
      ${ serviceWorkerTemplate }

  `;
}
<|endoftext|>


<commit_before>var Node = require('./node');

/**
 * The Grid class, which serves as the encapsulation of the layout of the
 * nodes on the map.
 * @constructor
 * @param {number} width Number of columns of the grid.
 * @param {number} height Number of rows of the grid.
 * @param {Array.<Array.<(number|boolean)>>} [matrix] - A 0-1 matrix
 *     representing the walkable status of the nodes(0 or false for walkable).
 *     If the matrix is not supplied, all the nodes will be walkable.
 */
function Grid(width, height, matrix) {
    /**
     * The number of columns of the grid.
     * @type number
     */
    this.width = width;
    /**
     * The number of rows of the grid.
     * @type number
     */
    this.height = height;

    this._buildGrid(matrix);
};

/**
 * Build the grids.
 * @private
 * @param {Array.<Array.<number|boolean>>} [matrix] - A 0-1 matrix representing
 *     the walkable status of the nodes.
 * @see Grid
 */
Grid.prototype._buildGrid = function(matrix) {
    var i, j,
        width = this.width,
        height = this.height,
        nodes = [],
        row;

    for (i = 0; i < height; ++i) {
        nodes.push([]); // push is faster than assignment via indexing
        row = nodes[i];
        for (j = 0; j < width; ++j) {
            row.push(new Node(j, i));
        }
    }

    this.nodes = nodes;

    if (matrix === undefined) {
        return;
    }

    if (matrix.length != height || matrix[0].length != width) {
        throw new Error('Matrix size does not fit');
    }

    for (i = 0; i < height; ++i) {
        for (j = 0; j < width; ++j) {
            if (matrix[i][j]) {
                // 0, false, null will be walkable
                // while others will be un-walkable
                nodes[i][j].walkable = false;
            }
        }
    }
};

/**
 * Get the node at the given position.
 * @param {number} x - The x coordinate of the node.
 * @param {number} y - The y coordinate of the node.
 * @return {Node}
 */
Grid.prototype.getNodeAt = function(x, y) {
    return this.nodes[y][x];
};

/**
 * Determine whether the node on the given position is walkable.
 * @param {number} x - The x coordinate of the node.
 * @param {number} y - The y coordinate of the node.
 * @return {boolean} - The walkability of the node.
 */
Grid.prototype.isWalkableAt = function(x, y) {
    return this.getNodeAt(x, y).get('walkable');
};

/**
 * Set whether the node on the given position is walkable.
 * @param {number} x - The x coordinate of the node.
 * @param {number} y - The y coordinate of the node.
 * @param {boolean} walkable - Whether the position is walkable.
 */
Grid.prototype.setWalkableAt = function(x, y, walkable) {
    this.getNodeAt(x, y).set('walkable', walkable);
};

/**
 * Determine whether the given position is inside the grid.
 * @param {number} x - The x coordinate of the position.
 * @param {number} y - The y coordinate of the position.
 * @return {boolean} Whether the position is inside.
 */
Grid.prototype.isInside = function(x, y) {
    return x >= 0 && x < this.width &&
           y >= 0 && y < this.height;
};

/**
 * Generic setter of the attribute at the given position.
 * Note: This method gets the same result as:
 *     {@code node = grid.getNodeAt(x, y);
 *            node[attr] = value;}
 * @param {number} x - The x coordinate of the position.
 * @param {number} y - The y coordinate of the position.
 * @param {string} attr - The name of attribute to set.
 * @param {*} value - The value of attribute.
 */
Grid.prototype.setAttributeAt = function(x, y, attr, value) {
    this.getNodeAt(x, y).set(attr, value);
};

/**
 * Generic getter of the attribute at the given position.
 * Note: This method gets the same result as:
 *     {@code node = grid.getNodeAt(x, y);
 *            return node[attr];}
 * @param {number} x - The x coordinate of the position.
 * @param {number} y - The y coordinate of the position.
 * @param {string} attr - The name of attribute to get.
 * @return The value of the attribute.
 */
Grid.prototype.getAttributeAt = function(x, y, attr) {
    return this.getNodeAt(x, y).get(attr);
};

/**
 * Get a clone of this grid.
 * @return {Grid} Cloned grid.
 */
Grid.prototype.clone = function() {
    var i, j,

        width = this.width,
        height = this.height,
        thisNodes = this.nodes,

        newGrid = new Grid(width, height),
        newNodes = [],
        row;

    for (i = 0; i < height; ++i) {
        newNodes.push([]);
        row = newNodes[i];
        for (j = 0; j < width; ++j) {
            row.push(thisNodes[i][j].clone());
        }
    }

    newGrid.nodes = newNodes;

    return newGrid;
};

module.exports = Grid;
<commit_msg>mod: adapt grid to the new node api<commit_after>var Node = require('./node');

/**
 * The Grid class, which serves as the encapsulation of the layout of the
 * nodes on the map.
 * @constructor
 * @param {number} width Number of columns of the grid.
 * @param {number} height Number of rows of the grid.
 * @param {Array.<Array.<(number|boolean)>>} [matrix] - A 0-1 matrix
 *     representing the walkable status of the nodes(0 or false for walkable).
 *     If the matrix is not supplied, all the nodes will be walkable.  */
function Grid(width, height, matrix) {
    /**
     * The number of columns of the grid.
     * @type number
     */
    this.width = width;
    /**
     * The number of rows of the grid.
     * @type number
     */
    this.height = height;

    this._buildGrid(matrix);
};

/**
 * Build the grids.
 * @private
 * @param {Array.<Array.<number|boolean>>} [matrix] - A 0-1 matrix representing
 *     the walkable status of the nodes.
 * @see Grid
 */
Grid.prototype._buildGrid = function(matrix) {
    var i, j,
        width = this.width,
        height = this.height,
        nodes = [],
        row;

    for (i = 0; i < height; ++i) {
        nodes.push([]); // push is faster than assignment via indexing
        row = nodes[i];
        for (j = 0; j < width; ++j) {
            row.push(new Node(j, i));
        }
    }

    this.nodes = nodes;

    if (matrix === undefined) {
        return;
    }

    if (matrix.length != height || matrix[0].length != width) {
        throw new Error('Matrix size does not fit');
    }

    for (i = 0; i < height; ++i) {
        for (j = 0; j < width; ++j) {
            if (matrix[i][j]) {
                // 0, false, null will be walkable
                // while others will be un-walkable
                nodes[i][j].walkable = false;
            }
        }
    }
};

/**
 * Get the node at the given position.
 * @param {number} x - The x coordinate of the node.
 * @param {number} y - The y coordinate of the node.
 * @return {Node}
 */
Grid.prototype.getNodeAt = function(x, y) {
    return this.nodes[y][x];
};

/**
 * Determine whether the node on the given position is walkable.
 * @param {number} x - The x coordinate of the node.
 * @param {number} y - The y coordinate of the node.
 * @return {boolean} - The walkability of the node. (Also returns false if
 *     the coordinate is not inside the grid.)
 */
Grid.prototype.isWalkableAt = function(x, y) {
    return (x >= 0 && x < this.width) &&
           (y >= 0 && y < this.height) &&
           this.getNodeAt(x, y).walkable;
};

/**
 * Set whether the node on the given position is walkable.
 * NOTE: throws exception if the coordinate is not inside the grid.
 * @param {number} x - The x coordinate of the node.
 * @param {number} y - The y coordinate of the node.
 * @param {boolean} walkable - Whether the position is walkable.
 */
Grid.prototype.setWalkableAt = function(x, y, walkable) {
    this.getNodeAt(x, y).walkable = walkable;
};

/**
 * Get a clone of this grid.
 * @return {Grid} Cloned grid.
 */
Grid.prototype.clone = function() {
    var i, j,

        width = this.width,
        height = this.height,
        thisNodes = this.nodes,

        newGrid = new Grid(width, height),
        newNodes = [],
        row;

    for (i = 0; i < height; ++i) {
        newNodes.push([]);
        row = newNodes[i];
        for (j = 0; j < width; ++j) {
            row.push(thisNodes[i][j].clone());
        }
    }

    newGrid.nodes = newNodes;

    return newGrid;
};

module.exports = Grid;
<|endoftext|>


<commit_before>var assert = require('chai').assert,
	path = require('path'),
	proxyquire = require('proxyquire'),
	sinon = require('sinon');

describe('CollectionItem', function () {

	var item;

	var restHandlersPath = path.normalize(__dirname + '/../../lib/restHandlers');

	var restHandlerMock = {
		editItem: sinon.spy()
	};

	var initWithMocks = function () {
		var stubs = {};
		stubs[restHandlersPath] = function () {
			return restHandlerMock
		};

		var CollectionItem = proxyquire('./../../lib/CollectionItem', stubs);

		item = new CollectionItem('deals', {
			title: 'Deal title'
		}, 1);

		return item;
	};

	beforeEach(function () {
		item = initWithMocks(restHandlerMock);
	});

	it('should return object', function () {
		assert.isObject(item);
		assert.isFunction(item.getUpdates);
	});

	describe('subMethods', function () {
		it('should be generated for deal products', function () {
			assert.isFunction(item.addProduct);
			assert.isFunction(item.updateProduct);
			assert.isFunction(item.deleteProduct);
		});

		it('should call restHandler.editItem() when item.updateProduct() is called', function () {
			item.updateProduct({
				id: 2
			});

			sinon.assert.calledOnce(restHandlerMock.editItem);
			sinon.assert.calledWith(restHandlerMock.editItem, 2, 'deals/1/products', {id: 2});
		});
	});
});<commit_msg>Added coverage for CollectionItem.getUpdates<commit_after>var assert = require('chai').assert,
	path = require('path'),
	proxyquire = require('proxyquire'),
	sinon = require('sinon');

describe('CollectionItem', function () {

	var item;

	var restHandlersPath = path.normalize(__dirname + '/../../lib/restHandlers');

	var restHandlerMock = {
		editItem: sinon.spy(),
		listItems: sinon.spy()
	};

	var initWithMocks = function () {
		var stubs = {};
		stubs[restHandlersPath] = function () {
			return restHandlerMock
		};

		var CollectionItem = proxyquire('./../../lib/CollectionItem', stubs);

		item = new CollectionItem('deals', {
			title: 'Deal title'
		}, 1);

		return item;
	};

	beforeEach(function () {
		item = initWithMocks(restHandlerMock);
	});

	it('should return object', function () {
		console.log(item);
		assert.isObject(item);
		assert.isFunction(item.getUpdates);
	});

	describe('subMethods', function () {
		it('should be generated for deal products', function () {
			assert.isFunction(item.addProduct);
			assert.isFunction(item.updateProduct);
			assert.isFunction(item.deleteProduct);
		});

		it('.getUpdates() should call restHandler.editItem()', function () {
			item.getUpdates({
				id: 3
			});

			sinon.assert.calledOnce(restHandlerMock.listItems);
			sinon.assert.calledWith(restHandlerMock.listItems, 'deals/1/flow', {id: 3});
		});

		it('.updateProduct() should call restHandler.editItem()', function () {
			item.updateProduct({
				id: 2
			});

			sinon.assert.calledOnce(restHandlerMock.editItem);
			sinon.assert.calledWith(restHandlerMock.editItem, 2, 'deals/1/products', {id: 2});
		});
	});
});<|endoftext|>


<commit_before>angular.module('formlyBootstrap', ['formly'], function configFormlyVanilla(formlyConfigProvider) {
  'use strict';

  formlyConfigProvider.setWrapper([{
      name: 'bootstrapLabel',
      templateUrl: 'wrappers/formly-wrappers-bootstrap-label.html'
        },
    {
      name: 'bootstrapHasError',
      templateUrl: 'wrappers/formly-wrappers-bootstrap-has-error.html'
        }
    ]);

  var commonWrappers = ['bootstrapLabel', 'bootstrapHasError'];

  angular.forEach(['radio', 'select'], function (fieldName) {
    formlyConfigProvider.setType({
      name: fieldName,
      templateUrl: getFieldTemplateUrl(fieldName),
      wrapper: commonWrappers
    });
  });
  formlyConfigProvider.setType({
    name: 'input',
    template: '<input class="form-control" ng-model="model[options.key]">',
    wrapper: commonWrappers
  });

  // textarea has custom defaultOptions
  formlyConfigProvider.setType({
    name: 'textarea',
    template: '<textarea class="form-control" ng-model="model[options.key]"></textarea>',
    wrapper: commonWrappers,
    defaultOptions: {
      data: {
        ngModelAttributes: {
          rows: 'rows',
          cols: 'cols'
        }
      }
    }
  });

  // checkbox doesn't have a bootstrapLabel wrapper
  formlyConfigProvider.setType({
    name: 'checkbox',
    templateUrl: getFieldTemplateUrl('checkbox'),
    wrapper: ['bootstrapHasError']
  });

  formlyConfigProvider.templateManipulators.preWrapper.push(function ariaDescribedBy(template, options, scope) {
    if (options.templateOptions && angular.isDefined(options.templateOptions.description) &&
      options.type !== 'radio' && options.type !== 'checkbox') {
      var el = angular.element('');
      el.append(template);
      var modelEls = angular.element(el[0].querySelectorAll('[ng-model]'));
      if (modelEls) {
        el.append(
          '
' +
          '{{options.templateOptions.description}}' +
          '
'
        );
        modelEls.attr('aria-describedby', scope.id + '_description');
        return el.html();
      } else {
        return template;
      }
    } else {
      return template;
    }
  });

  function getFieldTemplateUrl(name) {
    return 'fields/formly-field-' + name + '.html';
  }

});

angular.module('formlyBootstrap').run(function (formlyConfig, $http, $templateCache) {
  formlyConfig.templateManipulators.preWrapper.push(function (template, options) {
    if (options.type !== 'input' || (!options.templateOptions.addonLeft && !options.templateOptions.addonRight)) {
      return template;
    }
    return $http.get('other/formly-other-bootstrap-addons.html', {
      cache: $templateCache
    }).then(function (response) {
      return response.data.replace('<formly-transclude></formly-transclude>', template);
    });
  });
});<commit_msg>Indentation correction<commit_after>angular.module('formlyBootstrap', ['formly'], function configFormlyVanilla(formlyConfigProvider) {
  'use strict';

  formlyConfigProvider.setWrapper([
    {
      name: 'bootstrapLabel',
      templateUrl: 'wrappers/formly-wrappers-bootstrap-label.html'
    },
    {
      name: 'bootstrapHasError',
      templateUrl: 'wrappers/formly-wrappers-bootstrap-has-error.html'
    }
  ]);

  var commonWrappers = ['bootstrapLabel', 'bootstrapHasError'];

  angular.forEach(['radio', 'select'], function (fieldName) {
    formlyConfigProvider.setType({
      name: fieldName,
      templateUrl: getFieldTemplateUrl(fieldName),
      wrapper: commonWrappers
    });
  });
  formlyConfigProvider.setType({
    name: 'input',
    template: '<input class="form-control" ng-model="model[options.key]">',
    wrapper: commonWrappers
  });

  // textarea has custom defaultOptions
  formlyConfigProvider.setType({
    name: 'textarea',
    template: '<textarea class="form-control" ng-model="model[options.key]"></textarea>',
    wrapper: commonWrappers,
    defaultOptions: {
      data: {
        ngModelAttributes: {
          rows: 'rows',
          cols: 'cols'
        }
      }
    }
  });

  // checkbox doesn't have a bootstrapLabel wrapper
  formlyConfigProvider.setType({
    name: 'checkbox',
    templateUrl: getFieldTemplateUrl('checkbox'),
    wrapper: ['bootstrapHasError']
  });

  formlyConfigProvider.templateManipulators.preWrapper.push(function ariaDescribedBy(template, options, scope) {
    if (options.templateOptions && angular.isDefined(options.templateOptions.description) &&
        options.type !== 'radio' && options.type !== 'checkbox') {
      var el = angular.element('');
      el.append(template);
      var modelEls = angular.element(el[0].querySelectorAll('[ng-model]'));
      if (modelEls) {
        el.append(
          '
' +
          '{{options.templateOptions.description}}' +
          '
'
        );
        modelEls.attr('aria-describedby', scope.id + '_description');
        return el.html();
      } else {
        return template;
      }
    } else {
      return template;
    }
  });

  function getFieldTemplateUrl(name) {
    return 'fields/formly-field-' + name + '.html';
  }

});

angular.module('formlyBootstrap').run(function (formlyConfig, $http, $templateCache) {
  formlyConfig.templateManipulators.preWrapper.push(function (template, options) {
    if (options.type !== 'input' || (!options.templateOptions.addonLeft && !options.templateOptions.addonRight)) {
      return template;
    }
    return $http.get('other/formly-other-bootstrap-addons.html', {
      cache: $templateCache
    }).then(function (response) {
      return response.data.replace('<formly-transclude></formly-transclude>', template);
    });
  });
});<|endoftext|>


<commit_before>var midas = midas || {};
midas.upload = midas.upload || {};
midas.upload.simpleupload = {};

// We use shockwave flash uploader for IE (no multi-file upload support)
midas.upload.simpleupload.initSwfupload = function () {
    // Callback hook for the flash uploader
    midas.upload.simpleupload.uploadPreStart = function (file) {
        midas.upload.simpleupload.swfu.setPostParams({
            'sid': $('.sessionId').val(),
            'parent': $('#destinationId').val(),
            'license': $('select[name=licenseSelect]').val()
        });
    }
    var settings = {
        flash_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp10/swfupload.swf",
        flash9_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp9/swfupload_fp9.swf",
        upload_url: json.global.webroot+"/upload/saveuploaded",
        post_params: {
            'sid': $('.sessionId').val(),
            'parent': $('#destinationId').val(),
            'license': $('select[name=licenseSelect]').val()
        },
        file_size_limit: $('.maxSizeFile').val()+" MB",
        file_types: "*.*",
        file_types_description: "All Files",
        file_upload_limit: 100,
        file_queue_limit: 0,
        custom_settings: {
            progressTarget: "fsUploadProgress",
            cancelButtonId: "btnCancel",
            pageObj: midas.upload.simpleupload
        },
        debug: false,

        // Button settings
        button_image_url: json.global.coreWebroot+"/public/js/swfupload/images/Button_65x29.png",
        button_width: "65",
        button_height: "20",
        button_placeholder_id: "spanButtonPlaceHolder",
        button_text: ''+$('.buttonBrowse').val()+'',
        button_text_style: ".theFont { font-size: 12; }",
        button_text_left_padding: 5,
        button_text_top_padding: 0,

        // The event handler functions are defined in handlers.js
        swfupload_preload_handler: preLoad,
        swfupload_load_failed_handler: loadFailed,
        file_queued_handler: fileQueued,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialogComplete,
        upload_start_handler: midas.upload.simpleupload.uploadPreStart,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccess,
        upload_complete_handler: uploadComplete,
        queue_complete_handler: queueComplete  // Queue plugin event
    };

    $('#swfuploadContent').show();
    midas.upload.simpleupload.swfu = new SWFUpload(settings);

    $('#startUploadLink').click(function () {
        if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0) {
            midas.createNotice("Please select where you want to upload your files.", 4000, 'warning');
            return false;
        }
        midas.upload.simpleupload.swfu.startUpload();
    });
}

$('img#uploadAFile').show();
$('img#uploadAFileLoading').hide();

midas.upload.simpleupload.initHtml5FileUpload = function () {
    $('.progress-current').progressbar({value: 0});
    $('.progress-overall').progressbar({value: 0});

    var files = [],
        totalSize = 0,
        startByte = 0,
        currentIndex = 0,
        overallProgress = 0,
        lastProgress = 0,
        resumeUploadId = null,
        xhr = null;

    var _eatEvent = function (e) {
        e.stopPropagation();
        e.preventDefault();
    };

    /**
     * Helper function that begins the upload of the next file. This calls
     * _streamFileContents internally.
     */
    var _uploadNextFile = function () {
        if (currentIndex >= files.length) {
            // All files have finished
            $('.drop-zone').show();
            window.location.href = json.global.webroot+'/folder/' + $('.destinationId').val();
            return;
        }
        var file = files[currentIndex];
        // Initialize this upload
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: json.global.webroot+'/rest/system/uploadtoken?useSession=true' +
                '&filename=' + file.name + '&folderid=' + $('#destinationId').val()
        }).success(function (resp) {
            if (file.size > 0) {
                startByte = 0;
                _streamFileContents(resp.data.token);
            }
            else {
                // Empty file, so we are done
                currentIndex += 1;
                _uploadNextFile();
            }
        }).error(function (resp) {
            midas.createNotice('Error: ' + resp.error.msg, 4000, 'error');
        });
    };

    /**
     * Handle upload progress events from the XHR
     */
    var _uploadProgress = function (e) {
        if (!e.lengthComputable) {
            return;
        }

        if (startByte + e.loaded < lastProgress) {
            // This would happen from an error case, so we don't want
            // to render it as a progress event.
            return;
        }

        lastProgress = startByte + e.loaded;
        var file = files[currentIndex];

        $('.progress-current').progressbar('option', 'value',
            Math.ceil(100 * lastProgress / file.size));
        $('.progress-overall').progressbar('option', 'value',
            Math.ceil(100 * (overallProgress + e.loaded) / totalSize));
        $('.current-progress-message').html(
            'File ' + (currentIndex + 1) +' of ' +
            files.length + ' - ' + file.name + ': ' +
            midas.formatBytes(lastProgress) + ' / ' +
            midas.formatBytes(file.size));
        $('.overall-progress-message').html('Overall progress: ' +
            midas.formatBytes(overallProgress + e.loaded) + ' / ' +
            midas.formatBytes(totalSize));
    };

    /**
     * Upload errors will call this function to enable resume mode.
     */
    var _enableResumeMode = function () {
        $('.upload-error-message').html(
            ' ' +
            'The upload was interrupted. Click the ' +
            'Resume Upload button to continue.');
        $('.resume-upload').removeClass('disabled');
    };

    /**
     * Stream upload the contents of the current file
     */
    var _streamFileContents = function (uploadToken) {
        var file = files[currentIndex];
        var blob = file.slice(startByte);
        var url = json.global.webroot + '/api/rest?method=midas.upload.perform&uploadtoken=' +
            uploadToken + '&length=' + file.size + '&filename=' + (file.name || file.fileName);

        resumeUploadId = uploadToken;

        xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', _uploadProgress);
        xhr.addEventListener('load', function () {
            if (this.status == 200 || this.status == 201) {
                overallProgress += blob.size;
                currentIndex += 1;
                resumeUploadId = null;
                _uploadNextFile();
            }
            else {
                _enableResumeMode();
            }
        });
        xhr.addEventListener('error', function (e) {
            _enableResumeMode();
        });

        xhr.open('PUT', url, true);
        xhr.setRequestHeader('Content-Type', 'application/octet-stream');
        xhr.setRequestHeader('X-File-Name', file.name || file.fileName);
        xhr.setRequestHeader('X-File-Size', blob.size);
        xhr.setRequestHeader('X-File-Type', file.type);

        xhr.send(blob);
    };

    /**
     * Called when the file selection changes.
     */
    var filesChanged = function () {
        var retVal = midas.doCallback('CALLBACK_CORE_VALIDATE_UPLOAD', {
            files: files
        });
        $.each(retVal, function(module, resp) {
            if(resp.status === false) {
                $('div.uploadValidationError b').html(resp.message);
                $('div.uploadValidationError').show();
            }
        });

        $('.resume-upload').addClass('disabled');

        if (files.length === 0) {
            $('.upload-progress-message').text('No files selected');
            $('#startUploadLink').addClass('disabled');
        }
        else {
            totalSize = 0;
            $.each(files, function (i, file) {
                totalSize += file.size;
            });
            $('.overall-progress-message').html(' Selected ' + files.length +
                ' files (' + midas.formatBytes(totalSize) + ') -- Press start.');
            $('#startUploadLink').removeClass('disabled');
            $('.progress-overall,.progress-current').addClass('hide');
            $('.current-progress-message').empty();
            $('.upload-error-message').empty();
        }
    };

    $('.drop-zone').click(function () {
        $('#upload-files').click();
    }).on('dragover', _eatEvent)
      .on('dragenter', _eatEvent)
      .on('drop', function (e) {
        _eatEvent(e);

        files = e.originalEvent.dataTransfer.files;
        filesChanged();
    });

    $('#upload-files').change(function (e) {
        _eatEvent(e);
        files = this.files;
        filesChanged();
    });

    $('#startUploadLink').click(function (e) {
        if($(this).hasClass('disabled')) {
            return;
        }
        if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0) {
            midas.createNotice("Please select where you want to upload your files.", 4000, 'warning');
            return false;
        }
        $(this).addClass('disabled');
        $('.drop-zone').hide();
        $('.progress-overall,.progress-current').removeClass('hide');
        $('.upload-error-message').empty();

        currentIndex = 0;
        overallProgress = 0;
        lastProgress = 0;
        resumeUploadId = null;
        _uploadNextFile();
    });

    $('.resume-upload').click(function (e) {
        if($(this).hasClass('disabled')) {
            return;
        }
        $(this).addClass('disabled');
        $('.upload-error-message').empty();

        // Get the offset from the server
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: Routing.generate('upload_offset', {
                uploadToken: resumeUploadId
            }, true)
        }).success(function (resp) {
            startByte = resp.offset;
            overallProgress += startByte;
            _streamFileContents(resumeUploadId);
        }).error(function (resp) {
            midas.createNotice("An error occurred when getting the upload offset.", 4000, 'error');
            console.log(resp);
        });
    });
};

$('.uploadTabs').tabs({
    ajaxOptions: {
        beforeSend: function () {
            $('div.MainDialogLoading').show();
        },
        success: function () {
            $('div.MainDialogLoading').hide();
            $(".uploadTabs").show();
        },
        error: function (xhr, status, index, anchor) {
            $(anchor.hash).html("Couldn't load this tab. ");
        }
    }
});

$('.uploadTabs').show();
$('#linkForm').ajaxForm(function () {
    $('.uploadedLinks').val(parseInt($('.uploadedLinks').val()) + 1);
});

if($.browser.msie) {
    $('#swfuploadContent').show();
    $('#jqueryFileUploadContent').hide();
    midas.upload.simpleupload.initSwfupload();
}
else {
    $('#swfuploadContent').hide();
    $('#jqueryFileUploadContent').show();
    midas.upload.simpleupload.initHtml5FileUpload();
}

$('.browseMIDASLink').click(function () {
    midas.loadDialog("select", "/browse/selectfolder/?policy=write");
    midas.showDialog('Select upload destination');
});

if($('#destinationId').val()) {
    $('#startUploadLink').removeAttr('disabled');
}

midas.registerCallback('CALLBACK_CORE_UPLOAD_FOLDER_CHANGED', 'core', function () {
    $('#startUploadLink').removeAttr('disabled');
});

midas.doCallback('CALLBACK_CORE_SIMPLEUPLOAD_LOADED');

<commit_msg>BUG: refs #1052. Fix small progress reporting bug<commit_after>var midas = midas || {};
midas.upload = midas.upload || {};
midas.upload.simpleupload = {};

// We use shockwave flash uploader for IE (no multi-file upload support)
midas.upload.simpleupload.initSwfupload = function () {
    // Callback hook for the flash uploader
    midas.upload.simpleupload.uploadPreStart = function (file) {
        midas.upload.simpleupload.swfu.setPostParams({
            'sid': $('.sessionId').val(),
            'parent': $('#destinationId').val(),
            'license': $('select[name=licenseSelect]').val()
        });
    }
    var settings = {
        flash_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp10/swfupload.swf",
        flash9_url: json.global.coreWebroot+"/public/js/swfupload/swfupload_fp9/swfupload_fp9.swf",
        upload_url: json.global.webroot+"/upload/saveuploaded",
        post_params: {
            'sid': $('.sessionId').val(),
            'parent': $('#destinationId').val(),
            'license': $('select[name=licenseSelect]').val()
        },
        file_size_limit: $('.maxSizeFile').val()+" MB",
        file_types: "*.*",
        file_types_description: "All Files",
        file_upload_limit: 100,
        file_queue_limit: 0,
        custom_settings: {
            progressTarget: "fsUploadProgress",
            cancelButtonId: "btnCancel",
            pageObj: midas.upload.simpleupload
        },
        debug: false,

        // Button settings
        button_image_url: json.global.coreWebroot+"/public/js/swfupload/images/Button_65x29.png",
        button_width: "65",
        button_height: "20",
        button_placeholder_id: "spanButtonPlaceHolder",
        button_text: ''+$('.buttonBrowse').val()+'',
        button_text_style: ".theFont { font-size: 12; }",
        button_text_left_padding: 5,
        button_text_top_padding: 0,

        // The event handler functions are defined in handlers.js
        swfupload_preload_handler: preLoad,
        swfupload_load_failed_handler: loadFailed,
        file_queued_handler: fileQueued,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialogComplete,
        upload_start_handler: midas.upload.simpleupload.uploadPreStart,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccess,
        upload_complete_handler: uploadComplete,
        queue_complete_handler: queueComplete  // Queue plugin event
    };

    $('#swfuploadContent').show();
    midas.upload.simpleupload.swfu = new SWFUpload(settings);

    $('#startUploadLink').click(function () {
        if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0) {
            midas.createNotice("Please select where you want to upload your files.", 4000, 'warning');
            return false;
        }
        midas.upload.simpleupload.swfu.startUpload();
    });
}

$('img#uploadAFile').show();
$('img#uploadAFileLoading').hide();

midas.upload.simpleupload.initHtml5FileUpload = function () {
    $('.progress-current').progressbar({value: 0});
    $('.progress-overall').progressbar({value: 0});

    var files = [],
        totalSize = 0,
        startByte = 0,
        currentIndex = 0,
        overallProgress = 0,
        lastProgress = 0,
        resumeUploadId = null,
        xhr = null;

    var _eatEvent = function (e) {
        e.stopPropagation();
        e.preventDefault();
    };

    /**
     * Helper function that begins the upload of the next file. This calls
     * _streamFileContents internally.
     */
    var _uploadNextFile = function () {
        if (currentIndex >= files.length) {
            // All files have finished
            $('.drop-zone').show();
            window.location.href = json.global.webroot+'/folder/' + $('.destinationId').val();
            return;
        }
        var file = files[currentIndex];
        // Initialize this upload
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: json.global.webroot+'/rest/system/uploadtoken?useSession=true' +
                '&filename=' + file.name + '&folderid=' + $('#destinationId').val()
        }).success(function (resp) {
            if (file.size > 0) {
                startByte = 0;
                lastProgress = 0;
                _streamFileContents(resp.data.token);
            }
            else {
                // Empty file, so we are done
                currentIndex += 1;
                _uploadNextFile();
            }
        }).error(function (resp) {
            midas.createNotice('Error: ' + resp.error.msg, 4000, 'error');
        });
    };

    /**
     * Handle upload progress events from the XHR
     */
    var _uploadProgress = function (e) {
        if (!e.lengthComputable) {
            return;
        }

        if (startByte + e.loaded < lastProgress) {
            // This would happen from an error case, so we don't want
            // to render it as a progress event.
            return;
        }

        lastProgress = startByte + e.loaded;
        var file = files[currentIndex];

        $('.progress-current').progressbar('option', 'value',
            Math.ceil(100 * lastProgress / file.size));
        $('.progress-overall').progressbar('option', 'value',
            Math.ceil(100 * (overallProgress + e.loaded) / totalSize));
        $('.current-progress-message').html(
            'File ' + (currentIndex + 1) +' of ' +
            files.length + ' - ' + file.name + ': ' +
            midas.formatBytes(lastProgress) + ' / ' +
            midas.formatBytes(file.size));
        $('.overall-progress-message').html('Overall progress: ' +
            midas.formatBytes(overallProgress + e.loaded) + ' / ' +
            midas.formatBytes(totalSize));
    };

    /**
     * Upload errors will call this function to enable resume mode.
     */
    var _enableResumeMode = function () {
        $('.upload-error-message').html(
            ' ' +
            'The upload was interrupted. Click the ' +
            'Resume Upload button to continue.');
        $('.resume-upload').removeClass('disabled');
    };

    /**
     * Stream upload the contents of the current file
     */
    var _streamFileContents = function (uploadToken) {
        var file = files[currentIndex];
        var blob = file.slice(startByte);
        var url = json.global.webroot + '/api/rest?method=midas.upload.perform&uploadtoken=' +
            uploadToken + '&length=' + file.size + '&filename=' + (file.name || file.fileName);

        resumeUploadId = uploadToken;

        xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', _uploadProgress);
        xhr.addEventListener('load', function () {
            if (this.status == 200 || this.status == 201) {
                overallProgress += blob.size;
                currentIndex += 1;
                resumeUploadId = null;
                _uploadNextFile();
            }
            else {
                _enableResumeMode();
            }
        });
        xhr.addEventListener('error', function (e) {
            _enableResumeMode();
        });

        xhr.open('PUT', url, true);
        xhr.setRequestHeader('Content-Type', 'application/octet-stream');
        xhr.setRequestHeader('X-File-Name', file.name || file.fileName);
        xhr.setRequestHeader('X-File-Size', blob.size);
        xhr.setRequestHeader('X-File-Type', file.type);

        xhr.send(blob);
    };

    /**
     * Called when the file selection changes.
     */
    var filesChanged = function () {
        var retVal = midas.doCallback('CALLBACK_CORE_VALIDATE_UPLOAD', {
            files: files
        });
        $.each(retVal, function(module, resp) {
            if(resp.status === false) {
                $('div.uploadValidationError b').html(resp.message);
                $('div.uploadValidationError').show();
            }
        });

        $('.resume-upload').addClass('disabled');

        if (files.length === 0) {
            $('.upload-progress-message').text('No files selected');
            $('#startUploadLink').addClass('disabled');
        }
        else {
            totalSize = 0;
            $.each(files, function (i, file) {
                totalSize += file.size;
            });
            $('.overall-progress-message').html(' Selected ' + files.length +
                ' files (' + midas.formatBytes(totalSize) + ') -- Press start.');
            $('#startUploadLink').removeClass('disabled');
            $('.progress-overall,.progress-current').addClass('hide');
            $('.current-progress-message').empty();
            $('.upload-error-message').empty();
        }
    };

    $('.drop-zone').click(function () {
        $('#upload-files').click();
    }).on('dragover', _eatEvent)
      .on('dragenter', _eatEvent)
      .on('drop', function (e) {
        _eatEvent(e);

        files = e.originalEvent.dataTransfer.files;
        filesChanged();
    });

    $('#upload-files').change(function (e) {
        _eatEvent(e);
        files = this.files;
        filesChanged();
    });

    $('#startUploadLink').click(function (e) {
        if($(this).hasClass('disabled')) {
            return;
        }
        if($('#destinationId').val() == undefined || $('#destinationId').val().length == 0) {
            midas.createNotice("Please select where you want to upload your files.", 4000, 'warning');
            return false;
        }
        $(this).addClass('disabled');
        $('.drop-zone').hide();
        $('.progress-overall,.progress-current').removeClass('hide');
        $('.upload-error-message').empty();

        currentIndex = 0;
        overallProgress = 0;
        lastProgress = 0;
        resumeUploadId = null;
        _uploadNextFile();
    });

    $('.resume-upload').click(function (e) {
        if($(this).hasClass('disabled')) {
            return;
        }
        $(this).addClass('disabled');
        $('.upload-error-message').empty();

        // Get the offset from the server
        $.ajax({
            dataType: 'json',
            type: 'GET',
            url: Routing.generate('upload_offset', {
                uploadToken: resumeUploadId
            }, true)
        }).success(function (resp) {
            startByte = resp.offset;
            overallProgress += startByte;
            _streamFileContents(resumeUploadId);
        }).error(function (resp) {
            midas.createNotice("An error occurred when getting the upload offset.", 4000, 'error');
            console.log(resp);
        });
    });
};

$('.uploadTabs').tabs({
    ajaxOptions: {
        beforeSend: function () {
            $('div.MainDialogLoading').show();
        },
        success: function () {
            $('div.MainDialogLoading').hide();
            $(".uploadTabs").show();
        },
        error: function (xhr, status, index, anchor) {
            $(anchor.hash).html("Couldn't load this tab. ");
        }
    }
});

$('.uploadTabs').show();
$('#linkForm').ajaxForm(function () {
    $('.uploadedLinks').val(parseInt($('.uploadedLinks').val()) + 1);
});

if($.browser.msie) {
    $('#swfuploadContent').show();
    $('#jqueryFileUploadContent').hide();
    midas.upload.simpleupload.initSwfupload();
}
else {
    $('#swfuploadContent').hide();
    $('#jqueryFileUploadContent').show();
    midas.upload.simpleupload.initHtml5FileUpload();
}

$('.browseMIDASLink').click(function () {
    midas.loadDialog("select", "/browse/selectfolder/?policy=write");
    midas.showDialog('Select upload destination');
});

if($('#destinationId').val()) {
    $('#startUploadLink').removeAttr('disabled');
}

midas.registerCallback('CALLBACK_CORE_UPLOAD_FOLDER_CHANGED', 'core', function () {
    $('#startUploadLink').removeAttr('disabled');
});

midas.doCallback('CALLBACK_CORE_SIMPLEUPLOAD_LOADED');

<|endoftext|>


<commit_before>
  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,1,1,1,1,0,0,0]],
     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,2,0,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,1,1,1,1,1,1,1,1,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],
     3:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,3,3,3,3,3,3,3,0,0],
          [0,0,3,3,3,3,3,3,3,0,0],
          [0,2,2,2,2,2,2,2,2,2,0],
          [0,2,1,1,1,1,1,1,1,2,0],
          [1,0,1,1,1,1,1,1,1,0,0],
          [1,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]]};

//This is the positioning of the elements in the game

  var spriteData = {
    //Zelda Alien 1 = Octorok
    'alien1': { sx: 0,  sy: 0,  w: 32, h: 30, cls: Alien, frames: 2 },
    'alien2': { sx: 64,  sy: 0, w: 36, h: 26, cls: Alien, frames: 2 },
    'triforce': { sx: 137,  sy: 0,  w: 43, h: 37, cls: BossAlien,frames: 0},
    'player': { sx: 0,  sy: 30, w: 25, h: 37, cls: Player },
    'missile': { sx: 0,  sy: 67, w: 7,  h: 15, cls: Missile },
    'missile2': { sx: 6,  sy: 68, w: 8,  h: 8, cls: Missile },
  }

  function startGame() {
    var screen = new GameScreen("Alien Invaders","press space to start",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
    Game.loop();
    GameAudio.play('start');
  }

  function endGame() {
    var screen = new GameScreen("Game Over","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     score = 0;
                                     document.getElementById('score').innerHTML=" : " + score;

                                 });
    Game.loadBoard(screen);
  }

    function winGame() {
    var screen = new GameScreen("You Win!","(press space to restart)",                              // This represents what is shown when you beat all 3 levels and win the game

                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     score = 0;
                                     document.getElementById('score').innerHTML=" : " + score;
                                 });
    Game.loadBoard(screen);
  }

//This is the function that controls the sounds for firing and kills
//Could add enemy firing by adding another line of code 'fire2' : 'media/laser2.wav', etc.
//Added rare spawn sound and death

  $(function() {
    GameAudio.load({ 'fire' : 'media/laser.wav', 'die' : 'media/explosion.wav', 'start' : 'media/nes-intro.mp3', 'bossfire' : 'media/hit-triforce.wav' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<commit_msg>A few changes to sprites<commit_after>
  var levelData = {
     1:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,1,1,1,1,1,0,0,0]],
     2:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,2,2,2,2,2,2,0,0,0],
          [0,0,1,1,1,1,1,1,0,0,0],
          [0,0,1,1,1,1,1,1,0,0,0],
          [0,0,1,1,1,1,1,1,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]],
     3:  [[0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,0,0,0,0,0,0,0,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,1,1,1,1,1,1,1,0,0],
          [0,0,0,0,0,0,0,0,0,0,0]]};

//This is the positioning of the elements in the game

  var spriteData = {
    //Zelda Alien 1 = Octorok
    'alien1': { sx: 0,  sy: 0,  w: 32, h: 30, cls: Alien, frames: 2 },
    'alien2': { sx: 64,  sy: 0, w: 36, h: 26, cls: Alien, frames: 2 },
    'triforce': { sx: 137,  sy: 0,  w: 43, h: 37, cls: BossAlien,frames: 0},
    'player': { sx: 0,  sy: 30, w: 25, h: 37, cls: Player },
    'missile': { sx: 0,  sy: 67, w: 7,  h: 15, cls: Missile },
    'missile2': { sx: 6,  sy: 68, w: 8,  h: 8, cls: Missile },
  }

  function startGame() {
    var screen = new GameScreen("Alien Invaders","press space to start",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                 });
    Game.loadBoard(screen);
    Game.loop();
    GameAudio.play('start');
  }

  function endGame() {
    var screen = new GameScreen("Game Over","(press space to restart)",
                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     score = 0;
                                     document.getElementById('score').innerHTML=" : " + score;

                                 });
    Game.loadBoard(screen);
  }

    function winGame() {
    var screen = new GameScreen("You Win!","(press space to restart)",                              // This represents what is shown when you beat all 3 levels and win the game

                                 function() {
                                     Game.loadBoard(new GameBoard(1));
                                     score = 0;
                                     document.getElementById('score').innerHTML=" : " + score;
                                 });
    Game.loadBoard(screen);
  }

//This is the function that controls the sounds for firing and kills
//Could add enemy firing by adding another line of code 'fire2' : 'media/laser2.wav', etc.
//Added rare spawn sound and death

  $(function() {
    GameAudio.load({ 'fire' : 'media/laser.wav', 'die' : 'media/explosion.wav', 'start' : 'media/nes-intro.mp3', 'bossfire' : 'media/hit-triforce.wav' },
                   function() {
                       Game.initialize("#gameboard", levelData, spriteData,
                                      { "start": startGame,
                                        "die"  : endGame,
                                        "win"  : winGame });
                   });
   });

<|endoftext|>


<commit_before>// require("InputValidator");
// require("ArrayAugments");

/*
 * Provides an input list component.
 *
 * @param type Input type. (e.g. "checkbox", "radio", "text") (required)
 * @param values Option values. (required)
 * @param onChange Function called when the selection changes. (required)
 * @param name Button name. (required for radio)
 * @param idFunction Function which returns the id for a value. Defaults to simply return the value. (optional)
 * @param labelFunction Function which returns the label for a value. Defaults to simply return the value. (optional)
 * @param initialValues Initial values. (optional)
 * @param panelClass Panel class. (optional)
 * @param clientProps Client properties. (optional)
 */
var InputPanel = React.createClass(
{
    render: function()
    {
        this.validateProps();

        var inputProps = this.createInputProps();
        var selectedIds = this.determineSelectedIds();
        var values = this.props.values;
        var rows = [];

        values.forEach(function(value)
        {
            rows.push(this.createRow(rows.length, value, inputProps, selectedIds));
        }, this);

        return React.DOM.table(
        {
            className: this.props.panelClass,
        }, React.DOM.tbody({}, rows));
    },

    createInputProps: function()
    {
        var answer =
        {
            name: this.props.name, // needed for radio
            onChange: this.props.onChange,
            type: this.props.type,
        };

        var clientProps = this.props.clientProps;

        if (clientProps)
        {
            Object.getOwnPropertyNames(clientProps).forEach(function(key)
            {
                answer[key] = clientProps[key];
            });
        }

        return answer;
    },

    createRow: function(key, value, inputProps, selectedIds)
    {
        var idFunction = this.props.idFunction;
        var id = String(idFunction ? idFunction(value) : value);
        var labelFunction = this.props.labelFunction;
        var label = String(labelFunction ? labelFunction(value) : value);

        inputProps.id = id;

        var type = this.props.type;

        if (type === "checkbox" || type === "radio")
        {
            inputProps.defaultChecked = selectedIds.vizziniContains(id);
        }
        else if (type === "text")
        {
            inputProps.defaultValue = this.props.initialValues[id];
        }

        var input = React.DOM.input(inputProps);
        var cells = [];

        if (type === "checkbox" || type === "radio")
        {
            cells.push(React.DOM.td(
            {
                key: cells.length,
            }, React.DOM.label({}, input, " ", label)));
        }
        else if (type === "text")
        {
            cells.push(React.DOM.td(
            {
                key: cells.length,
            }, label));
            cells.push(React.DOM.td(
            {
                key: cells.length,
            }, input));
        }

        return React.DOM.tr(
        {
            key: key,
        }, cells);
    },

    determineSelectedIds: function()
    {
        var answer;
        var type = this.props.type;
        var idFunction = this.props.idFunction;

        if (type === "checkbox")
        {
            var values = this.props.initialValues;

            answer = values.map(function(value)
            {
                return String(idFunction ? idFunction(value) : value);
            });
        }
        else if (type === "radio")
        {
            var value = this.props.initialValues;
            var id = String(idFunction ? idFunction(value) : value);
            answer = [ id ];
        }

        return answer;
    },

    validateProps: function()
    {
        InputValidator.validateNotNull("type", this.props.type);

        var values = this.props.values;
        InputValidator.validateNotEmpty("values", values);

        InputValidator.validateNotNull("onChange", this.props.onChange);

        if (this.props.type === "radio")
        {
            InputValidator.validateNotNull("name", this.props.name);
        }
    }
});
<commit_msg>Changed to accommodate React components as labels.<commit_after>// require("InputValidator");
// require("ArrayAugments");

/*
 * Provides an input list component.
 *
 * @param type Input type. (e.g. "checkbox", "radio", "text") (required)
 * @param values Option values. (required)
 * @param onChange Function called when the selection changes. (required)
 * @param name Button name. (required for radio)
 * @param idFunction Function which returns the id for a value. Defaults to simply return the value. (optional)
 * @param labelFunction Function which returns the label for a value. Defaults to simply return the value. (optional)
 * @param initialValues Initial values. (optional)
 * @param panelClass Panel class. (optional)
 * @param clientProps Client properties. (optional)
 */
var InputPanel = React.createClass(
{
    render: function()
    {
        this.validateProps();

        var inputProps = this.createInputProps();
        var selectedIds = this.determineSelectedIds();
        var values = this.props.values;
        var rows = [];

        values.forEach(function(value)
        {
            rows.push(this.createRow(rows.length, value, inputProps, selectedIds));
        }, this);

        return React.DOM.table(
        {
            className: this.props.panelClass,
        }, React.DOM.tbody({}, rows));
    },

    createInputProps: function()
    {
        var answer =
        {
            name: this.props.name, // needed for radio
            onChange: this.props.onChange,
            type: this.props.type,
        };

        var clientProps = this.props.clientProps;

        if (clientProps)
        {
            Object.getOwnPropertyNames(clientProps).forEach(function(key)
            {
                answer[key] = clientProps[key];
            });
        }

        return answer;
    },

    createRow: function(key, value, inputProps, selectedIds)
    {
        var idFunction = this.props.idFunction;
        var id = String(idFunction ? idFunction(value) : value);
        var labelFunction = this.props.labelFunction;
        var label = (labelFunction ? labelFunction(value) : value);

        inputProps.id = id;

        var type = this.props.type;

        if (type === "checkbox" || type === "radio")
        {
            inputProps.defaultChecked = selectedIds.vizziniContains(id);
        }
        else if (type === "text")
        {
            inputProps.defaultValue = this.props.initialValues[id];
        }

        var input = React.DOM.input(inputProps);
        var cells = [];

        if (type === "checkbox" || type === "radio")
        {
            cells.push(React.DOM.td(
            {
                key: cells.length,
            }, React.DOM.label({}, input, " ", label)));
        }
        else if (type === "text")
        {
            cells.push(React.DOM.td(
            {
                key: cells.length,
            }, label));
            cells.push(React.DOM.td(
            {
                key: cells.length,
            }, input));
        }

        return React.DOM.tr(
        {
            key: key,
        }, cells);
    },

    determineSelectedIds: function()
    {
        var answer;
        var type = this.props.type;
        var idFunction = this.props.idFunction;

        if (type === "checkbox")
        {
            var values = this.props.initialValues;

            answer = values.map(function(value)
            {
                return String(idFunction ? idFunction(value) : value);
            });
        }
        else if (type === "radio")
        {
            var value = this.props.initialValues;
            var id = String(idFunction ? idFunction(value) : value);
            answer = [ id ];
        }

        return answer;
    },

    validateProps: function()
    {
        InputValidator.validateNotNull("type", this.props.type);

        var values = this.props.values;
        InputValidator.validateNotEmpty("values", values);

        InputValidator.validateNotNull("onChange", this.props.onChange);

        if (this.props.type === "radio")
        {
            InputValidator.validateNotNull("name", this.props.name);
        }
    }
});
<|endoftext|>


<commit_before>toolbarController = function () {
    var //Support
        isPopup = function() {
            return window.location.href.indexOf(data.currentMetadata().paths.popup) > -1;
        },
        wireListeners = function() {
            pubsub.subscribe('action.open', function(topic, payload) { open(payload); });
            pubsub.subscribe('action.minimize', function() { close(false); });
            pubsub.subscribe('action.close', function() { close(true); });
            pubsub.subscribe('action.popout', popout);
            pubsub.subscribe('state.final', checkPopout);
            pubsub.subscribe('state.build.shell.modify', wireDomListeners);
            pubsub.subscribe('state.build.rendered', restore);
        },
        wireDomListeners = function() {
            elements.scope.find('.glimpse-open').click(function () { pubsub.publish('action.open', false); return false; });
            elements.scope.find('.glimpse-minimize').click(function () { pubsub.publish('action.minimize'); return false; });
            elements.scope.find('.glimpse-close').click(function () { pubsub.publish('action.close'); return false; });
            elements.scope.find('.glimpse-popout').click(function () { pubsub.publish('action.popout'); return false; });

            if (settings.popupOn) {
                if (isPopup()) {
                    $(window).resize(function () {
                        elements.holder.find('.glimpse-panel').height($(window).height() - 54);
                    });
                }
                $(window).unload(closePopup);
            }
        },
        openPopup = function () {
            settings.popupOn = true;
            pubsub.publish('state.persist');

            util.cookie('glimpseKeepPopup', '1');

            //TODO !!!! This needs to be updated once we get going !!!!
            var path = data.currentMetadata().paths.popup,
                url = path + (path.indexOf('?') > -1 ? '&' : '?') + 'requestId=' + data.current().requestId;
            window.open(url, 'GlimpsePopup', 'width=1100,height=600,status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes');
        },

        //Main
        open = function (shortCircuitSlide) {
            settings.open = true;
            pubsub.publish('state.persist');

            elements.opener.hide();
            $.fn.add.call(elements.holder, elements.spacer).show().animate({ height : settings.height }, (shortCircuitSlide ? 0 : 'fast'));
        },
        close = function (remove, suppressPersist) {
            if (!suppressPersist) {
                settings.open = false;
                pubsub.publish('state.persist');
            }

            var panelElements = $.fn.add.call(elements.holder, elements.spacer).animate({ height : '0' }, 'fast', function() {
                    panelElements.hide();

                    if (remove) {
                        elements.scope.remove();
                        pubsub.publish('state.terminate');
                    }
                    else
                        elements.opener.show();
                });
        },
        popout = function () {
            openPopup();

            close(false, true);
        },
        checkPopout = function () {
            var pResult = isPopup();
            if (pResult)
                util.cookie('glimpseKeepPopup', '');

            if (settings.open && settings.popupOn && !pResult)
                openPopup();
        },
        closePopup = function () {
            if (isPopup() && !util.cookie('glimpseKeepPopup')) {
                settings.popupOn = false;
                pubsub.publish('state.persist');
            }
            else
                util.cookie('glimpseKeepPopup', null);
        },
        restore = function () {
            var key = settings.activeTab,
                opened = settings.open,
                popupOn = settings.popupOn,
                tab = elements.tabHolder.find('.glimpse-tab[data-glimpseKey="' + key + '"]');

            if (tab.length == 0 || tab.hasClass('glimpse-disabled'))
                key = elements.tabHolder.find('.glimpse-tab:not(.glimpse-disabled):first').attr('data-glimpseKey');

            pubsub.publish('action.tab.select', key);

            if (opened && !popupOn)
                pubsub.publish('action.open', true);
        },
        init = function () {
            wireListeners();
        };

    init();
} ()<commit_msg>Remove old comment<commit_after>toolbarController = function () {
    var //Support
        isPopup = function() {
            return window.location.href.indexOf(data.currentMetadata().paths.popup) > -1;
        },
        wireListeners = function() {
            pubsub.subscribe('action.open', function(topic, payload) { open(payload); });
            pubsub.subscribe('action.minimize', function() { close(false); });
            pubsub.subscribe('action.close', function() { close(true); });
            pubsub.subscribe('action.popout', popout);
            pubsub.subscribe('state.final', checkPopout);
            pubsub.subscribe('state.build.shell.modify', wireDomListeners);
            pubsub.subscribe('state.build.rendered', restore);
        },
        wireDomListeners = function() {
            elements.scope.find('.glimpse-open').click(function () { pubsub.publish('action.open', false); return false; });
            elements.scope.find('.glimpse-minimize').click(function () { pubsub.publish('action.minimize'); return false; });
            elements.scope.find('.glimpse-close').click(function () { pubsub.publish('action.close'); return false; });
            elements.scope.find('.glimpse-popout').click(function () { pubsub.publish('action.popout'); return false; });

            if (settings.popupOn) {
                if (isPopup()) {
                    $(window).resize(function () {
                        elements.holder.find('.glimpse-panel').height($(window).height() - 54);
                    });
                }
                $(window).unload(closePopup);
            }
        },
        openPopup = function () {
            settings.popupOn = true;
            pubsub.publish('state.persist');

            util.cookie('glimpseKeepPopup', '1');

            var path = data.currentMetadata().paths.popup,
                url = path + (path.indexOf('?') > -1 ? '&' : '?') + 'requestId=' + data.current().requestId;
            window.open(url, 'GlimpsePopup', 'width=1100,height=600,status=no,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes');
        },

        //Main
        open = function (shortCircuitSlide) {
            settings.open = true;
            pubsub.publish('state.persist');

            elements.opener.hide();
            $.fn.add.call(elements.holder, elements.spacer).show().animate({ height : settings.height }, (shortCircuitSlide ? 0 : 'fast'));
        },
        close = function (remove, suppressPersist) {
            if (!suppressPersist) {
                settings.open = false;
                pubsub.publish('state.persist');
            }

            var panelElements = $.fn.add.call(elements.holder, elements.spacer).animate({ height : '0' }, 'fast', function() {
                    panelElements.hide();

                    if (remove) {
                        elements.scope.remove();
                        pubsub.publish('state.terminate');
                    }
                    else
                        elements.opener.show();
                });
        },
        popout = function () {
            openPopup();

            close(false, true);
        },
        checkPopout = function () {
            var pResult = isPopup();
            if (pResult)
                util.cookie('glimpseKeepPopup', '');

            if (settings.open && settings.popupOn && !pResult)
                openPopup();
        },
        closePopup = function () {
            if (isPopup() && !util.cookie('glimpseKeepPopup')) {
                settings.popupOn = false;
                pubsub.publish('state.persist');
            }
            else
                util.cookie('glimpseKeepPopup', null);
        },
        restore = function () {
            var key = settings.activeTab,
                opened = settings.open,
                popupOn = settings.popupOn,
                tab = elements.tabHolder.find('.glimpse-tab[data-glimpseKey="' + key + '"]');

            if (tab.length == 0 || tab.hasClass('glimpse-disabled'))
                key = elements.tabHolder.find('.glimpse-tab:not(.glimpse-disabled):first').attr('data-glimpseKey');

            pubsub.publish('action.tab.select', key);

            if (opened && !popupOn)
                pubsub.publish('action.open', true);
        },
        init = function () {
            wireListeners();
        };

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