<commit_before>import {Motion} from 'react-motion';
import React, {Component} from 'react';

class SceneNavigator extends Component{
    constructor(props) {
        super(props);
        var {stateContext: {state, data, url}} = props.stateNavigator;
        this.state = {scenes: {[url]: state.renderScene(data)}};
    }
    componentDidMount() {
        var {stateNavigator} = this.props;
        stateNavigator.onNavigate(() => {
            this.setState((prevState) => {
                var {stateContext: {state, data, url, crumbs}} = stateNavigator;
                var scenes = {[url]: state.renderScene(data)};
                for(var i = 0; i < crumbs.length; i++) {
                    scenes[crumbs[i].url] = prevState.scenes[crumbs[i].url];
                }
                return {scenes};
            });
        });
    }
    render() {
        var {stateContext: {state, url, crumbs}} = this.props.stateNavigator;
        var {startStyle, endStyle, style} = this.props;
        var sceneContexts = crumbs.concat({state, url});
        var scenes = sceneContexts.map((sceneContext, i) => {
            var {component: Scene, props} = this.state.scenes[sceneContext.url];
            var last = sceneContexts.length === i + 1;
            return (
                <Motion key={sceneContext.url}
                    defaultStyle={getStyle(sceneContext.state.startStyle, startStyle)}
                    style={getStyle(sceneContext.state.endStyle, endStyle(last))}>
                    {(interpolatingStyle) =>

                            <Scene {...props} />

                    }
                </Motion>
            );
        });
        return
{scenes}
;
    }
}

function getStyle(overrideStyle, style) {
    return overrideStyle ? overrideStyle(style) : style;
}

export default SceneNavigator;
<commit_msg>Set last/show during concat instead of calculating<commit_after>import {Motion} from 'react-motion';
import React, {Component} from 'react';

class SceneNavigator extends Component{
    constructor(props) {
        super(props);
        var {stateContext: {state, data, url}} = props.stateNavigator;
        this.state = {scenes: {[url]: state.renderScene(data)}};
    }
    componentDidMount() {
        var {stateNavigator} = this.props;
        stateNavigator.onNavigate(() => {
            this.setState((prevState) => {
                var {stateContext: {state, data, url, crumbs}} = stateNavigator;
                var scenes = {[url]: state.renderScene(data)};
                for(var i = 0; i < crumbs.length; i++) {
                    scenes[crumbs[i].url] = prevState.scenes[crumbs[i].url];
                }
                return {scenes};
            });
        });
    }
    render() {
        var {stateContext: {state, url, crumbs}} = this.props.stateNavigator;
        var {startStyle, endStyle, style} = this.props;
        var scenes = crumbs.concat({state, url, show: true}).map((sceneContext) => {
            var {component: Scene, props} = this.state.scenes[sceneContext.url];
            return (
                <Motion key={sceneContext.url}
                    defaultStyle={getStyle(sceneContext.state.startStyle, startStyle)}
                    style={getStyle(sceneContext.state.endStyle, endStyle(!!sceneContext.show))}>
                    {(interpolatingStyle) =>

                            <Scene {...props} />

                    }
                </Motion>
            );
        });
        return
{scenes}
;
    }
}

function getStyle(overrideStyle, style) {
    return overrideStyle ? overrideStyle(style) : style;
}

export default SceneNavigator;
<|endoftext|>


<commit_before>var globalInputs = [
    'Rata estimari',
    'Rata fluctuatii personal',
    'Resurse materiale'
];

var globalOutputs = [
    'Timp',
    'Cost'
    ];

var parametersPercent = [];
var coeficients = [];
var timeChanges = [];

var globalTimeFields = [1];

var globalParametersOutputInfluenceTime = [1, -1, 1];
var globalParametersOutputInfluenceCost = [-1, -1, 1];

var globalUsedParameters;

var globalInputVar = 0;

var globalReferences = [];

var computeDenCoeficient = 1;

function addNewTimeField() {
    var position = globalTimeFields.length + 1;
    globalTimeFields.push(position);

    var content1 = "
<input data-prev='" + (position - 1) + "' data-next='" + (position + 1) + "' class='validate[required,custom[number],min[1],funcCall[verificareTimpMaxim]] form-control' type='text' id='time_" + (position) + "' placeholder='Timp'>
	";
    $("#time_input").append(content1);
    var content2 = "
<input data-prev='" + (position - 1) + "' data-next='" + (position + 1) + "' class='validate[required,custom[number],min[0],max[200]] form-control' type='text' id='percent_" + (position) + "' placeholder='%'>
	";
    $("#percent_input").append(content2);
}

function generateInputsFields() {
    var i = 1;
    generateNewParameterButton();
    globalInputs.forEach(function (input) {
        renderInput(i, input);
        renderSelect(i++, input);
    });
    i = 1;
    globalOutputs.forEach(function (label) {
        renderOutputSelect(i++, label);
    });
    renderInputTitle();

}

function renderInput(position, label) {
    var content = "
" + label + ":
<input type='text' name='parametru_" + position + "' id='parametru_" + position + "' class='validate[required,custom[number],min[1],max[99],funcCall[testSumaProcente]] form-control'>%

";
    $('#parameter').append(content);
}

function renderInputTitle() {
    var content = "
Nume parametru
Pondere

";
    $('#parameter_first').prepend(content);
}

function renderSelect(position, label) {
    var content = "<option value='" + position + "'>" + label + "</option>";
    $("#parameters").append(content);
}

function renderOutputSelect(position, label) {
    var content = "<option value='" + position + "'>" + label + "</option>";
    $("#output").append(content);
}

function renderOptionSelectInput(position, label) {
    $(".chzn-select").trigger("chosen:updated");

}

function generateNewParameterButton() {
    var content = "

 Adauga paramentru nou

<input class='form-control' placeholder='Nume parametru' type='text' id='new_parameter' />

";
    $('#parameter_btn').append(content);
}

function addNewParameter(input) {
    var new_parameter = $('#new_parameter ').val();
    if (!new_parameter) {
        alert('Completeaza numele noului parametru ');
        return false;
    }
    globalInputs.push(new_parameter);
    renderInput(globalInputs.length, new_parameter);
    renderSelect(globalInputs.length, new_parameter);
    renderOptionSelectInput(globalInputs.length, new_parameter);
    var timeInfluence = parseInput('new_parameter_time');
    var costInfluence = parseInput('new_parameters_cost');
    globalParametersOutputInfluenceTime.push(timeInfluence);
    globalParametersOutputInfluenceCost.push(costInfluence);
    $('#new_parameter ').val('');
    return false;
}

function testSumaProcente(field, rules, i, options) {
    "use strict";
    var param_max_sum = 100;
    var result = 0;
    var ok = true;
    for (var i = 1; i <= globalInputs.length; i++) {
        var partial = parseInput("parametru_" + i);
        if (!partial) {
            ok = false;
            break;
        } else {
            result += partial;
        }
    }
    if (ok)
        if (result != param_max_sum) {
            return 'Suma procentelor trebuie sa fie 100!';
        }
}

function verificareTimpMaxim(field, rules, i, options) {
    "use strict";
    var timpMax = $("#timp_stabilit").val();
    var camp = field.val();
    timpMax = timpMax ? timpMax : 0;
    camp = camp ? camp : 0;

    timpMax = parseInt(timpMax);
    camp = parseInt(camp);
    if (timpMax == 0) {
        return 'Completati mai intai campul Timp stabilit!';
    }
    if (timpMax < camp) {
        return 'Timpul selectat trebuie sa fie mai mic decat: ' + timpMax;
    }
}

function verificarePerioadaTimp(field, rules, i, options) {
    "use strict";
    var data_prev = field.attr('data - prev ');
    var prevTime = $("#time_" + data_prev).val();
    var time = field.val();

    prevTime = prevTime ? prevTime : 0;
    time = time ? time : 0;

    prevTime = parseInt(prevTime);
    time = parseInt(time);
    if (prevTime > time) {
        return 'Aceasta valoare trebuie sa fie mai mare decat: ' + prevTime;
    }
}

function verificareCompletare(field, rules, i, options) {
    "use strict";
    var data_next = field.attr('data-next');
    var time = field.val();
    var i = parseInt(data_next);
    i = i - 1;
    if (time != "")
        $("#time_" + data_next).attr({
            'disabled': false
        });
    else if (time == "" || $("#time_" + i).attr('disabled ') == "true")
        $("#time_" + data_next).attr({
            'disabled': true
        });
    return i;
}

function generateNewChartLog() {
    "use strict";
    var timpStabilit = parseInput('timp_stabilit');
    var costStabilit = parseInput('cost_stabilit');
    var output = getOutput();
    var input = getInput();

    setGlobalInput(input - 1);

    var coeficient = 1;
    var pConstant = 10000 * coeficient / timpStabilit;
    var interval = timpStabilit / 500;
    var initConstant = pConstant;

    getInputParameters();
    getTimeChanges();
    setInitialCoeficients();

    var data = [];
    var lastR = 0;
    for (var i = 0; i <= timpStabilit; i += interval) {
        lastR = Math.sqrt(i * coeficient);
        data.push([i, lastR]);
    }

    var maxValue = data[data.length - 1][1];
    var test = 100 / maxValue;

    data.forEach(function (curent, index) {
        data[index][1] = data[index][1] * test;
    });
    var dataNew = [];
    var initialTime = 0;

    var lastTime = 0;
    for (var i = 0; i < globalTimeFields.length; i++) {
        for (var j = initialTime; j <= timeChanges[i][0][0]; j += interval) {
            lastR = Math.sqrt(j * coeficient);
            dataNew.push([j, lastR]);
        }
        lastTime = timeChanges[i][0][0];
        initialTime = timeChanges[i][0][0] + interval;
        changeParametersPercent(input, timeChanges[i][0][1]);
        computeDenCoeficient = timeChanges[i][0][0] / 10;
        coeficient = computeCoeficient();
        //console.log(coeficient);

    }

    var maxValue = dataNew[dataNew.length - 1][1];
    var test = 100 / maxValue;
    var currentValue = 0;

    dataNew.forEach(function (curent, index) {
        currentValue = dataNew[index][1] * test;
        if(currentValue <=101) {
            dataNew[index][1] = currentValue;
        }
        else {
            break;
        }
    });

    chart(globalInputs[input - 1], globalOutputs[output - 1], data, dataNew);
    return false;

}

function changeParametersPercent(input, value) {
    coeficients[input - 1] = value / 100;

}

function computeCoeficient() {
    changeReferences();
    var num = computeNum();
    var den = computeDen();
    return num / den;
}

function changeReferences() {

    var reference = timeChanges[globalInputVar][0][1] / 100;
    reference = globalParametersOutputInfluenceTime[globalInputVar] == 1 ? reference : 1 / reference;
    globalReferences[globalInputVar] = reference;
}

function computeNum() {
    var result = 0;
    parametersPercent.forEach(function (value, index) {
        result += parametersPercent[index] * globalParametersOutputInfluenceTime[index];
    });
    return result;
}

function computeDen() {
    return computeDenCoeficient;
}

function setGlobalInput(input) {
    globalInputVar = input;
}

function getInputParameters() {
    parametersPercent = [];
    globalInputs.forEach(function (value, index) {
        parametersPercent.push(parseInput("parametru_" + (index + 1)));
        globalReferences.push(1);
    });
}

function setInitialCoeficients() {
    for (i = 1; i <= globalInputs.length; i++) {
        coeficients.push(1);
    }
}

function getTimeChanges() {
    timeChanges = [];
    globalTimeFields.forEach(function (value, index) {
        timeChanges.push([[parseInput("time_" + value), parseInput("percent_" + value)]]);
    });
}

function getInput() {
    return parseInput('parameters');
}

function getOutput() {
    return parseInput('output');
}

function parseInput(selector) {
    var result = $('#' + selector).val();
    result = parseInt(result);
    return result ? result : 0;
}

function chart(labelInput, labelOuptut, data1, data2) {
    "use strict";

    $.plot($("#chart"), [

        {
            data: data1,
            label: "Grafic initial iesire: " + labelOuptut
        },
        {
            data: data2,
            label: "Grafic iesire " + labelOuptut + "
parametru modificat " + labelInput,
        }

    ], {
        clickable: true,
        hoverable: true,
        series: {
            lines: {
                show: true,
                fill: false,
                fillColor: {
                    colors: [
                        {
                            opacity: 0.5
                        },
                        {
                            opacity: 0.15
                        }
            ]
                }
            },
            points: {
                show: false
            }
        },
        legend: {
            position: "nw"
        },
        xaxis: {
            label: labelOuptut
        },
        yaxis: {
            label: 'Realizabilitate'
        },
        grid: {
            hoverable: true,
            clickable: true
        },
        tooltip: true,
        tooltipOpts: {
            content: "Timp: %x
 Realizabilitate: %y",
            shifts: {
                x: -60,
                y: 25
            }
        }
    });

}
/////////////////////////////////////////////////////////////

function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=500,left = 390,top = 50');");
}<commit_msg>fix chart generation<commit_after>
var globalInputs = [
    'Rata estimari',
    'Rata fluctuatii personal',
    'Resurse materiale'
];

var globalOutputs = [
    'Timp',
    'Cost'
    ];

var parametersPercent = [];
var coeficients = [];
var timeChanges = [];

var globalTimeFields = [1];

var globalParametersOutputInfluenceTime = [1, -1, 1];
var globalParametersOutputInfluenceCost = [-1, -1, 1];

var globalInputVar = 0;

var globalReferences = [];

var computeDenCoeficient = 1;

function addNewTimeField() {
    var position = globalTimeFields.length + 1;
    globalTimeFields.push(position);

    var content1 = "
<input data-prev='" + (position - 1) + "' data-next='" + (position + 1) + "' class='validate[required,custom[number],min[1],funcCall[verificareTimpMaxim]] form-control' type='text' id='time_" + (position) + "' placeholder='Timp'>
	";
    $("#time_input").append(content1);
    var content2 = "
<input data-prev='" + (position - 1) + "' data-next='" + (position + 1) + "' class='validate[required,custom[number],min[0],max[200]] form-control' type='text' id='percent_" + (position) + "' placeholder='%'>
	";
    $("#percent_input").append(content2);
}

function generateInputsFields() {
    var i = 1;
    generateNewParameterButton();
    globalInputs.forEach(function (input) {
        renderInput(i, input);
        renderSelect(i++, input);
    });
    i = 1;
    globalOutputs.forEach(function (label) {
        renderOutputSelect(i++, label);
    });
    renderInputTitle();

}

function renderInput(position, label) {
    var content = "
" + label + ":
<input type='text' name='parametru_" + position + "' id='parametru_" + position + "' class='validate[required,custom[number],min[1],max[99],funcCall[testSumaProcente]] form-control'>%

";
    $('#parameter').append(content);
}

function renderInputTitle() {
    var content = "
Nume parametru
Pondere

";
    $('#parameter_first').prepend(content);
}

function renderSelect(position, label) {
    var content = "<option value='" + position + "'>" + label + "</option>";
    $("#parameters").append(content);
}

function renderOutputSelect(position, label) {
    var content = "<option value='" + position + "'>" + label + "</option>";
    $("#output").append(content);
}

function renderOptionSelectInput(position, label) {
    $(".chzn-select").trigger("chosen:updated");

}

function generateNewParameterButton() {
    var content = "

 Adauga paramentru nou

<input class='form-control' placeholder='Nume parametru' type='text' id='new_parameter' />

";
    $('#parameter_btn').append(content);
}

function addNewParameter(input) {
    var new_parameter = $('#new_parameter ').val();
    if (!new_parameter) {
        alert('Completeaza numele noului parametru ');
        return false;
    }
    globalInputs.push(new_parameter);
    renderInput(globalInputs.length, new_parameter);
    renderSelect(globalInputs.length, new_parameter);
    renderOptionSelectInput(globalInputs.length, new_parameter);
    var timeInfluence = parseInput('new_parameter_time');
    var costInfluence = parseInput('new_parameters_cost');
    globalParametersOutputInfluenceTime.push(timeInfluence);
    globalParametersOutputInfluenceCost.push(costInfluence);
    $('#new_parameter ').val('');
    return false;
}

function testSumaProcente(field, rules, i, options) {
    "use strict";
    var param_max_sum = 100;
    var result = 0;
    var ok = true;
    for (var i = 1; i <= globalInputs.length; i++) {
        var partial = parseInput("parametru_" + i);
        if (!partial) {
            ok = false;
            break;
        } else {
            result += partial;
        }
    }
    if (ok)
        if (result != param_max_sum) {
            return 'Suma procentelor trebuie sa fie 100!';
        }
}

function verificareTimpMaxim(field, rules, i, options) {
    "use strict";
    var timpMax = $("#timp_stabilit").val();
    var camp = field.val();
    timpMax = timpMax ? timpMax : 0;
    camp = camp ? camp : 0;

    timpMax = parseInt(timpMax);
    camp = parseInt(camp);
    if (timpMax == 0) {
        return 'Completati mai intai campul Timp stabilit!';
    }
    if (timpMax < camp) {
        return 'Timpul selectat trebuie sa fie mai mic decat: ' + timpMax;
    }
}

function verificarePerioadaTimp(field, rules, i, options) {
    "use strict";
    var data_prev = field.attr('data - prev ');
    var prevTime = $("#time_" + data_prev).val();
    var time = field.val();

    prevTime = prevTime ? prevTime : 0;
    time = time ? time : 0;

    prevTime = parseInt(prevTime);
    time = parseInt(time);
    if (prevTime > time) {
        return 'Aceasta valoare trebuie sa fie mai mare decat: ' + prevTime;
    }
}

function verificareCompletare(field, rules, i, options) {
    "use strict";
    var data_next = field.attr('data-next');
    var time = field.val();
    var i = parseInt(data_next);
    i = i - 1;
    if (time != "")
        $("#time_" + data_next).attr({
            'disabled': false
        });
    else if (time == "" || $("#time_" + i).attr('disabled ') == "true")
        $("#time_" + data_next).attr({
            'disabled': true
        });
    return i;
}

function generateNewChartLog() {
    "use strict";
    var timpStabilit = parseInput('timp_stabilit');
    var costStabilit = parseInput('cost_stabilit');
    var output = getOutput();
    var input = getInput();

    setGlobalInput(input - 1);

    var coeficient = 1;
    var pConstant = 10000 * coeficient / timpStabilit;
    var interval = timpStabilit / 500;
    var initConstant = pConstant;

    getInputParameters();
    getTimeChanges();
    setInitialCoeficients();

    var data = [];
    var lastR = 0;
    for (var i = 0; i <= timpStabilit; i += interval) {
        lastR = Math.sqrt(i * coeficient);
        data.push([i, lastR]);
    }

    var maxValue = data[data.length - 1][1];
    var test = 100 / maxValue;

    data.forEach(function (curent, index) {
        data[index][1] = data[index][1] * test;
    });
    var dataNew = [];
    var initialTime = 0;

    var lastTime = 0;
    for (var i = 0; i < globalTimeFields.length; i++) {
        for (var j = initialTime; j <= timeChanges[i][0][0]; j += interval) {
            lastR = Math.sqrt(j * coeficient);
            dataNew.push([j, lastR]);
        }
        lastTime = timeChanges[i][0][0];
        initialTime = timeChanges[i][0][0] + interval;
        changeParametersPercent(input, timeChanges[i][0][1]);
        computeDenCoeficient = timeChanges[i][0][0] / 10;
        coeficient = computeCoeficient();
        //console.log(coeficient);

    }

    var maxValue = dataNew[dataNew.length - 1][1];
    var test = 100 / maxValue;
    var currentValue = 0;

    dataNew.forEach(function (curent, index) {
        currentValue = dataNew[index][1] * test;
    });

    chart(globalInputs[input - 1], globalOutputs[output - 1], data, dataNew);
    return false;

}

function changeParametersPercent(input, value) {
    coeficients[input - 1] = value / 100;

}

function computeCoeficient() {
    changeReferences();
    var num = computeNum();
    var den = computeDen();
    return num / den;
}

function changeReferences() {

    var reference = timeChanges[globalInputVar][0][1] / 100;
    reference = globalParametersOutputInfluenceTime[globalInputVar] == 1 ? reference : 1 / reference;
    globalReferences[globalInputVar] = reference;
}

function computeNum() {
    var result = 0;
    parametersPercent.forEach(function (value, index) {
        result += parametersPercent[index] * globalParametersOutputInfluenceTime[index];
    });
    return result;
}

function computeDen() {
    return computeDenCoeficient;
}

function setGlobalInput(input) {
    globalInputVar = input;
}

function getInputParameters() {
    parametersPercent = [];
    globalInputs.forEach(function (value, index) {
        parametersPercent.push(parseInput("parametru_" + (index + 1)));
        globalReferences.push(1);
    });
}

function setInitialCoeficients() {
    for (i = 1; i <= globalInputs.length; i++) {
        coeficients.push(1);
    }
}

function getTimeChanges() {
    timeChanges = [];
    globalTimeFields.forEach(function (value, index) {
        timeChanges.push([[parseInput("time_" + value), parseInput("percent_" + value)]]);
    });
}

function getInput() {
    return parseInput('parameters');
}

function getOutput() {
    return parseInput('output');
}

function parseInput(selector) {
    var result = $('#' + selector).val();
    result = parseInt(result);
    return result ? result : 0;
}

function chart(labelInput, labelOuptut, data1, data2) {
    "use strict";

    $.plot($("#chart"), [

        {
            data: data1,
            label: "Grafic initial iesire: " + labelOuptut
        },
        {
            data: data2,
            label: "Grafic iesire " + labelOuptut + "
parametru modificat " + labelInput,
        }

    ], {
        clickable: true,
        hoverable: true,
        series: {
            lines: {
                show: true,
                fill: false,
                fillColor: {
                    colors: [
                        {
                            opacity: 0.5
                        },
                        {
                            opacity: 0.15
                        }
            ]
                }
            },
            points: {
                show: false
            }
        },
        legend: {
            position: "nw"
        },
        xaxis: {
            label: labelOuptut
        },
        yaxis: {
            label: 'Realizabilitate'
        },
        grid: {
            hoverable: true,
            clickable: true
        },
        tooltip: true,
        tooltipOpts: {
            content: "Timp: %x
 Realizabilitate: %y",
            shifts: {
                x: -60,
                y: 25
            }
        }
    });

}
/////////////////////////////////////////////////////////////

function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=500,height=500,left = 390,top = 50');");
}<|endoftext|>


<commit_before>/**
 * Toolkit JavaScript
 */

// Tabs
function Tabs (tab) {
  this.tabsItem = tab;

  this.displayTabs = function (active) {
    var tabsContent = this.tabsItem.querySelectorAll('[data-tabs-content]');

    tabsContent.forEach(function (t) {
        t.style.display = t.getAttribute('id') !== active.dataset.tab ? 'none': '';
    });
  }.bind(this);

  this.showTab = function (e) {
    e.preventDefault();

    var siblings = Array.prototype.filter.call(e.target.parentNode.children, function(child) {
      return child !== e.target;
    });

    // Hide other tabs
    siblings.forEach(function (i) {
      i.classList.remove('active')
    });

    e.target.classList.add('active');
    this.displayTabs(e.target);
  }.bind(this);

  var links = this.tabsItem.querySelectorAll('a');
  var active = this.tabsItem.querySelector('.active') || this.tabsItem.querySelector('.tabs-header-link')[0];
  active.classList.add('active');

  // Run first time
  this.displayTabs(active);

  // Bind links
  for(var link of links) {
    link.addEventListener('click', this.showTab);
  }
}

// Initialize Tabs
var tabs = document.querySelectorAll('[data-tabs]');

for (var tab of tabs) {
  new Tabs(tab);
}

<commit_msg>fix tabs auto-select first tab<commit_after>/**
 * Toolkit JavaScript
 */

// Tabs
function Tabs (tab) {
  this.tabsItem = tab;

  this.displayTabs = function (active) {
    var tabsContent = this.tabsItem.querySelectorAll('[data-tabs-content]');

    tabsContent.forEach(function (t) {
        t.style.display = t.getAttribute('id') !== active.dataset.tab ? 'none': '';
    });
  }.bind(this);

  this.showTab = function (e) {
    e.preventDefault();

    var siblings = Array.prototype.filter.call(e.target.parentNode.children, function(child) {
      return child !== e.target;
    });

    // Hide other tabs
    siblings.forEach(function (i) {
      i.classList.remove('active')
    });

    e.target.classList.add('active');
    this.displayTabs(e.target);
  }.bind(this);

  var links = this.tabsItem.querySelectorAll('a');
  var active = this.tabsItem.querySelector('.active') || this.tabsItem.querySelector('.tabs-header-link');
  active.classList.add('active');

  // Run first time
  this.displayTabs(active);

  // Bind links
  for(var link of links) {
    link.addEventListener('click', this.showTab);
  }
}

// Initialize Tabs
var tabs = document.querySelectorAll('[data-tabs]');

for (var tab of tabs) {
  new Tabs(tab);
}

<|endoftext|>


<commit_before>function hijackConnection(original, type) {
  return function () {
    var self = this;
    var args = Array.prototype.slice.call(arguments);

    // if this comes from a Method.call we don't need to track it
    var isFromCall = Zone.fromCall.get();

    if(!isFromCall && args.length) {
      var callback = args[args.length - 1];
      if(typeof callback === 'function') {
        var methodName = args[0];
        var methodArgs = args.slice(1, args.length - 1);
        var ownerInfo = {type: type, name: methodName, args: methodArgs};
        var zoneInfo = {type: type, name: methodName, args: methodArgs};
        zone.setInfo(type, zoneInfo);
        args[args.length - 1] = function (argument) {
          var args = Array.prototype.slice.call(arguments);
          return callback.apply(this, args);
        }
        args[args.length - 1] = zone.bind(args[args.length - 1], false, ownerInfo, pickAllArgs);
      }
    }

    if(type == "Meteor.call") {
      // make sure this won't get tracked another time
      return Zone.fromCall.withValue(true, function() {
        return original.apply(self, args);
      });
    } else {
      return original.apply(this, args);
    }
  }
}

function hijackSubscribe(originalFunction, type) {
  return function () {
    var args = Array.prototype.slice.call(arguments);
    if(args.length) {
      var callback = args[args.length - 1];
      var subName = args[0];
      var subArgs = args.slice(1, args.length - 1);
      if(typeof callback === 'function') {
        var ownerInfo = {type: type, name: subName, args: subArgs};
        var zoneInfo = {type: type, name: subName, args: subArgs};
        zone.setInfo(type, zoneInfo);
        args[args.length - 1] = function (argument) {
          var args = Array.prototype.slice.call(arguments);
          return callback.apply(this, args);
        }
        args[args.length - 1] = zone.bind(args[args.length - 1], false, ownerInfo, pickAllArgs);
      } else if(callback) {
        ['onReady', 'onError'].forEach(function (funName) {
          var ownerInfo = {type: type, name: subName, args: subArgs, callbackType: funName};
          if(typeof callback[funName] === "function") {
            var zoneInfo = {type: type, name: subName, args: subArgs, callbackType: funName};
            zone.setInfo(type, zoneInfo);
            callback[funName] = function (argument) {
              var args = Array.prototype.slice.call(arguments);
              return callback.apply(this, args);
            }
            callback[funName] = zone.bind(callback[funName], false, ownerInfo, pickAllArgs);
          }
        })
      }
    }
    return originalFunction.apply(this, args);
  }
}

function hijackCursor(Cursor) {

  hijackFunction('observe', [
    'added', 'addedAt', 'changed', 'changedAt',
    'removed', 'removedAt', 'movedTo'
  ]);

  hijackFunction('observeChanges', [
    'added', 'addedBefore', 'changed',
    'removed', 'movedBefore'
  ]);

  // hijack Cursor.fetch
  var originalCursorFetch = Cursor.fetch;
  Cursor.fetch = function () {
    var self = this;
    var args = Array.prototype.slice.call(arguments);
    var type = 'MongoCursor.fetch';
    if(zone && !this._avoidZones) {
      var zoneInfo = {type: type, collection: this.collection.name};
      zone.setInfo(type, zoneInfo)
    };
    return Zone.notFromForEach.withValue(true, function() {
      return originalCursorFetch.apply(self, args);
    });
  };

  ['forEach', 'map'].forEach(function (name) {
    var original = Cursor[name];
    Cursor[name] = function (callback, thisArg) {
      var self = thisArg || this;
      var args = Array.prototype.slice.call(arguments);
      var type = 'MongoCursor.' + name;
      var notFromForEach = Zone.notFromForEach.get();
      if(!this._avoidZones
        && !notFromForEach
        && typeof callback === 'function') {
        args[0] = function (doc, index) {
          var args = Array.prototype.slice.call(arguments);
          var ownerInfo = {type: type, collection: self.collection.name};
          var zoneInfo = {type: type, collection: self.collection.name, document: doc, index: index};
          zone.setInfo(type, zoneInfo);
          callback = zone.bind(callback, false, ownerInfo. pickAllArgs);
          return callback.apply(this, args);
        };
      }

      if(name !== 'forEach') {
        return Zone.notFromForEach.withValue(true, function() {
          return original.apply(self, args);
        });
      } else {
        return original.apply(self, args);
      }
    }
  });

  function hijackFunction(type, callbacks) {
    var original = Cursor[type];
    Cursor[type] = function (options) {
      var self = this;
      // check this request comes from an observer call
      // if so, we don't need to track this request
      var isFromObserve = Zone.fromObserve.get();

      if(!this._avoidZones && !isFromObserve && options) {
        callbacks.forEach(function (funName) {
          var callback = options[funName];
          if(typeof callback === 'function') {
            var ownerInfo = {
              type: 'MongoCursor.' + type,
              callbackType: funName,
              collection: self.collection.name
            };
            zone.setInfo(type, {
              type: 'MongoCursor.' + type,
              collection: self.collection.name
            });
            options[funName] = zone.bind(callback, false, ownerInfo, pickAllArgs);
          }
        });
      }

      if(type == 'observe') {
        // notify observeChanges to not to track again
        return Zone.fromObserve.withValue(true, function() {
          return original.call(self, options);
        });
      } else {
        return original.call(this, options);
      }
    };
  }
}

function hijackComponentEvents(original) {
  var type = 'Template.event';
  return function (dict) {
    var self = this;
    var name = this.__templateName || this.kind.split('_')[1];
    for (var target in dict) {
      dict[target] = prepareHandler(dict[target], target);
    }

    return original.call(this, dict);

    function prepareHandler(handler, target) {
      return function () {
        var args = Array.prototype.slice.call(arguments);
        var ownerInfo = {type: type, event: target, template: name};
        zone.owner = ownerInfo;
        handler.apply(this, args);
      };
    }

  }
}

function hijackDepsFlush(original, type) {
  return function () {
    var args = Array.prototype.slice.call(arguments);
    if(zone.owner && window.zone.owner.type == 'setTimeout') {
      zone.owner = {type: type};
    }
    return original.apply(this, args);
  }
}

function hijackSessionSet(original, type) {
  return function () {
    var args = Array.prototype.slice.call(arguments);
    zone.addEvent({type: type, key: args[0], value: args[1]});
    return original.apply(this, args);
  }
}

var TemplateCoreFunctions = ['prototype', '__makeView', '__render'];

function hijackTemplateHelpers(template, templateName) {
  _.each(template, function (hookFn, name) {
    template[name] = hijackHelper(hookFn, name, templateName);
  });
}

function hijackNewTemplateHelpers(original, templateName) {
  return function (dict) {
    dict && _.each(dict, function (hookFn, name) {
      dict[name] = hijackHelper(hookFn, name, templateName);
    });

    var args = Array.prototype.slice.call(arguments);
    return original.apply(this, args);
  }
}

function hijackHelper(hookFn, name, templateName) {
  if(hookFn
    && typeof hookFn === 'function'
    && _.indexOf(TemplateCoreFunctions, name) === -1) {
    // Assuming the value is a template helper
    return function () {
      var args = Array.prototype.slice.call(arguments);
      zone.setInfo('Template.helper', {name: name, template: templateName});
      var result = hookFn.apply(this, args);
      if(result && typeof result.observe === 'function') {
        result._avoidZones = true;
      }
      return result;
    }
  } else {
    return hookFn;
  }
}

function hijackGlobalHelpers(helpers) {
  var _ = Package.underscore._;
  _(helpers || {}).each(function (helperFn, name) {
    helpers[name] = hijackGlobalHelper(helperFn, name)
  });
}

function hijackNewGlobalHelpers (original) {
  return function (name, helperFn) {
    var args = Array.prototype.slice.call(arguments);
    args[1] = hijackGlobalHelper(helperFn, name);
    return original.apply(this, args);
  };
}

function hijackGlobalHelper(helperFn, name) {
  var _ = Package.underscore._;
  if(helperFn
    && typeof helperFn === 'function'
    && _.indexOf(TemplateCoreFunctions, name) === -1) {
    return function () {
      var args = Array.prototype.slice.call(arguments);
      zone.setInfo('Global.helper', {name: name});
      var result = helperFn.apply(this, args);
      if(result && typeof result.observe === 'function') {
        result._avoidZones = true;
      }
      return result;
    }
  } else {
    return helperFn;
  }
}

//--------------------------------------------------------------------------\\

var routerEvents = [
  'onRun', 'onData', 'onBeforeAction', 'onAfterAction', 'onStop', 'waitOn',
  'load', 'before', 'after', 'unload',
  'data', 'waitOn'
];

function hijackRouterConfigure(original, type) {
  return function (options) {
    var args = Array.prototype.slice.call(arguments);
    options && routerEvents.forEach(function (hookName) {
      var hookFn = options[hookName];
      if(typeof hookFn === 'function') {
        options[hookName] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hookFn.apply(this, args);
        }
      }
    });
    return original.apply(this, args);
  }
}

function hijackRouterGlobalHooks(Router, type) {
  routerEvents.forEach(function (hookName) {
    var hookFn = Router[hookName];
    /**
     * Example
     * Router.onBeforeAction( handler-function, options )
     */
    Router[hookName] = function (hook, options) {
      var args = Array.prototype.slice.call(arguments);
      var hook = args[0];
      if(hook && typeof hook === 'function') {
        // override hook function before sending to iron-router
        args[0] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hook.apply(this, args);
        }
      }
      return hookFn.apply(this, args);
    }
  });

  return Router;
}

function hijackRouterOptions(original, type) {
  return function (name, options) {
    var args = Array.prototype.slice.call(arguments);

    // hijack options
    options && routerEvents.forEach(function (hookName) {
      var hookFn = options[hookName];
      if(typeof hookFn === 'function') {
        options[hookName] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hookFn.apply(this, args);
        }
      }
    });

    return original.apply(this, args);
  }
}

function hijackRouteController(original, type) {
  return function (options) {
    var args = Array.prototype.slice.call(arguments);
    options && routerEvents.forEach(function (hookName) {
      var hookFn = options[hookName];
      if(typeof hookFn === 'function') {
        options[hookName] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hookFn.apply(this, args);
        }
      }
    });
    return original.apply(this, args);
  }
}

//--------------------------------------------------------------------------\\

var originalFunctions = [];
function backupOriginals(obj, methodNames) {
  if(obj && Array.isArray(methodNames)) {
    var backup = {obj: obj};
    backup.methods = {};
    methodNames.forEach(function (name) {
      backup.methods[name] = obj[name];
    });
    originalFunctions.push(backup);
  };
}

function restoreOriginals() {
  originalFunctions.forEach(function (backup) {
    for(var name in backup.methods) {
      backup.obj[name] = backup.methods[name];
    };
  });
}

function pickAllArgs(context, args) {
  return args;
}
<commit_msg>Add query to cursor methods info<commit_after>function hijackConnection(original, type) {
  return function () {
    var self = this;
    var args = Array.prototype.slice.call(arguments);

    // if this comes from a Method.call we don't need to track it
    var isFromCall = Zone.fromCall.get();

    if(!isFromCall && args.length) {
      var callback = args[args.length - 1];
      if(typeof callback === 'function') {
        var methodName = args[0];
        var methodArgs = args.slice(1, args.length - 1);
        var ownerInfo = {type: type, name: methodName, args: methodArgs};
        var zoneInfo = {type: type, name: methodName, args: methodArgs};
        zone.setInfo(type, zoneInfo);
        args[args.length - 1] = function (argument) {
          var args = Array.prototype.slice.call(arguments);
          return callback.apply(this, args);
        }
        args[args.length - 1] = zone.bind(args[args.length - 1], false, ownerInfo, pickAllArgs);
      }
    }

    if(type == "Meteor.call") {
      // make sure this won't get tracked another time
      return Zone.fromCall.withValue(true, function() {
        return original.apply(self, args);
      });
    } else {
      return original.apply(this, args);
    }
  }
}

function hijackSubscribe(originalFunction, type) {
  return function () {
    var args = Array.prototype.slice.call(arguments);
    if(args.length) {
      var callback = args[args.length - 1];
      var subName = args[0];
      var subArgs = args.slice(1, args.length - 1);
      if(typeof callback === 'function') {
        var ownerInfo = {type: type, name: subName, args: subArgs};
        var zoneInfo = {type: type, name: subName, args: subArgs};
        zone.setInfo(type, zoneInfo);
        args[args.length - 1] = function (argument) {
          var args = Array.prototype.slice.call(arguments);
          return callback.apply(this, args);
        }
        args[args.length - 1] = zone.bind(args[args.length - 1], false, ownerInfo, pickAllArgs);
      } else if(callback) {
        ['onReady', 'onError'].forEach(function (funName) {
          var ownerInfo = {type: type, name: subName, args: subArgs, callbackType: funName};
          if(typeof callback[funName] === "function") {
            var zoneInfo = {type: type, name: subName, args: subArgs, callbackType: funName};
            zone.setInfo(type, zoneInfo);
            callback[funName] = function (argument) {
              var args = Array.prototype.slice.call(arguments);
              return callback.apply(this, args);
            }
            callback[funName] = zone.bind(callback[funName], false, ownerInfo, pickAllArgs);
          }
        })
      }
    }
    return originalFunction.apply(this, args);
  }
}

function hijackCursor(Cursor) {

  hijackFunction('observe', [
    'added', 'addedAt', 'changed', 'changedAt',
    'removed', 'removedAt', 'movedTo'
  ]);

  hijackFunction('observeChanges', [
    'added', 'addedBefore', 'changed',
    'removed', 'movedBefore'
  ]);

  // hijack Cursor.fetch
  var originalCursorFetch = Cursor.fetch;
  Cursor.fetch = function () {
    var self = this;
    var args = Array.prototype.slice.call(arguments);
    var type = 'MongoCursor.fetch';
    if(zone && !this._avoidZones) {
      var collection = this.collection && this.collection.name;
      var query = this.matcher && this.matcher._selector;
      var zoneInfo = {type: type, collection: collection, query: query};
      zone.setInfo(type, zoneInfo)
    };
    return Zone.notFromForEach.withValue(true, function() {
      return originalCursorFetch.apply(self, args);
    });
  };

  ['forEach', 'map'].forEach(function (name) {
    var original = Cursor[name];
    Cursor[name] = function (callback, thisArg) {
      var self = thisArg || this;
      var args = Array.prototype.slice.call(arguments);
      var type = 'MongoCursor.' + name;
      var notFromForEach = Zone.notFromForEach.get();
      if(!this._avoidZones
        && !notFromForEach
        && typeof callback === 'function') {
        args[0] = function (doc, index) {
          var args = Array.prototype.slice.call(arguments);
          var collection = self.collection && self.collection.name;
          var query = self.matcher && self.matcher._selector;
          var ownerInfo = {type: type, collection: collection, query: query};
          var zoneInfo = {type: type, collection: collection, query: query, document: doc, index: index};
          zone.setInfo(type, zoneInfo);
          callback = zone.bind(callback, false, ownerInfo. pickAllArgs);
          return callback.apply(this, args);
        };
      }

      if(name !== 'forEach') {
        return Zone.notFromForEach.withValue(true, function() {
          return original.apply(self, args);
        });
      } else {
        return original.apply(self, args);
      }
    }
  });

  function hijackFunction(type, callbacks) {
    var original = Cursor[type];
    Cursor[type] = function (options) {
      var self = this;
      // check this request comes from an observer call
      // if so, we don't need to track this request
      var isFromObserve = Zone.fromObserve.get();

      if(!this._avoidZones && !isFromObserve && options) {
        callbacks.forEach(function (funName) {
          var callback = options[funName];
          if(typeof callback === 'function') {
            var ownerInfo = {
              type: 'MongoCursor.' + type,
              callbackType: funName,
              collection: self.collection.name
            };
            zone.setInfo(type, {
              type: 'MongoCursor.' + type,
              collection: self.collection.name
            });
            options[funName] = zone.bind(callback, false, ownerInfo, pickAllArgs);
          }
        });
      }

      if(type == 'observe') {
        // notify observeChanges to not to track again
        return Zone.fromObserve.withValue(true, function() {
          return original.call(self, options);
        });
      } else {
        return original.call(this, options);
      }
    };
  }
}

function hijackComponentEvents(original) {
  var type = 'Template.event';
  return function (dict) {
    var self = this;
    var name = this.__templateName || this.kind.split('_')[1];
    for (var target in dict) {
      dict[target] = prepareHandler(dict[target], target);
    }

    return original.call(this, dict);

    function prepareHandler(handler, target) {
      return function () {
        var args = Array.prototype.slice.call(arguments);
        var ownerInfo = {type: type, event: target, template: name};
        zone.owner = ownerInfo;
        handler.apply(this, args);
      };
    }

  }
}

function hijackDepsFlush(original, type) {
  return function () {
    var args = Array.prototype.slice.call(arguments);
    if(zone.owner && window.zone.owner.type == 'setTimeout') {
      zone.owner = {type: type};
    }
    return original.apply(this, args);
  }
}

function hijackSessionSet(original, type) {
  return function () {
    var args = Array.prototype.slice.call(arguments);
    zone.addEvent({type: type, key: args[0], value: args[1]});
    return original.apply(this, args);
  }
}

var TemplateCoreFunctions = ['prototype', '__makeView', '__render'];

function hijackTemplateHelpers(template, templateName) {
  _.each(template, function (hookFn, name) {
    template[name] = hijackHelper(hookFn, name, templateName);
  });
}

function hijackNewTemplateHelpers(original, templateName) {
  return function (dict) {
    dict && _.each(dict, function (hookFn, name) {
      dict[name] = hijackHelper(hookFn, name, templateName);
    });

    var args = Array.prototype.slice.call(arguments);
    return original.apply(this, args);
  }
}

function hijackHelper(hookFn, name, templateName) {
  if(hookFn
    && typeof hookFn === 'function'
    && _.indexOf(TemplateCoreFunctions, name) === -1) {
    // Assuming the value is a template helper
    return function () {
      var args = Array.prototype.slice.call(arguments);
      zone.setInfo('Template.helper', {name: name, template: templateName});
      var result = hookFn.apply(this, args);
      if(result && typeof result.observe === 'function') {
        result._avoidZones = true;
      }
      return result;
    }
  } else {
    return hookFn;
  }
}

function hijackGlobalHelpers(helpers) {
  var _ = Package.underscore._;
  _(helpers || {}).each(function (helperFn, name) {
    helpers[name] = hijackGlobalHelper(helperFn, name)
  });
}

function hijackNewGlobalHelpers (original) {
  return function (name, helperFn) {
    var args = Array.prototype.slice.call(arguments);
    args[1] = hijackGlobalHelper(helperFn, name);
    return original.apply(this, args);
  };
}

function hijackGlobalHelper(helperFn, name) {
  var _ = Package.underscore._;
  if(helperFn
    && typeof helperFn === 'function'
    && _.indexOf(TemplateCoreFunctions, name) === -1) {
    return function () {
      var args = Array.prototype.slice.call(arguments);
      zone.setInfo('Global.helper', {name: name});
      var result = helperFn.apply(this, args);
      if(result && typeof result.observe === 'function') {
        result._avoidZones = true;
      }
      return result;
    }
  } else {
    return helperFn;
  }
}

//--------------------------------------------------------------------------\\

var routerEvents = [
  'onRun', 'onData', 'onBeforeAction', 'onAfterAction', 'onStop', 'waitOn',
  'load', 'before', 'after', 'unload',
  'data', 'waitOn'
];

function hijackRouterConfigure(original, type) {
  return function (options) {
    var args = Array.prototype.slice.call(arguments);
    options && routerEvents.forEach(function (hookName) {
      var hookFn = options[hookName];
      if(typeof hookFn === 'function') {
        options[hookName] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hookFn.apply(this, args);
        }
      }
    });
    return original.apply(this, args);
  }
}

function hijackRouterGlobalHooks(Router, type) {
  routerEvents.forEach(function (hookName) {
    var hookFn = Router[hookName];
    /**
     * Example
     * Router.onBeforeAction( handler-function, options )
     */
    Router[hookName] = function (hook, options) {
      var args = Array.prototype.slice.call(arguments);
      var hook = args[0];
      if(hook && typeof hook === 'function') {
        // override hook function before sending to iron-router
        args[0] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hook.apply(this, args);
        }
      }
      return hookFn.apply(this, args);
    }
  });

  return Router;
}

function hijackRouterOptions(original, type) {
  return function (name, options) {
    var args = Array.prototype.slice.call(arguments);

    // hijack options
    options && routerEvents.forEach(function (hookName) {
      var hookFn = options[hookName];
      if(typeof hookFn === 'function') {
        options[hookName] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hookFn.apply(this, args);
        }
      }
    });

    return original.apply(this, args);
  }
}

function hijackRouteController(original, type) {
  return function (options) {
    var args = Array.prototype.slice.call(arguments);
    options && routerEvents.forEach(function (hookName) {
      var hookFn = options[hookName];
      if(typeof hookFn === 'function') {
        options[hookName] = function () {
          var args = Array.prototype.slice.call(arguments);
          zone.setInfo('irHook', {
            name: this.route && this.route.name,
            hook: hookName,
            path: this.path
          });
          return hookFn.apply(this, args);
        }
      }
    });
    return original.apply(this, args);
  }
}

//--------------------------------------------------------------------------\\

var originalFunctions = [];
function backupOriginals(obj, methodNames) {
  if(obj && Array.isArray(methodNames)) {
    var backup = {obj: obj};
    backup.methods = {};
    methodNames.forEach(function (name) {
      backup.methods[name] = obj[name];
    });
    originalFunctions.push(backup);
  };
}

function restoreOriginals() {
  originalFunctions.forEach(function (backup) {
    for(var name in backup.methods) {
      backup.obj[name] = backup.methods[name];
    };
  });
}

function pickAllArgs(context, args) {
  return args;
}
<|endoftext|>


<commit_before>/*
 * based on: iframeReizer.js
 * Author: David J. Bradshaw - dave@bradshaw.net
 * Contributor: Jure Mav - jure.mav@gmail.com
 * License: MIT, https://github.com/davidjbradshaw/iframe-resizer
 */
;
(function () {
  'use strict';

  // initialize only once after async load
  if (!window.atAppEmbedLoaded) {
    window.atAppEmbedLoaded = true;
  } else {
    return;
  }

  var
    count = 0,
    firstRun = true,
    msgHeader = 'message',
    msgHeaderLen = msgHeader.length,
    msgId = '[iFrameSizer]', //Must match iframe msg ID
    msgIdLen = msgId.length,
    page = '', //:'+location.href, //Uncoment to debug nested iFrames
    pagePosition = null,
    requestAnimationFrame = window.requestAnimationFrame,
    resetRequiredMethods = {
      max: 1,
      scroll: 1,
      bodyScroll: 1,
      documentElementScroll: 1
    },
    settings = {},

    defaults = {
      autoResize: true,
      bodyBackground: null,
      bodyMargin: null,
      bodyMarginV1: 8,
      bodyPadding: null,
      checkOrigin: true,
      enablePublicMethods: false,
      heightCalculationMethod: 'offset',
      interval: 32,
      log: false,
      maxHeight: Infinity,
      maxWidth: Infinity,
      minHeight: 0,
      minWidth: 0,
      scrolling: false,
      sizeHeight: true,
      sizeWidth: false,
      tolerance: 0,
      closedCallback: function () {},
      initCallback: function () {},
      messageCallback: function () {},
      resizedCallback: function () {}
    };

  function addEventListener(obj, evt, func) {
    if ('addEventListener' in window) {
      obj.addEventListener(evt, func, false);
    } else if ('attachEvent' in window) { //IE
      obj.attachEvent('on' + evt, func);
    }
  }

  function setupRequestAnimationFrame() {
    var
      vendors = ['moz', 'webkit', 'o', 'ms'],
      x;

    // Remove vendor prefixing if prefixed and break early if not
    for (x = 0; x < vendors.length && !requestAnimationFrame; x += 1) {
      requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    }

    if (!(requestAnimationFrame)) {
      log(' RequestAnimationFrame not supported');
    }
  }

  function log(msg) {
    if (settings.log && (typeof console === 'object')) {
      console.log(msgId + '[Host page' + page + ']' + msg);
    }
  }

  function iFrameListener(event) {
    function resizeIFrame() {
      function resize() {
        setSize(messageData);
        setPagePosition();
        settings.resizedCallback(messageData);
      }

      ensureInRange('Height');
      ensureInRange('Width');

      syncResize(resize, messageData, 'resetPage');
    }

    function closeIFrame(iframe) {
      var iframeID = iframe.id;

      log(' Removing iFrame: ' + iframeID);
      iframe.parentNode.removeChild(iframe);
      settings.closedCallback(iframeID);
      log(' --');
    }

    function processMsg() {
      var data = msg.substr(msgIdLen).split(':');

      return {
        iframe: document.getElementById(data[0]),
        id: data[0],
        height: data[1],
        width: data[2],
        type: data[3]
      };
    }

    function ensureInRange(Dimension) {
      var
        max = Number(settings['max' + Dimension]),
        min = Number(settings['min' + Dimension]),
        dimension = Dimension.toLowerCase(),
        size = Number(messageData[dimension]);

      if (min > max) {
        throw new Error('Value for min' + Dimension + ' can not be greater than max' + Dimension);
      }

      log(' Checking ' + dimension + ' is in range ' + min + '-' + max);

      if (size < min) {
        size = min;
        log(' Set ' + dimension + ' to min value');
      }

      if (size > max) {
        size = max;
        log(' Set ' + dimension + ' to max value');
      }

      messageData[dimension] = '' + size;
    }

    function isMessageFromIFrame() {

      var
        origin = event.origin,
        remoteHost = messageData.iframe.src.split('/').slice(0, 3).join('/');

      if (settings.checkOrigin) {
        log(' Checking connection is from: ' + remoteHost);

        if (('' + origin !== 'null') && (origin !== remoteHost)) {
          throw new Error(
            'Unexpected message received from: ' + origin +
            ' for ' + messageData.iframe.id +
            '. Message was: ' + event.data +
            '. This error can be disabled by adding the checkOrigin: false option.'
          );
        }
      }

      return true;
    }

    function isMessageForUs() {
      return msgId === ('' + msg).substr(0, msgIdLen); //''+Protects against non-string msg
    }

    function isMessageFromMetaParent() {
      //test if this message is from a parent above us. This is an ugly test, however, updating
      //the message format would break backwards compatibity.
      var retCode = messageData.type in {
        'true': 1,
        'false': 1
      };

      if (retCode) {
        log(' Ignoring init message from meta parent page');
      }

      return retCode;
    }

    function forwardMsgFromIFrame() {
      var msgBody = msg.substr(msg.indexOf(':') + msgHeaderLen + 6); //6 === ':0:0:' + ':' (Ideas to name this magic number most welcome)

      log(' MessageCallback passed: {iframe: ' + messageData.iframe.id + ', message: ' + msgBody + '}');
      settings.messageCallback({
        iframe: messageData.iframe,
        message: JSON.parse(msgBody)
      });
      log(' --');
    }

    function checkIFrameExists() {
      if (null === messageData.iframe) {
        throw new Error('iFrame (' + messageData.id + ') does not exist on ' + page);
      }
      return true;
    }

    function getIFramePosition() {
      var iFramePosition = messageData.iframe.getBoundingClientRect();

      getPagePosition();

      return {
        x: Number(iFramePosition.left) + Number(pagePosition.x),
        y: Number(iFramePosition.top) + Number(pagePosition.y)
      };
    }

    function scrollRequestFromChild(addOffset) {
      var offset = addOffset ? getIFramePosition() : {
        x: 0,
        y: 0
      };

      log(' Reposition requested from iFrame (offset x:' + offset.x + ' y:' + offset.y + ')');
      pagePosition = {
        x: Number(messageData.width) + offset.x,
        y: Number(messageData.height) + offset.y
      };
      setPagePosition();
    }

    function actionMsg() {
      switch (messageData.type) {
      case 'close':
        closeIFrame(messageData.iframe);
        settings.resizedCallback(messageData); //To be removed.
        break;
      case 'message':
        forwardMsgFromIFrame();
        break;
      case 'scrollTo':
        scrollRequestFromChild(false);
        break;
      case 'scrollToOffset':
        scrollRequestFromChild(true);
        break;
      case 'reset':
        resetIFrame(messageData);
        break;
      case 'init':
        resizeIFrame();
        settings.initCallback(messageData.iframe);
        break;
      default:
        resizeIFrame();
      }
    }

    var
      msg = event.data,
      messageData = {};

    if (isMessageForUs()) {
      log(' Received: ' + msg);
      messageData = processMsg();

      if (!isMessageFromMetaParent() && checkIFrameExists() && isMessageFromIFrame()) {
        actionMsg();
        firstRun = false;
      }
    }
  }

  function getPagePosition() {
    if (null === pagePosition) {
      pagePosition = {
        x: (window.pageXOffset !== undefined) ? window.pageXOffset : document.documentElement.scrollLeft,
        y: (window.pageYOffset !== undefined) ? window.pageYOffset : document.documentElement.scrollTop
      };
      log(' Get position: ' + pagePosition.x + ',' + pagePosition.y);
    }
  }

  function setPagePosition() {
    if (null !== pagePosition) {
      window.scrollTo(pagePosition.x, pagePosition.y);
      log(' Set position: ' + pagePosition.x + ',' + pagePosition.y);
      pagePosition = null;
    }
  }

  function resetIFrame(messageData) {
    function reset() {
      setSize(messageData);
      trigger('reset', 'reset', messageData.iframe);
    }

    log(' Size reset requested by ' + ('init' === messageData.type ? 'host page' : 'iFrame'));
    getPagePosition();
    syncResize(reset, messageData, 'init');
  }

  function setSize(messageData) {
    function setDimension(dimension) {
      messageData.iframe.style[dimension] = messageData[dimension] + 'px';
      log(
        ' IFrame (' + messageData.iframe.id +
        ') ' + dimension +
        ' set to ' + messageData[dimension] + 'px'
      );
    }

    if (settings.sizeHeight) {
      setDimension('height');
    }
    if (settings.sizeWidth) {
      setDimension('width');
    }
  }

  function syncResize(func, messageData, doNotSync) {
    if (doNotSync !== messageData.type && requestAnimationFrame) {
      log(' Requesting animation frame');
      requestAnimationFrame(func);
    } else {
      func();
    }
  }

  function trigger(calleeMsg, msg, iframe) {
    log('[' + calleeMsg + '] Sending msg to iframe (' + msg + ')');
    iframe.contentWindow.postMessage(msgId + msg, '*');
  }

  function setupIFrame() {
    function setLimits() {
      function addStyle(style) {
        if ((Infinity !== settings[style]) && (0 !== settings[style])) {
          iframe.style[style] = settings[style] + 'px';
          log(' Set ' + style + ' = ' + settings[style] + 'px');
        }
      }

      addStyle('maxHeight');
      addStyle('minHeight');
      addStyle('maxWidth');
      addStyle('minWidth');
    }

    function ensureHasId(iframeID) {
      if ('' === iframeID) {
        iframe.id = iframeID = 'iFrameResizer' + count++;
        log(' Added missing iframe ID: ' + iframeID + ' (' + iframe.src + ')');
      }

      return iframeID;
    }

    function setScrolling() {
      log(' IFrame scrolling ' + (settings.scrolling ? 'enabled' : 'disabled') + ' for ' + iframeID);
      iframe.style.overflow = false === settings.scrolling ? 'hidden' : 'auto';
      iframe.scrolling = false === settings.scrolling ? 'no' : 'yes';
    }

    //The V1 iFrame script expects an int, where as in V2 expects a CSS
    //string value such as '1px 3em', so if we have an int for V2, set V1=V2
    //and then convert V2 to a string PX value.
    function setupBodyMarginValues() {
      if (('number' === typeof (settings.bodyMargin)) || ('0' === settings.bodyMargin)) {
        settings.bodyMarginV1 = settings.bodyMargin;
        settings.bodyMargin = '' + settings.bodyMargin + 'px';
      }
    }

    function createOutgoingMsg() {
      return iframeID +
        ':' + settings.bodyMarginV1 +
        ':' + settings.sizeWidth +
        ':' + settings.log +
        ':' + settings.interval +
        ':' + settings.enablePublicMethods +
        ':' + settings.autoResize +
        ':' + settings.bodyMargin +
        ':' + settings.heightCalculationMethod +
        ':' + settings.bodyBackground +
        ':' + settings.bodyPadding +
        ':' + settings.tolerance;
    }

    function init(msg) {
      //We have to call trigger twice, as we can not be sure if all
      //iframes have completed loading when this code runs. The
      //event listener also catches the page changing in the iFrame.
      addEventListener(iframe, 'load', function () {
        var fr = firstRun; // Reduce scope of var to function, because IE8's JS execution
        // context stack is borked and this value gets externally
        // changed midway through running this function.
        trigger('iFrame.onload', msg, iframe);
        if (!fr && settings.heightCalculationMethod in resetRequiredMethods) {
          resetIFrame({
            iframe: iframe,
            height: 0,
            width: 0,
            type: 'init'
          });
        }
      });
      trigger('init', msg, iframe);
    }

    var
    /*jshint validthis:true */
      iframe = this,
      iframeID = ensureHasId(iframe.id);

    setScrolling();
    setLimits();
    setupBodyMarginValues();
    init(createOutgoingMsg());
  }

  function checkOptions(options) {
    if ('object' !== typeof options) {
      throw new TypeError('Options is not an object.');
    }
  }

  function createNativePublicFunction() {
    function init(element) {
      if ('IFRAME' !== element.tagName.toUpperCase()) {
        throw new TypeError('Expected <IFRAME> tag, found <' + element.tagName + '>.');
      } else {
        setupIFrame.call(element);
      }
    }

    function processOptions(options) {
      options = options || {};
      checkOptions(options);

      for (var option in defaults) {
        if (defaults.hasOwnProperty(option)) {
          settings[option] = options.hasOwnProperty(option) ? options[option] : defaults[option];
        }
      }
    }

    return function iFrameResizeF(options, selecter) {
      processOptions(options);
      Array.prototype.forEach.call(document.querySelectorAll(selecter || 'iframe'), init);
      window.iFrameResize.settings = settings;
    };
  }

  function createJQueryPublicMethod($) {
    $.fn.iFrameResize = function $iFrameResizeF(options) {
      options = options || {};
      checkOptions(options);
      settings = $.extend({}, defaults, options);
      return this.filter('iframe').each(setupIFrame).end();
    };
  }

  setupRequestAnimationFrame();
  addEventListener(window, 'message', iFrameListener);
  //window.addEventListener('message', iFrameListener.bind(this));

  if (window.jQuery) {
    createJQueryPublicMethod(jQuery);
  }

  if (typeof define === 'function' && define.amd) {
    define([], createNativePublicFunction);
  } else if (typeof exports === 'object') { //Node for browserfy
    module.exports = createNativePublicFunction();
  } else {
    window.iFrameResize = createNativePublicFunction();
  }

  // add IFrames to all div with class="at-app-embed"
  function createIFrames() {

    var ifs = document.getElementsByClassName("at-app-embed");
    for (var i = 0; i < ifs.length; i++) {
      createIFrameForDiv(ifs[i], i);
    }

    window.iFrameResize({
      log: false
    });

    for (var i = 0; i < ifs.length; i++) {
      var aae = document.getElementById("aae" + i);
      var url = aae.getAttribute("xsrc");
      var app = aae.getAttribute("xapp");

      if (i == 0) {
        window.iFrameResize.settings.boundIFrame = aae;

        var hash = window.location.hash || "";
        if (hash.indexOf("#!") == 0) {
          hash = hash.substr(2);
        } else if (hash.indexOf("#") == 0) {
          hash = hash.substr(1);
        }

        // if hash seems to be an app then replace default app
        if (hash.indexOf("/") > 0) {
          app = hash;
        }
      }

      if (app) {
        url += "#!" + app;
      }
      aae.src = url;
    }
  }

  window.onhashchange = function () {

    if (window.iFrameResize.settings.boundIFrame == undefined) return;
    var aae = window.iFrameResize.settings.boundIFrame;
    var url = aae.getAttribute("xsrc");
    var app = aae.getAttribute("xapp");

    var hash = window.location.hash || "";
    if (hash.indexOf("#!") == 0) {
      hash = hash.substr(2);
    } else if (hash.indexOf("#") == 0) {
      hash = hash.substr(1);
    }

    // if hash seems to be an app then replace default app
    if (hash.indexOf("/") > 0) {
      url += "#!" + hash;
      aae.src = url;
    }
  }

  function createIFrameForDiv(div, cntr) {
    var src = div.getAttribute("src") || "/components/at-app-embed-scaffold/at-app-embed.html";
    var app = div.getAttribute("app") || "";
    var iframe = document.createElement('iframe');
    iframe.id = "aae" + cntr;
    iframe.frameBorder = 0;
    iframe.width = "100%";
    iframe.scrolling = "no";
    iframe.setAttribute("xsrc", src);
    iframe.setAttribute("xapp", app);
    div.appendChild(iframe);
  }

  createIFrames();

})();<commit_msg>ignore jquery if existing in target page<commit_after>/*
 * based on: iframeReizer.js
 * Author: David J. Bradshaw - dave@bradshaw.net
 * Contributor: Jure Mav - jure.mav@gmail.com
 * License: MIT, https://github.com/davidjbradshaw/iframe-resizer
 */
;
(function () {
  'use strict';

  // initialize only once after async load
  if (!window.atAppEmbedLoaded) {
    window.atAppEmbedLoaded = true;
  } else {
    return;
  }

  var
    count = 0,
    firstRun = true,
    msgHeader = 'message',
    msgHeaderLen = msgHeader.length,
    msgId = '[iFrameSizer]', //Must match iframe msg ID
    msgIdLen = msgId.length,
    page = '', //:'+location.href, //Uncoment to debug nested iFrames
    pagePosition = null,
    requestAnimationFrame = window.requestAnimationFrame,
    resetRequiredMethods = {
      max: 1,
      scroll: 1,
      bodyScroll: 1,
      documentElementScroll: 1
    },
    settings = {},

    defaults = {
      autoResize: true,
      bodyBackground: null,
      bodyMargin: null,
      bodyMarginV1: 8,
      bodyPadding: null,
      checkOrigin: true,
      enablePublicMethods: false,
      heightCalculationMethod: 'offset',
      interval: 32,
      log: false,
      maxHeight: Infinity,
      maxWidth: Infinity,
      minHeight: 0,
      minWidth: 0,
      scrolling: false,
      sizeHeight: true,
      sizeWidth: false,
      tolerance: 0,
      closedCallback: function () {},
      initCallback: function () {},
      messageCallback: function () {},
      resizedCallback: function () {}
    };

  function addEventListener(obj, evt, func) {
    if ('addEventListener' in window) {
      obj.addEventListener(evt, func, false);
    } else if ('attachEvent' in window) { //IE
      obj.attachEvent('on' + evt, func);
    }
  }

  function setupRequestAnimationFrame() {
    var
      vendors = ['moz', 'webkit', 'o', 'ms'],
      x;

    // Remove vendor prefixing if prefixed and break early if not
    for (x = 0; x < vendors.length && !requestAnimationFrame; x += 1) {
      requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    }

    if (!(requestAnimationFrame)) {
      log(' RequestAnimationFrame not supported');
    }
  }

  function log(msg) {
    if (settings.log && (typeof console === 'object')) {
      console.log(msgId + '[Host page' + page + ']' + msg);
    }
  }

  function iFrameListener(event) {
    function resizeIFrame() {
      function resize() {
        setSize(messageData);
        setPagePosition();
        settings.resizedCallback(messageData);
      }

      ensureInRange('Height');
      ensureInRange('Width');

      syncResize(resize, messageData, 'resetPage');
    }

    function closeIFrame(iframe) {
      var iframeID = iframe.id;

      log(' Removing iFrame: ' + iframeID);
      iframe.parentNode.removeChild(iframe);
      settings.closedCallback(iframeID);
      log(' --');
    }

    function processMsg() {
      var data = msg.substr(msgIdLen).split(':');

      return {
        iframe: document.getElementById(data[0]),
        id: data[0],
        height: data[1],
        width: data[2],
        type: data[3]
      };
    }

    function ensureInRange(Dimension) {
      var
        max = Number(settings['max' + Dimension]),
        min = Number(settings['min' + Dimension]),
        dimension = Dimension.toLowerCase(),
        size = Number(messageData[dimension]);

      if (min > max) {
        throw new Error('Value for min' + Dimension + ' can not be greater than max' + Dimension);
      }

      log(' Checking ' + dimension + ' is in range ' + min + '-' + max);

      if (size < min) {
        size = min;
        log(' Set ' + dimension + ' to min value');
      }

      if (size > max) {
        size = max;
        log(' Set ' + dimension + ' to max value');
      }

      messageData[dimension] = '' + size;
    }

    function isMessageFromIFrame() {

      var
        origin = event.origin,
        remoteHost = messageData.iframe.src.split('/').slice(0, 3).join('/');

      if (settings.checkOrigin) {
        log(' Checking connection is from: ' + remoteHost);

        if (('' + origin !== 'null') && (origin !== remoteHost)) {
          throw new Error(
            'Unexpected message received from: ' + origin +
            ' for ' + messageData.iframe.id +
            '. Message was: ' + event.data +
            '. This error can be disabled by adding the checkOrigin: false option.'
          );
        }
      }

      return true;
    }

    function isMessageForUs() {
      return msgId === ('' + msg).substr(0, msgIdLen); //''+Protects against non-string msg
    }

    function isMessageFromMetaParent() {
      //test if this message is from a parent above us. This is an ugly test, however, updating
      //the message format would break backwards compatibity.
      var retCode = messageData.type in {
        'true': 1,
        'false': 1
      };

      if (retCode) {
        log(' Ignoring init message from meta parent page');
      }

      return retCode;
    }

    function forwardMsgFromIFrame() {
      var msgBody = msg.substr(msg.indexOf(':') + msgHeaderLen + 6); //6 === ':0:0:' + ':' (Ideas to name this magic number most welcome)

      log(' MessageCallback passed: {iframe: ' + messageData.iframe.id + ', message: ' + msgBody + '}');
      settings.messageCallback({
        iframe: messageData.iframe,
        message: JSON.parse(msgBody)
      });
      log(' --');
    }

    function checkIFrameExists() {
      if (null === messageData.iframe) {
        throw new Error('iFrame (' + messageData.id + ') does not exist on ' + page);
      }
      return true;
    }

    function getIFramePosition() {
      var iFramePosition = messageData.iframe.getBoundingClientRect();

      getPagePosition();

      return {
        x: Number(iFramePosition.left) + Number(pagePosition.x),
        y: Number(iFramePosition.top) + Number(pagePosition.y)
      };
    }

    function scrollRequestFromChild(addOffset) {
      var offset = addOffset ? getIFramePosition() : {
        x: 0,
        y: 0
      };

      log(' Reposition requested from iFrame (offset x:' + offset.x + ' y:' + offset.y + ')');
      pagePosition = {
        x: Number(messageData.width) + offset.x,
        y: Number(messageData.height) + offset.y
      };
      setPagePosition();
    }

    function actionMsg() {
      switch (messageData.type) {
      case 'close':
        closeIFrame(messageData.iframe);
        settings.resizedCallback(messageData); //To be removed.
        break;
      case 'message':
        forwardMsgFromIFrame();
        break;
      case 'scrollTo':
        scrollRequestFromChild(false);
        break;
      case 'scrollToOffset':
        scrollRequestFromChild(true);
        break;
      case 'reset':
        resetIFrame(messageData);
        break;
      case 'init':
        resizeIFrame();
        settings.initCallback(messageData.iframe);
        break;
      default:
        resizeIFrame();
      }
    }

    var
      msg = event.data,
      messageData = {};

    if (isMessageForUs()) {
      log(' Received: ' + msg);
      messageData = processMsg();

      if (!isMessageFromMetaParent() && checkIFrameExists() && isMessageFromIFrame()) {
        actionMsg();
        firstRun = false;
      }
    }
  }

  function getPagePosition() {
    if (null === pagePosition) {
      pagePosition = {
        x: (window.pageXOffset !== undefined) ? window.pageXOffset : document.documentElement.scrollLeft,
        y: (window.pageYOffset !== undefined) ? window.pageYOffset : document.documentElement.scrollTop
      };
      log(' Get position: ' + pagePosition.x + ',' + pagePosition.y);
    }
  }

  function setPagePosition() {
    if (null !== pagePosition) {
      window.scrollTo(pagePosition.x, pagePosition.y);
      log(' Set position: ' + pagePosition.x + ',' + pagePosition.y);
      pagePosition = null;
    }
  }

  function resetIFrame(messageData) {
    function reset() {
      setSize(messageData);
      trigger('reset', 'reset', messageData.iframe);
    }

    log(' Size reset requested by ' + ('init' === messageData.type ? 'host page' : 'iFrame'));
    getPagePosition();
    syncResize(reset, messageData, 'init');
  }

  function setSize(messageData) {
    function setDimension(dimension) {
      messageData.iframe.style[dimension] = messageData[dimension] + 'px';
      log(
        ' IFrame (' + messageData.iframe.id +
        ') ' + dimension +
        ' set to ' + messageData[dimension] + 'px'
      );
    }

    if (settings.sizeHeight) {
      setDimension('height');
    }
    if (settings.sizeWidth) {
      setDimension('width');
    }
  }

  function syncResize(func, messageData, doNotSync) {
    if (doNotSync !== messageData.type && requestAnimationFrame) {
      log(' Requesting animation frame');
      requestAnimationFrame(func);
    } else {
      func();
    }
  }

  function trigger(calleeMsg, msg, iframe) {
    log('[' + calleeMsg + '] Sending msg to iframe (' + msg + ')');
    iframe.contentWindow.postMessage(msgId + msg, '*');
  }

  function setupIFrame() {
    function setLimits() {
      function addStyle(style) {
        if ((Infinity !== settings[style]) && (0 !== settings[style])) {
          iframe.style[style] = settings[style] + 'px';
          log(' Set ' + style + ' = ' + settings[style] + 'px');
        }
      }

      addStyle('maxHeight');
      addStyle('minHeight');
      addStyle('maxWidth');
      addStyle('minWidth');
    }

    function ensureHasId(iframeID) {
      if ('' === iframeID) {
        iframe.id = iframeID = 'iFrameResizer' + count++;
        log(' Added missing iframe ID: ' + iframeID + ' (' + iframe.src + ')');
      }

      return iframeID;
    }

    function setScrolling() {
      log(' IFrame scrolling ' + (settings.scrolling ? 'enabled' : 'disabled') + ' for ' + iframeID);
      iframe.style.overflow = false === settings.scrolling ? 'hidden' : 'auto';
      iframe.scrolling = false === settings.scrolling ? 'no' : 'yes';
    }

    //The V1 iFrame script expects an int, where as in V2 expects a CSS
    //string value such as '1px 3em', so if we have an int for V2, set V1=V2
    //and then convert V2 to a string PX value.
    function setupBodyMarginValues() {
      if (('number' === typeof (settings.bodyMargin)) || ('0' === settings.bodyMargin)) {
        settings.bodyMarginV1 = settings.bodyMargin;
        settings.bodyMargin = '' + settings.bodyMargin + 'px';
      }
    }

    function createOutgoingMsg() {
      return iframeID +
        ':' + settings.bodyMarginV1 +
        ':' + settings.sizeWidth +
        ':' + settings.log +
        ':' + settings.interval +
        ':' + settings.enablePublicMethods +
        ':' + settings.autoResize +
        ':' + settings.bodyMargin +
        ':' + settings.heightCalculationMethod +
        ':' + settings.bodyBackground +
        ':' + settings.bodyPadding +
        ':' + settings.tolerance;
    }

    function init(msg) {
      //We have to call trigger twice, as we can not be sure if all
      //iframes have completed loading when this code runs. The
      //event listener also catches the page changing in the iFrame.
      addEventListener(iframe, 'load', function () {
        var fr = firstRun; // Reduce scope of var to function, because IE8's JS execution
        // context stack is borked and this value gets externally
        // changed midway through running this function.
        trigger('iFrame.onload', msg, iframe);
        if (!fr && settings.heightCalculationMethod in resetRequiredMethods) {
          resetIFrame({
            iframe: iframe,
            height: 0,
            width: 0,
            type: 'init'
          });
        }
      });
      trigger('init', msg, iframe);
    }

    var
    /*jshint validthis:true */
      iframe = this,
      iframeID = ensureHasId(iframe.id);

    setScrolling();
    setLimits();
    setupBodyMarginValues();
    init(createOutgoingMsg());
  }

  function checkOptions(options) {
    if ('object' !== typeof options) {
      throw new TypeError('Options is not an object.');
    }
  }

  function createNativePublicFunction() {
    function init(element) {
      if ('IFRAME' !== element.tagName.toUpperCase()) {
        throw new TypeError('Expected <IFRAME> tag, found <' + element.tagName + '>.');
      } else {
        setupIFrame.call(element);
      }
    }

    function processOptions(options) {
      options = options || {};
      checkOptions(options);

      for (var option in defaults) {
        if (defaults.hasOwnProperty(option)) {
          settings[option] = options.hasOwnProperty(option) ? options[option] : defaults[option];
        }
      }
    }

    return function iFrameResizeF(options, selecter) {
      processOptions(options);
      Array.prototype.forEach.call(document.querySelectorAll(selecter || 'iframe'), init);
      window.iFrameResize.settings = settings;
    };
  }

  function createJQueryPublicMethod($) {
    $.fn.iFrameResize = function $iFrameResizeF(options) {
      options = options || {};
      checkOptions(options);
      settings = $.extend({}, defaults, options);
      return this.filter('iframe').each(setupIFrame).end();
    };
  }

  setupRequestAnimationFrame();
  addEventListener(window, 'message', iFrameListener);
  //window.addEventListener('message', iFrameListener.bind(this));

  /* don't use accidentially existing jquery from parent
  if (window.jQuery) {
    createJQueryPublicMethod(jQuery);
  }

  if (typeof define === 'function' && define.amd) {
    define([], createNativePublicFunction);
  } else if (typeof exports === 'object') { //Node for browserfy
    module.exports = createNativePublicFunction();
  } else {
    window.iFrameResize = createNativePublicFunction();
  }
  */

  /* always create a new public, probably we should adjust the name */
  window.iFrameResize = createNativePublicFunction();

  // add IFrames to all div with class="at-app-embed"
  function createIFrames() {

    var ifs = document.getElementsByClassName("at-app-embed");
    for (var i = 0; i < ifs.length; i++) {
      createIFrameForDiv(ifs[i], i);
    }
    debugger;
    window.iFrameResize({
      log: false
    });

    for (var i = 0; i < ifs.length; i++) {
      var aae = document.getElementById("aae" + i);
      var url = aae.getAttribute("xsrc");
      var app = aae.getAttribute("xapp");

      if (i == 0) {
        window.iFrameResize.settings.boundIFrame = aae;

        var hash = window.location.hash || "";
        if (hash.indexOf("#!") == 0) {
          hash = hash.substr(2);
        } else if (hash.indexOf("#") == 0) {
          hash = hash.substr(1);
        }

        // if hash seems to be an app then replace default app
        if (hash.indexOf("/") > 0) {
          app = hash;
        }
      }

      if (app) {
        url += "#!" + app;
      }
      aae.src = url;
    }
  }

  window.onhashchange = function () {

    if (window.iFrameResize.settings.boundIFrame == undefined) return;
    var aae = window.iFrameResize.settings.boundIFrame;
    var url = aae.getAttribute("xsrc");
    var app = aae.getAttribute("xapp");

    var hash = window.location.hash || "";
    if (hash.indexOf("#!") == 0) {
      hash = hash.substr(2);
    } else if (hash.indexOf("#") == 0) {
      hash = hash.substr(1);
    }

    // if hash seems to be an app then replace default app
    if (hash.indexOf("/") > 0) {
      url += "#!" + hash;
      aae.src = url;
    }
  }

  function createIFrameForDiv(div, cntr) {
    var src = div.getAttribute("src") || "/components/at-app-embed-scaffold/at-app-embed.html";
    var app = div.getAttribute("app") || "";
    var iframe = document.createElement('iframe');
    iframe.id = "aae" + cntr;
    iframe.frameBorder = 0;
    iframe.width = "100%";
    iframe.scrolling = "no";
    iframe.setAttribute("xsrc", src);
    iframe.setAttribute("xapp", app);
    div.appendChild(iframe);
  }

  createIFrames();

})();<|endoftext|>


<commit_before>const promise = require("bluebird");
const options = {
  // Initialization Options
  promiseLib: promise, // use bluebird as promise library
  capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
const oldS3Url = "uploads.participedia.xyz";
const newS3Url = process.env.AWS_S3_BUCKET;

let config;
try {
  config = parse(connectionString);
  if (process.env.NODE_ENV === "test" || config.host === "localhost") {
    config.ssl = false;
  } else {
    config.ssl = true;
  }
} catch (e) {
  console.error("# Error parsing DATABASE_URL environment variable");
}

let db = pgp(config);
getPhotos("cases");
getPhotos("methods");
getPhotos("organizations");

function getPhotos(table) {
  db.any(`SELECT id, photos, files, videos, audio FROM ${table}`)
    .then(function(data) {
      data.forEach(data => {
        // Handle photos
        var newPhoto = data.photos;
        var newFiles = data.files;
        var newVideos = data.videos;
        var newAudio = data.audio;
        var metaData = {};

        if (newPhoto.search(oldS3Url) >= 0) {
          newPhoto = newPhoto.replace(oldS3Url, newS3Url);
          metaData["photos"] = newPhoto;
        } else {
          // console.log(`Table: ${table}, Column 'photos', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (newFiles.search(oldS3Url) >= 0) {
          newFiles = newFiles.replace(oldS3Url, newS3Url);
          metaData["files"] = newFiles;
        } else {
          // console.log(`Table: ${table}, Column 'files', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (newVideos.search(oldS3Url) >= 0) {
          newVideos = newVideos.replace(oldS3Url, newS3Url);
          metaData["videos"] = newAudio;
        } else {
          // console.log(`Table: ${table}, Column 'videos', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (newAudio.search(oldS3Url) >= 0) {
          newAudio = newAudio.replace(oldS3Url, newS3Url);
          metaData["audio"] = newAudio;
        } else {
          // console.log(`Table: ${table}, Column 'audio', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (
          metaData.hasOwnProperty("photos") ||
          metaData.hasOwnProperty("files") ||
          metaData.hasOwnProperty("videos") ||
          metaData.hasOwnProperty("audio")
        ) {
          updatePhoto(data.id, metaData, table);
        }
      });
    })
    .catch(function(error) {
      console.log(error);
    });
}

function updatePhoto(id, value, table) {
  const dataSingle = value;
  const condition = pgp.as.format(` WHERE id = ${id}`, dataSingle);
  const update = pgp.helpers.update(dataSingle, null, table) + condition;

  db.none(update)
    .then(function(data) {
      console.log(`Table: ${table}; ID: ${id} updated`);
    })
    .catch(function(error) {
      console.log(error);
    });
}
<commit_msg>refactor updating of old to new bucket  (debug commit)<commit_after>const promise = require("bluebird");
const options = {
  // Initialization Options
  promiseLib: promise, // use bluebird as promise library
  capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
// const oldS3Url = "uploads.participedia.xyz";
const oldS3Url = new RegExp('uploads.participedia.xyz', 'g');
const newS3Url = process.env.AWS_S3_BUCKET;

let config;
try {
  config = parse(connectionString);
  if (process.env.NODE_ENV === "test" || config.host === "localhost") {
    config.ssl = false;
  } else {
    config.ssl = true;
  }
} catch (e) {
  console.error("# Error parsing DATABASE_URL environment variable");
}

let db = pgp(config);
getPhotos("cases");
getPhotos("methods");
getPhotos("organizations");

function getPhotos(table) {
  db.any(`SELECT id, photos, files, videos, audio FROM ${table}`)
    .then(function(data) {
      data.forEach(data => {
        // Handle photos
        var newPhoto = data.photos;
        var newFiles = data.files;
        var newVideos = data.videos;
        var newAudio = data.audio;
        var metaData = {};

        if (newPhoto.search(oldS3Url) >= 0) {
          newPhoto = newPhoto.replace(oldS3Url, newS3Url);
          metaData["photos"] = newPhoto;
          console.log(`Table: ${table}, Column 'photos', ID ${data.id} has the URL we are looking for.`);
        } else {
          // console.log(`Table: ${table}, Column 'photos', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (newFiles.search(oldS3Url) >= 0) {
          newFiles = newFiles.replace(oldS3Url, newS3Url);
          metaData["files"] = newFiles;
          console.log(`Table: ${table}, Column 'files', ID ${data.id} has the URL we are looking for.`);
          console.log(metaData["files"]);
        } else {
          // console.log(`Table: ${table}, Column 'files', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (newVideos.search(oldS3Url) >= 0) {
          newVideos = newVideos.replace(oldS3Url, newS3Url);
          metaData["videos"] = newAudio;
          console.log(`Table: ${table}, Column 'videos', ID ${data.id} has the URL we are looking for.`);
        } else {
          // console.log(`Table: ${table}, Column 'videos', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (newAudio.search(oldS3Url) >= 0) {
          newAudio = newAudio.replace(oldS3Url, newS3Url);
          metaData["audio"] = newAudio;
          console.log(`Table: ${table}, Column 'audio', ID ${data.id} has the URL we are looking for.`);
        } else {
          // console.log(`Table: ${table}, Column 'audio', ID ${data.id} doesn't have the URL we are looking for.`);
        }

        if (
          metaData.hasOwnProperty("photos") ||
          metaData.hasOwnProperty("files") ||
          metaData.hasOwnProperty("videos") ||
          metaData.hasOwnProperty("audio")
        ) {
          // updatePhoto(data.id, metaData, table);
        }
      });
    })
    .catch(function(error) {
      console.log(error);
    });
}

// function updatePhoto(id, value, table) {
//   const dataSingle = value;
//   const condition = pgp.as.format(` WHERE id = ${id}`, dataSingle);
//   const update = pgp.helpers.update(dataSingle, null, table) + condition;

//   db.none(update)
//     .then(function(data) {
//       console.log(`Table: ${table}; ID: ${id} updated`);
//     })
//     .catch(function(error) {
//       console.log(error);
//     });
// }
<|endoftext|>