<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));

            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var lockedPercent = 0;
        var nrOfUnlocked = 0;

        for(var index = 0; index < gvm.competences.length; index++)
        {
            if(gvm.competences[index].locked == true)
            {
                lockedPercent += gvm.competences[index].weight;
            }
            else
            {
                nrOfUnlocked++;
            }
        }

        var remainingPercent = 100 - lockedPercent;

        var percentPerCompetence = lockedPercent / nrOfUnlocked;

        console.log(percentPerCompetence);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}
<commit_msg>lock icons<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));

            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var lockedPercent = 0;
        var nrOfUnlocked = 0;

        for(var index = 0; index < gvm.competences.length; index++)
        {
            if(gvm.competences[index].locked == true)
            {
                lockedPercent += gvm.competences[index].weight;
            }
            else
            {
                nrOfUnlocked++;
            }
        }

        var remainingPercent = 100 - lockedPercent;

        var percentPerCompetence = remainingPercent / nrOfUnlocked;

        console.log(percentPerCompetence);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        weightLeft: ko.computed(
            function (weight) {
                this.weight - weight;
            }
        ),

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };
}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators, gvm) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            parent.weightLeft = parent.weightLeft - this.weight;
            alert(parent.weightLeft);
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.weightLeft = 100;

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<commit_msg>lock weight<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };
}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators, gvm) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.weightLeft = 100;

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<|endoftext|>


<commit_before>"use strict";

/**
 * An ethernet-through-websocket adapter, to be used with
 *     https://github.com/benjamincburns/websockproxy
 *
 * emulated ethernet card <--> this <--> websocket proxy <--> network
 *
 * @constructor
 */
function NetworkAdapter(url, bus)
{
    this.send_data = function(x) {};

    this.bus = undefined;
    this.socket = undefined;
    this.send_queue = [];
    this.url = url;

    this.reconnect_interval = 10000;
    this.last_connect_attempt = Date.now() - this.reconnect_interval;
    this.send_queue_limit = 64;

    this.register(bus);
}

NetworkAdapter.prototype.handle_message = function(e)
{
    if(this.bus)
    {
        this.bus.send("net0-receive", new Uint8Array(e.data));
    }
};

NetworkAdapter.prototype.handle_close = function(e)
{
    //console.log("onclose", e);

    this.connect();
    setTimeout(this.connect.bind(this), this.reconnect_interval);
};

NetworkAdapter.prototype.handle_open = function(e)
{
    //console.log("open", e);

    for(var i = 0; i < this.send_queue.length; i++)
    {
        this.send(this.send_queue[i]);
    }

    this.send_queue = [];
};

NetworkAdapter.prototype.handle_error = function(e)
{
    //console.log("onerror", e);
};

NetworkAdapter.prototype.register = function(bus)
{
    this.bus = bus;
    this.bus.register("net0-send", function(data)
    {
        this.send(data);
    }, this);
};

NetworkAdapter.prototype.destroy = function()
{
    if(this.socket)
    {
        this.socket.close();
    }
};

NetworkAdapter.prototype.connect = function()
{
    if(this.socket)
    {
        var state = this.socket.readyState;

        if(state === 0 || state === 1)
        {
            // already or almost there
            return;
        }
    }

    var now = Date.now();

    if(this.last_connect_attempt + this.reconnect_interval > now)
    {
        return;
    }

    this.last_connect_attempt = Date.now();

    this.socket = new WebSocket(this.url);
    this.socket.binaryType = "arraybuffer";

    this.socket.onopen = this.handle_open.bind(this);;
    this.socket.onmessage = this.handle_message.bind(this);
    this.socket.onclose = this.handle_close.bind(this);
    this.socket.onerror = this.handle_error.bind(this);
};

NetworkAdapter.prototype.send = function(data)
{
    //console.log("send", data);

    if(!this.socket || this.socket.readyState !== 1)
    {
        this.send_queue.push(data);

        if(this.send_queue.length > 2 * this.send_queue_limit)
        {
            this.send_queue = this.send_queue.slice(-this.send_queue_limit);
        }

        this.connect();
    }
    else
    {
        this.socket.send(data);
    }
}
<commit_msg>Clean up<commit_after>"use strict";

/**
 * An ethernet-through-websocket adapter, to be used with
 *     https://github.com/benjamincburns/websockproxy
 *
 * emulated ethernet card <--> this <--> websocket proxy <--> network
 *
 * @constructor
 */
function NetworkAdapter(url, bus)
{
    this.send_data = function(x) {};

    this.bus = bus;
    this.socket = undefined;
    this.send_queue = [];
    this.url = url;

    this.reconnect_interval = 10000;
    this.last_connect_attempt = Date.now() - this.reconnect_interval;
    this.send_queue_limit = 64;

    this.bus.register("net0-send", function(data)
    {
        this.send(data);
    }, this);
}

NetworkAdapter.prototype.handle_message = function(e)
{
    if(this.bus)
    {
        this.bus.send("net0-receive", new Uint8Array(e.data));
    }
};

NetworkAdapter.prototype.handle_close = function(e)
{
    //console.log("onclose", e);

    this.connect();
    setTimeout(this.connect.bind(this), this.reconnect_interval);
};

NetworkAdapter.prototype.handle_open = function(e)
{
    //console.log("open", e);

    for(var i = 0; i < this.send_queue.length; i++)
    {
        this.send(this.send_queue[i]);
    }

    this.send_queue = [];
};

NetworkAdapter.prototype.handle_error = function(e)
{
    //console.log("onerror", e);
};

NetworkAdapter.prototype.destroy = function()
{
    if(this.socket)
    {
        this.socket.close();
    }
};

NetworkAdapter.prototype.connect = function()
{
    if(this.socket)
    {
        var state = this.socket.readyState;

        if(state === 0 || state === 1)
        {
            // already or almost there
            return;
        }
    }

    var now = Date.now();

    if(this.last_connect_attempt + this.reconnect_interval > now)
    {
        return;
    }

    this.last_connect_attempt = Date.now();

    this.socket = new WebSocket(this.url);
    this.socket.binaryType = "arraybuffer";

    this.socket.onopen = this.handle_open.bind(this);;
    this.socket.onmessage = this.handle_message.bind(this);
    this.socket.onclose = this.handle_close.bind(this);
    this.socket.onerror = this.handle_error.bind(this);
};

NetworkAdapter.prototype.send = function(data)
{
    //console.log("send", data);

    if(!this.socket || this.socket.readyState !== 1)
    {
        this.send_queue.push(data);

        if(this.send_queue.length > 2 * this.send_queue_limit)
        {
            this.send_queue = this.send_queue.slice(-this.send_queue_limit);
        }

        this.connect();
    }
    else
    {
        this.socket.send(data);
    }
}
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        weightLeft: ko.computed(
            function (weight) {
                this.weight - weight;
            }
        ),

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };
}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators, gvm) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            parent.weightLeft = parent.weightLeft() - this.weight;
            alert(parent.weightLeft);
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.weightLeft = 100;

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<commit_msg>lock weight<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        weightLeft: ko.computed(
            function (weight) {
                this.weight - weight;
            }
        ),

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };
}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators, gvm) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            parent.weightLeft = parent.weightLeft - this.weight;
            alert(parent.weightLeft);
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.weightLeft = 100;

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<|endoftext|>


<commit_before>/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "Common" }] */
'use strict';

const Common = (() => {
    const translate = (message) => {
        return browser.i18n.getMessage(message);
    };

    const translateAll = () => {
        [].forEach.call(document.querySelectorAll('[data-i18n]'), (el) => {
            const message = el.getAttribute('data-i18n');
            el.textContent = translate(message);
        });
        [].forEach.call(document.querySelectorAll('[data-i18n-attr]'), (el) => {
            const [attr, message] = el.getAttribute('data-i18n-attr').split('|');
            el.setAttribute(attr, translate(message));
        });
    };

    const getLocale = () => browser.i18n.getUILanguage();

    return {
        translate: translate,
        translateAll: translateAll,
        getLocale: getLocale
    };
})();
<commit_msg>Missing translations displayed with [@TOTRANSLATE] prefix<commit_after>/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "Common" }] */
'use strict';

const Common = (() => {
    const translate = (key) => {
        const message = browser.i18n.getMessage(key);
        return message || `[@TOTRANSLATE] ${key.replace(/_/g, ' ')}`;
    };

    const translateAll = () => {
        [].forEach.call(document.querySelectorAll('[data-i18n]'), (el) => {
            const message = el.getAttribute('data-i18n');
            el.textContent = translate(message);
        });
        [].forEach.call(document.querySelectorAll('[data-i18n-attr]'), (el) => {
            const [attr, message] = el.getAttribute('data-i18n-attr').split('|');
            el.setAttribute(attr, translate(message));
        });
    };

    const getLocale = () => browser.i18n.getUILanguage();

    return {
        translate: translate,
        translateAll: translateAll,
        getLocale: getLocale
    };
})();
<|endoftext|>


<commit_before>// Following function takes a numebrs and returns a rounded off number
function toInteger(number) {
  // Making float to show 2 decimal places
  return parseFloat(number).toFixed(2);
};

//Sanitary Ware Calculator
//Calculating Sanitry Ware for Educational building types
function educationalType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('carpetArea-educational').valueAsNumber;
    // Calculating Number of People
    var result = (a / 1);
    var positiveResult = Math.abs(result);

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-educational').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-educational').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0 && calcMale() <= 250) {
      var positiveResult = 5;
    } else if (calcMale() > 250) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0 && calcMale() <= 400) {
      var positiveResult = 2;
    } else if (calcMale() > 400) {
      var result = calcMale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0 && calcFemale() <= 400) {
      var positiveResult = 2;
    } else if (calcFemale() > 400) {
      var result = calcFemale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "WC for Female:" + calcWCFemale();
  };

  return resultSanitaryWare();
};

//Calculating Sanitry Ware for Business building types
function businessType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('carpetArea-business').valueAsNumber;
    // Calculating Number of People
    var result = (a / 4);
    var positiveResult = Math.abs(result);

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-business').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-business').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0 && calcMale() < 20) {
      var positiveResult = 1;
    } else if (calcMale() > 20 && calcMale() <= 100) {
      var result = calcMale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100 && calcMale() <= 500) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 500) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0 && calcMale() < 20) {
      var positiveResult = 1;
    } else if (calcMale() > 20 && calcMale() <= 100) {
      var result = calcMale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100 && calcMale() <= 500) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 500) {
      var result = calcMale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0 && calcFemale() < 20) {
      var positiveResult = 1;
    } else if (calcFemale() > 20 && calcFemale() <= 100) {
      var result = calcFemale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcFemale() > 100 && calcFemale() <= 500) {
      var result = calcFemale() / 50;
      var positiveResult = Math.ceil(result);
    } else if (calcFemale() > 500) {
      var result = calcFemale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "WC for Female:" + calcWCFemale();
  };

  return resultSanitaryWare();
};

//Calculating Sanitry Ware for Industrial & Storage building types
function industrialType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('carpetArea-industrial').valueAsNumber;
    // Calculating Number of People
    var result = (a / 25);
    var positiveResult = Math.abs(result);

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-industrial').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-industrial').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0 && calcMale() <= 100) {
      var result = calcMale() / 100;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0 && calcMale() <= 100) {
      var result = calcMale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0 && calcFemale() <= 100) {
      var result = calcFemale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcFemale() > 100) {
      var result = calcFemale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "WC for Female:" + calcWCFemale() + "
" + "Wash Area: 4 m²";
  };

  return resultSanitaryWare();
};

//Calculating Sanitry Ware for Special building types
function specialType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('seats-special').valueAsNumber;
    // Calculating Number of People
    var positiveResult = a;

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-special').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-special').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0) {
      var result = (calcMale() / 75) * 2;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0) {
      var result = calcMale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWBMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0) {
      var result = calcMale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0) {
      var result = calcFemale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWBFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0) {
      var result = calcFemale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "Wash Basins for Male:" + calcWBMale() + "
" + "WC for Female:" + calcWCFemale() + "
" + "Wash Basins for Female:" + calcWBFemale();
  };

  return resultSanitaryWare();
};
<commit_msg>Sanitaryware Calc error fix<commit_after>// Following function takes a numebrs and returns a rounded off number
function toInteger(number) {
  // Making float to show 2 decimal places
  return parseFloat(number).toFixed(2);
};

//Sanitary Ware Calculator
//Calculating Sanitry Ware for Educational building types
function educationalType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('carpetArea-educational').valueAsNumber;
    // Calculating Number of People
    var result = (a / 1);
    var positiveResult = Math.abs(result);

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-educational').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-educational').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0 && calcMale() <= 250) {
      var positiveResult = 5;
    } else if (calcMale() > 250) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0 && calcMale() <= 400) {
      var positiveResult = 2;
    } else if (calcMale() > 400) {
      var result = calcMale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0 && calcFemale() <= 400) {
      var positiveResult = 2;
    } else if (calcFemale() > 400) {
      var result = calcFemale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "WC for Female:" + calcWCFemale();
  };

  return resultSanitaryWare();
};

//Calculating Sanitry Ware for Business building types
function businessType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('carpetArea-business').valueAsNumber;
    // Calculating Number of People
    var result = (a / 4);
    var positiveResult = Math.abs(result);

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-business').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-business').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0 && calcMale() <= 20) {
      var positiveResult = 1;
    } else if (calcMale() > 20 && calcMale() <= 100) {
      var result = calcMale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100 && calcMale() <= 500) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 500) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0 && calcMale() <= 20) {
      var positiveResult = 1;
    } else if (calcMale() > 20 && calcMale() <= 100) {
      var result = calcMale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100 && calcMale() <= 500) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 500) {
      var result = calcMale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0 && calcFemale() <= 20) {
      var positiveResult = 1;
    } else if (calcFemale() > 20 && calcFemale() <= 100) {
      var result = calcFemale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcFemale() > 100 && calcFemale() <= 500) {
      var result = calcFemale() / 50;
      var positiveResult = Math.ceil(result);
    } else if (calcFemale() > 500) {
      var result = calcFemale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "WC for Female:" + calcWCFemale();
  };

  return resultSanitaryWare();
};

//Calculating Sanitry Ware for Industrial & Storage building types
function industrialType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('carpetArea-industrial').valueAsNumber;
    // Calculating Number of People
    var result = (a / 25);
    var positiveResult = Math.abs(result);

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-industrial').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-industrial').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0 && calcMale() <= 100) {
      var result = calcMale() / 100;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0 && calcMale() <= 100) {
      var result = calcMale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcMale() > 100) {
      var result = calcMale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0 && calcFemale() <= 100) {
      var result = calcFemale() / 25;
      var positiveResult = Math.ceil(result);
    } else if (calcFemale() > 100) {
      var result = calcFemale() / 50;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "WC for Female:" + calcWCFemale() + "
" + "Wash Area: 4 m²";
  };

  return resultSanitaryWare();
};

//Calculating Sanitry Ware for Special building types
function specialType() {
  var calcPax = function() {
    // Taking input
    var a = document.getElementById('seats-special').valueAsNumber;
    // Calculating Number of People
    var positiveResult = a;

    return positiveResult;
  };

  var calcMale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-special').valueAsNumber;
    var result = (a / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcFemale = function() {
    // Calculating Number of Male
    var a = document.getElementById('percentageOfMale-special').valueAsNumber;
    var result = ((100 - a) / 100) * calcPax();
    var positiveResult = Math.ceil(result);

    return positiveResult;
  };

  var calcUrinals = function() {
    // Calculating Number of Urinals
    if (calcMale() > 0) {
      var result = (calcMale() / 75) * 2;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0) {
      var result = calcMale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWBMale = function() {
    // Calculating Number of WC for Male
    if (calcMale() > 0) {
      var result = calcMale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWCFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0) {
      var result = calcFemale() / 100;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var calcWBFemale = function() {
    // Calculating Number of WC for Male
    if (calcFemale() > 0) {
      var result = calcFemale() / 200;
      var positiveResult = Math.ceil(result);
    } else {
      var positiveResult = 0;
    }

    return positiveResult;
  };

  var resultSanitaryWare = function() {
    // Declaring Result
    document.getElementById('resultSanitaryWare').innerHTML = "Urinals: " + calcUrinals() + "
" + "WC for Male:" + calcWCMale() + "
" + "Wash Basins for Male:" + calcWBMale() + "
" + "WC for Female:" + calcWCFemale() + "
" + "Wash Basins for Female:" + calcWBFemale();
  };

  return resultSanitaryWare();
};
<|endoftext|>


<commit_before>/*********************************************
* A minimal wrapper for kaltura server api
*
* Supports static requests,
* Auto includes kWidget for userKS queries ( where admin ks is not provided )
* Makes use of defined:
* 	'Kaltura.ServiceUrl', 'http://cdnapi.kaltura.com' );
* 		&&
*	'Kaltura.ServiceBase'
**********************************************/
(function( kWidget ){ "use strict"
if( !kWidget ){
	kWidget = window.kWidget = {};
}
kWidget.api = function( options ){
	return this.init( options );
};
kWidget.api.prototype = {
	ks: null,
	// the default api request method
	// will dictate if the CDN can cache on a per url basis
	type: 'auto',
	baseParam: {
		'apiVersion' : '3.1',
		'expiry' : '86400',
		'clientTag': 'kwidget:v' + window[ 'MWEMBED_VERSION' ],
		'format' : 9, // 9 = JSONP format
		'ignoreNull' : 1
	},
	/**
	 * Init the api object:
	 * options {Object} Set of init options
	 */
	init: function( options  ){
		for( var i in options ){
			this[i] = options[i];
		}
		// check for globals if not set, use mw.getConfig
		if( ! this.serviceUrl ){
			this.serviceUrl = mw.getConfig( 'Kaltura.ServiceUrl' );
		}
		if( ! this.serviceBase ){
			this.serviceBase = mw.getConfig( 'Kaltura.ServiceBase' );
		}
		if( ! this.statsServiceUrl ){
			this.statsServiceUrl = mw.getConfig( 'Kaltura.StatsServiceUrl' );
		}
		if( typeof this.disableCache == 'undefined' ){
			this.disableCache = mw.getConfig('Kaltura.NoApiCache');
		}
	},
	setKs: function( ks ){
		this.ks = ks;
	},
	getKs: function(){
		return this.ks;
	},
	/**
	 * Do an api request and get data in callback
	 */
	doRequest: function ( requestObject, callback,skipKS, errorCallback  ){
		var _this = this;
		var param = {};
		var globalCBName = null;
		// If we have Kaltura.NoApiCache flag, pass 'nocache' param to the client
		if( this.disableCache === true ) {
			param['nocache'] = 'true';
		}

		// Add in the base parameters:
		for( var i in this.baseParam ){
			if( typeof param[i] == 'undefined' ){
				param[i] = this.baseParam[i];
			}
		};

		// Check for "user" service queries ( no ks or wid is provided  )
		if( requestObject['service'] != 'user' && !skipKS ){
			kWidget.extend( param, this.handleKsServiceRequest( requestObject ) );
		} else {
			kWidget.extend( param, requestObject );
		}
		// Add kalsig to query:
		param[ 'kalsig' ] = this.hashCode( kWidget.param( param ) );

		// Remove service tag ( hard coded into the api url )
		var serviceType = param['service'];
		delete param['service'];

		var timeoutError = setTimeout(function(){
			if ( globalCBName ) {
				window[globalCBName] = undefined;
			}
			if (errorCallback){
				errorCallback();
			}
			//mw.log("Timeout occur in doApiRequest");
		},mw.getConfig("Kaltura.APITimeout"));

		var handleDataResult = function( data ){
			clearTimeout(timeoutError);
			// check if the base param was a session
            data = data || [];
            if( data.length > 1 && param[ '1:service' ] == 'session' ){
				//Set the returned ks
	            _this.setKs(data[0].ks);
	            // if original request was not a multirequest then directly return the data object
	            // if original request was a multirequest then remove the session from the returned data objects
	            if (data.length == 2){
		            data = data[1];
	            } else {
		            data.shift();
	            }
			}
			// issue the local scope callback:
			if( callback ){
				callback( data );
				callback = null;
			}
		};

		// Run the request
		// NOTE kaltura api server should return:
		// Access-Control-Allow-Origin:* most browsers support this.
		// ( old browsers with large api payloads are not supported )
		var userAgent = navigator.userAgent.toLowerCase();
		var forceJSONP = ( userAgent.indexOf('msie 8') !== -1 || userAgent.indexOf('msie 9') !== -1 );
		try {
			if ( forceJSONP ){
				throw "forceJSONP";
			}
			// set format to JSON ( Access-Control-Allow-Origin:* )
			param['format'] = 1;
			this.xhrRequest( _this.getApiUrl( serviceType ), param, function( data ){
				handleDataResult( data );
			});
		} catch(e){
			param['format'] = 9; // jsonp
			// build the request url:
			var requestURL = _this.getApiUrl( serviceType ) + '&' + kWidget.param( param );
			// try with callback:
			globalCBName = 'kapi_' + Math.abs( _this.hashCode( kWidget.param( param ) ) );
			if( window[ globalCBName ] ){
				// Update the globalCB name inx.
				this.callbackIndex++;
				globalCBName = globalCBName + this.callbackIndex;
			}
			window[ globalCBName ] = function(data){
				handleDataResult( data );
				// null out the global callback for fresh loads
				 window[globalCBName] = undefined;
				try{
					delete window[globalCBName];
				}catch( e ){}
			}
			requestURL+= '&callback=' + globalCBName;
			kWidget.appendScriptUrl( requestURL );
		}
	},
	xhrRequest: function( url, param, callback ){
		// get the request method:
		var requestMethod = this.type == "auto" ?
				( ( kWidget.param( param ).length > 2000 ) ? 'xhrPost' : 'xhrGet' ) :
				( (  this.type == "GET" )? 'xhrGet': 'xhrPost' );
		// do the respective request
		this[ requestMethod ](  url, param, callback );
	},
	parseResponse: function (data ){
		var response = data;
		try {
			response = JSON.parse( data );
		}catch(e){}
		return response;
	},
	xhrGet: function( url, param, callback ){
		var _this = this;
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function(){
			if ( xmlhttp.readyState==4 && xmlhttp.status==200 ){
				callback( _this.parseResponse( xmlhttp.responseText ) );
			}
		}
		xmlhttp.open("GET", url + '&' + kWidget.param( param ), true);
		xmlhttp.send();
	},
	/**
	 * Do an xhr request
	 */
	xhrPost: function( url, param, callback ){
		var _this = this;
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function(){
			if ( xmlhttp.readyState==4 && xmlhttp.status==200 ){
				callback( _this.parseResponse( xmlhttp.responseText ) );
			}
		}
		xmlhttp.open("POST", url, true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.send( kWidget.param( param ) );
	},
	handleKsServiceRequest: function( requestObject ){
		var param = {};
		// put the ks into the params request if set
		if( requestObject[ 'ks' ] ){
			this.ks = requestObject['ks'];
		}
		// Convert into a multi-request if no session is set ( ks will be added below )
		if( !requestObject.length && !this.getKs() ){
			requestObject = [ requestObject ];
		}
		// Check that we have a session established if not make it part of our multi-part request
		if( requestObject.length ){
			param['service'] = 'multirequest';
			param['action'] = 'null';

			// Kaltura api starts with index 1 for some strange reason.
			var mulitRequestIndex = 1;
			// check if we should add a user ks
			if( !this.getKs() ){
				param[ mulitRequestIndex + ':service' ] = 'session';
				param[ mulitRequestIndex + ':action' ] = 'startWidgetSession';
				param[ mulitRequestIndex + ':widgetId'] = this.wid;
				// update the request index:
				mulitRequestIndex = 2;
			}

			for( var i = 0 ; i < requestObject.length; i++ ){
				var requestInx = mulitRequestIndex + i;
				// If ks was null always add back ref to ks:
				param[ requestInx + ':ks'] = ( this.getKs() ) ? this.getKs() : '{1:result:ks}';

				// MultiRequest pre-process each param with inx:param
				for( var paramKey in requestObject[i] ){
					// support multi dimension array request:
					if( typeof requestObject[i][paramKey] == 'object' ){
						for( var subParamKey in requestObject[i][paramKey] ){
							param[ requestInx + ':' + paramKey + ':' +  subParamKey ] =
								this.parseParam(requestObject[i][paramKey][subParamKey]);
						}
					} else {
						param[ requestInx + ':' + paramKey ] = this.parseParam(requestObject[i][paramKey]);
					}
				}
			}
		} else {
			param = requestObject;
			param['ks'] = this.getKs();
		}
		return param;
	},
	parseParam: function(data){
		var param = data;
		//Check if we need to request session
		if (!this.getKs()) {
			//check if request contains dependent params and if so then update reference object num -
			// because reference index changed due to addition of multirequest startWidgetSession service
			var paramParts = param.toString().match( /\{(\d+)(:result:.*)\}/ );
			if ( paramParts ) {
				var refObj = parseInt(paramParts[1]) + 1;
				param = "{"+ refObj + paramParts[2] + "}"
			}
		}
		return param;
	},
	getApiUrl : function( serviceType ){
		var serviceUrl = mw.getConfig( 'Kaltura.ServiceUrl' );
		if( serviceType && serviceType == 'stats' &&  mw.getConfig( 'Kaltura.StatsServiceUrl' ) ) {
			serviceUrl = mw.getConfig( 'Kaltura.StatsServiceUrl' );
		}
		if( serviceType && serviceType == 'liveStats' &&  mw.getConfig( 'Kaltura.LiveStatsServiceUrl' ) ) {
			serviceUrl = mw.getConfig( 'Kaltura.LiveStatsServiceUrl' );
		}
		return serviceUrl + mw.getConfig( 'Kaltura.ServiceBase' ) + serviceType;
	},
	hashCode: function( str ){
		var hash = 0;
		if (str.length == 0) return hash;
		for (var i = 0; i < str.length; i++) {
			var currentChar = str.charCodeAt(i);
			hash = ((hash<<5)-hash)+currentChar;
			hash = hash & hash; // Convert to 32bit integer
		}
		return hash;
	}
}

})( window.kWidget );<commit_msg>SUP-3936 add force JSONP to IE10 as well<commit_after>/*********************************************
* A minimal wrapper for kaltura server api
*
* Supports static requests,
* Auto includes kWidget for userKS queries ( where admin ks is not provided )
* Makes use of defined:
* 	'Kaltura.ServiceUrl', 'http://cdnapi.kaltura.com' );
* 		&&
*	'Kaltura.ServiceBase'
**********************************************/
(function( kWidget ){ "use strict"
if( !kWidget ){
	kWidget = window.kWidget = {};
}
kWidget.api = function( options ){
	return this.init( options );
};
kWidget.api.prototype = {
	ks: null,
	// the default api request method
	// will dictate if the CDN can cache on a per url basis
	type: 'auto',
	baseParam: {
		'apiVersion' : '3.1',
		'expiry' : '86400',
		'clientTag': 'kwidget:v' + window[ 'MWEMBED_VERSION' ],
		'format' : 9, // 9 = JSONP format
		'ignoreNull' : 1
	},
	/**
	 * Init the api object:
	 * options {Object} Set of init options
	 */
	init: function( options  ){
		for( var i in options ){
			this[i] = options[i];
		}
		// check for globals if not set, use mw.getConfig
		if( ! this.serviceUrl ){
			this.serviceUrl = mw.getConfig( 'Kaltura.ServiceUrl' );
		}
		if( ! this.serviceBase ){
			this.serviceBase = mw.getConfig( 'Kaltura.ServiceBase' );
		}
		if( ! this.statsServiceUrl ){
			this.statsServiceUrl = mw.getConfig( 'Kaltura.StatsServiceUrl' );
		}
		if( typeof this.disableCache == 'undefined' ){
			this.disableCache = mw.getConfig('Kaltura.NoApiCache');
		}
	},
	setKs: function( ks ){
		this.ks = ks;
	},
	getKs: function(){
		return this.ks;
	},
	/**
	 * Do an api request and get data in callback
	 */
	doRequest: function ( requestObject, callback,skipKS, errorCallback  ){
		var _this = this;
		var param = {};
		var globalCBName = null;
		// If we have Kaltura.NoApiCache flag, pass 'nocache' param to the client
		if( this.disableCache === true ) {
			param['nocache'] = 'true';
		}

		// Add in the base parameters:
		for( var i in this.baseParam ){
			if( typeof param[i] == 'undefined' ){
				param[i] = this.baseParam[i];
			}
		};

		// Check for "user" service queries ( no ks or wid is provided  )
		if( requestObject['service'] != 'user' && !skipKS ){
			kWidget.extend( param, this.handleKsServiceRequest( requestObject ) );
		} else {
			kWidget.extend( param, requestObject );
		}
		// Add kalsig to query:
		param[ 'kalsig' ] = this.hashCode( kWidget.param( param ) );

		// Remove service tag ( hard coded into the api url )
		var serviceType = param['service'];
		delete param['service'];

		var timeoutError = setTimeout(function(){
			if ( globalCBName ) {
				window[globalCBName] = undefined;
			}
			if (errorCallback){
				errorCallback();
			}
			//mw.log("Timeout occur in doApiRequest");
		},mw.getConfig("Kaltura.APITimeout"));

		var handleDataResult = function( data ){
			clearTimeout(timeoutError);
			// check if the base param was a session
            data = data || [];
            if( data.length > 1 && param[ '1:service' ] == 'session' ){
				//Set the returned ks
	            _this.setKs(data[0].ks);
	            // if original request was not a multirequest then directly return the data object
	            // if original request was a multirequest then remove the session from the returned data objects
	            if (data.length == 2){
		            data = data[1];
	            } else {
		            data.shift();
	            }
			}
			// issue the local scope callback:
			if( callback ){
				callback( data );
				callback = null;
			}
		};

		// Run the request
		// NOTE kaltura api server should return:
		// Access-Control-Allow-Origin:* most browsers support this.
		// ( old browsers with large api payloads are not supported )
		var userAgent = navigator.userAgent.toLowerCase();
		var forceJSONP = ( userAgent.indexOf('msie 8') !== -1 || userAgent.indexOf('msie 9') !== -1 || userAgent.indexOf('msie 10') !== -1 );
		try {
			if ( forceJSONP ){
				throw "forceJSONP";
			}
			// set format to JSON ( Access-Control-Allow-Origin:* )
			param['format'] = 1;
			this.xhrRequest( _this.getApiUrl( serviceType ), param, function( data ){
				handleDataResult( data );
			});
		} catch(e){
			param['format'] = 9; // jsonp
			// build the request url:
			var requestURL = _this.getApiUrl( serviceType ) + '&' + kWidget.param( param );
			// try with callback:
			globalCBName = 'kapi_' + Math.abs( _this.hashCode( kWidget.param( param ) ) );
			if( window[ globalCBName ] ){
				// Update the globalCB name inx.
				this.callbackIndex++;
				globalCBName = globalCBName + this.callbackIndex;
			}
			window[ globalCBName ] = function(data){
				handleDataResult( data );
				// null out the global callback for fresh loads
				 window[globalCBName] = undefined;
				try{
					delete window[globalCBName];
				}catch( e ){}
			}
			requestURL+= '&callback=' + globalCBName;
			kWidget.appendScriptUrl( requestURL );
		}
	},
	xhrRequest: function( url, param, callback ){
		// get the request method:
		var requestMethod = this.type == "auto" ?
				( ( kWidget.param( param ).length > 2000 ) ? 'xhrPost' : 'xhrGet' ) :
				( (  this.type == "GET" )? 'xhrGet': 'xhrPost' );
		// do the respective request
		this[ requestMethod ](  url, param, callback );
	},
	parseResponse: function (data ){
		var response = data;
		try {
			response = JSON.parse( data );
		}catch(e){}
		return response;
	},
	xhrGet: function( url, param, callback ){
		var _this = this;
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function(){
			if ( xmlhttp.readyState==4 && xmlhttp.status==200 ){
				callback( _this.parseResponse( xmlhttp.responseText ) );
			}
		}
		xmlhttp.open("GET", url + '&' + kWidget.param( param ), true);
		xmlhttp.send();
	},
	/**
	 * Do an xhr request
	 */
	xhrPost: function( url, param, callback ){
		var _this = this;
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function(){
			if ( xmlhttp.readyState==4 && xmlhttp.status==200 ){
				callback( _this.parseResponse( xmlhttp.responseText ) );
			}
		}
		xmlhttp.open("POST", url, true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.send( kWidget.param( param ) );
	},
	handleKsServiceRequest: function( requestObject ){
		var param = {};
		// put the ks into the params request if set
		if( requestObject[ 'ks' ] ){
			this.ks = requestObject['ks'];
		}
		// Convert into a multi-request if no session is set ( ks will be added below )
		if( !requestObject.length && !this.getKs() ){
			requestObject = [ requestObject ];
		}
		// Check that we have a session established if not make it part of our multi-part request
		if( requestObject.length ){
			param['service'] = 'multirequest';
			param['action'] = 'null';

			// Kaltura api starts with index 1 for some strange reason.
			var mulitRequestIndex = 1;
			// check if we should add a user ks
			if( !this.getKs() ){
				param[ mulitRequestIndex + ':service' ] = 'session';
				param[ mulitRequestIndex + ':action' ] = 'startWidgetSession';
				param[ mulitRequestIndex + ':widgetId'] = this.wid;
				// update the request index:
				mulitRequestIndex = 2;
			}

			for( var i = 0 ; i < requestObject.length; i++ ){
				var requestInx = mulitRequestIndex + i;
				// If ks was null always add back ref to ks:
				param[ requestInx + ':ks'] = ( this.getKs() ) ? this.getKs() : '{1:result:ks}';

				// MultiRequest pre-process each param with inx:param
				for( var paramKey in requestObject[i] ){
					// support multi dimension array request:
					if( typeof requestObject[i][paramKey] == 'object' ){
						for( var subParamKey in requestObject[i][paramKey] ){
							param[ requestInx + ':' + paramKey + ':' +  subParamKey ] =
								this.parseParam(requestObject[i][paramKey][subParamKey]);
						}
					} else {
						param[ requestInx + ':' + paramKey ] = this.parseParam(requestObject[i][paramKey]);
					}
				}
			}
		} else {
			param = requestObject;
			param['ks'] = this.getKs();
		}
		return param;
	},
	parseParam: function(data){
		var param = data;
		//Check if we need to request session
		if (!this.getKs()) {
			//check if request contains dependent params and if so then update reference object num -
			// because reference index changed due to addition of multirequest startWidgetSession service
			var paramParts = param.toString().match( /\{(\d+)(:result:.*)\}/ );
			if ( paramParts ) {
				var refObj = parseInt(paramParts[1]) + 1;
				param = "{"+ refObj + paramParts[2] + "}"
			}
		}
		return param;
	},
	getApiUrl : function( serviceType ){
		var serviceUrl = mw.getConfig( 'Kaltura.ServiceUrl' );
		if( serviceType && serviceType == 'stats' &&  mw.getConfig( 'Kaltura.StatsServiceUrl' ) ) {
			serviceUrl = mw.getConfig( 'Kaltura.StatsServiceUrl' );
		}
		if( serviceType && serviceType == 'liveStats' &&  mw.getConfig( 'Kaltura.LiveStatsServiceUrl' ) ) {
			serviceUrl = mw.getConfig( 'Kaltura.LiveStatsServiceUrl' );
		}
		return serviceUrl + mw.getConfig( 'Kaltura.ServiceBase' ) + serviceType;
	},
	hashCode: function( str ){
		var hash = 0;
		if (str.length == 0) return hash;
		for (var i = 0; i < str.length; i++) {
			var currentChar = str.charCodeAt(i);
			hash = ((hash<<5)-hash)+currentChar;
			hash = hash & hash; // Convert to 32bit integer
		}
		return hash;
	}
}

})( window.kWidget );<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 * RequireJS configuration file for vibe testing.
 * @author John Blanco
 */
require.config( {
  deps: [ 'vibe-test-main' ],

  config: {},

  paths: {

    // plugins
    audio: '../../chipper/requirejs-plugins/audio',

    // PhET libs, uppercase names to identify them in require.js imports
    AXON: '../../axon/js',
    PHET_CORE: '../../phet-core/js',
    SHERPA: '../../sherpa',

    // This library
    VIBE: '.'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()
} );
<commit_msg>move requirejs plugins to chipper/js/requirejs-plugins, phetsims/chipper#92<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * RequireJS configuration file for vibe testing.
 * @author John Blanco
 */
require.config( {
  deps: [ 'vibe-test-main' ],

  config: {},

  paths: {

    // plugins
    audio: '../../chipper/js/requirejs-plugins/audio',

    // PhET libs, uppercase names to identify them in require.js imports
    AXON: '../../axon/js',
    PHET_CORE: '../../phet-core/js',
    SHERPA: '../../sherpa',

    // This library
    VIBE: '.'
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.chipper.getCacheBusterArgs()
} );
<|endoftext|>


<commit_before>define([
	'jquery',
	'underscore',
	'libs/underscore/underscore.string.min',
	'backbone',
	'text!templates/style/menu.html',
	'jscssp',
	'config',
	'libs/marked/marked'
],
function($, _, str, Backbone, dashboardPageTemplate, jscssp, config, marked) {
	var DashboardPage = Backbone.View.extend({
		el: '.js-phytoplankton-menu',
		events: {
			'click .phytoplankton-menu__list__item__link': function (ev) {
				if($(ev.currentTarget).hasClass('active')) {
					ev.preventDefault();
				} else {
					this.$el.find('.active').removeClass('active');
					$(ev.currentTarget).addClass('active');
					$(ev.currentTarget).parent().find('li:first-child').addClass('active');
				}
			},
			'click .phytoplankton-menu__list__item a': function() {
				$('.js-phytoplankton-menu').removeClass('is-active');
				$('body').removeClass('is-opaque is-locked');
			},
			'click .phytoplankton-menu__list__item ul li ul li a': function(ev) {
				ev.preventDefault();
				var scrollAnchor = $(ev.currentTarget).attr('href');
				var scrollAnchor = scrollAnchor.substr(scrollAnchor.lastIndexOf('#') + 1);
				var scrollPoint = $('.phytoplankton-page__item *[id="' + scrollAnchor + '"]').offset().top - (50 + 40);
				$('html, body').animate({
					scrollTop: scrollPoint
				}, '200');
			}
		},
		render: function () {

			var that = this;

			that.$el.html('Loading styles');

			var page = {blocks:[]};

			require(['text!' + config.css_path], function (styles) {
				// Default "imports.css"
				var markedOpts = _.extend({
										sanitize: false,
										gfm: true
									},
									config.marked_options || {}
								);
				marked.setOptions(markedOpts);

				var parser = new jscssp();
				var stylesheet = parser.parse(styles, false, true);
				var menus = [];
				var menuTitle = '';
				var currentMenu = {
					sheets: [],
					category: ''
				};
				var sheetPath;

				_.each(stylesheet.cssRules, function(rule) {
					// If /* Comment */
					if(rule.type === 101) {
						var comment = rule.parsedCssText;
						comment = comment.replace('/*', '');
						comment = comment.replace('*/', '');

						var comments = marked.lexer(comment);
						var defLinks = comments.links || {};
						_.each(comments, function (comment) {
							var tokens = [comment];
							tokens.links = defLinks;
							if(comment.type === 'heading' && comment.depth === 1) {
								menus.push(_.extend({}, currentMenu));
								currentMenu.sheets = [];
								currentMenu.category = comment.text;
							}
						});
					}
					// If @import url('');
					if(rule.type === 3) {
						// Removes @import url(''); leaving just the style sheet name.
						var sheet = rule.href.substr(rule.href.indexOf('(')+2, rule.href.indexOf(')')-rule.href.indexOf('(')-3);

						var regex = /(?:.*\/)(.*)\.(css|sass|scss|less)$/gi;
						var result = [];
						if((result = regex.exec(sheet)) !== null) {
							// result[0] Original Input.
							// result[1] Filename.
							// result[2] Extension.

							// Returns the path before 'extension/'.
							sheetPath = result[0].substr(0, result[0].lastIndexOf('' + result[2] + '/') + (result[2].length + 1));
							// Removes 'sheetPath' from 'sheet' leaving the path after 'extension/'.
							sheet = result[0].replace(sheetPath, '');
						}
						// Pushes style sheet to currentMenu.
						currentMenu.sheets.push(sheet);
					}
				});

				if(config.css_paths) {
					for(var i = 0; i < config.css_paths.length; i++) {
						var regex = /(?:.*\/)(.*)\.(css|sass|scss|less)$/gi;
						var result = [];
						if((result = regex.exec(config.css_paths[i])) !== null) {
							// result[0] Original Input.
							// result[1] Filename.
							// result[2] Extension.

							// Returns the path before 'extension/'.
							sheetPath = result[0].substr(0, result[0].lastIndexOf('' + result[2] + '/') + (result[2].length + 1));
							// Removes 'sheetPath' from 'sheet' leaving the path after 'extension/'.
							config.css_paths[i] = result[0].replace(sheetPath, '');
						}
						// Pushes style sheet to currentMenu.
						currentMenu.sheets.push(config.css_paths[i]);
					}
				}

				menus.push(currentMenu);

				$(that.el).html(_.template(dashboardPageTemplate, {_:_, menus: menus}));
				$('[href="' + window.location.hash + '"]').addClass('active');
				if(window.location.hash === '') {
					$('.js-phytoplankton-home').addClass('active');
				}

			});
		}
	});
	return DashboardPage;
});<commit_msg>Kinda fixed ghost menu item issue<commit_after>define([
	'jquery',
	'underscore',
	'libs/underscore/underscore.string.min',
	'backbone',
	'text!templates/style/menu.html',
	'jscssp',
	'config',
	'libs/marked/marked'
],
function($, _, str, Backbone, dashboardPageTemplate, jscssp, config, marked) {
	var DashboardPage = Backbone.View.extend({
		el: '.js-phytoplankton-menu',
		events: {
			'click .phytoplankton-menu__list__item__link': function (ev) {
				if($(ev.currentTarget).hasClass('active')) {
					ev.preventDefault();
				} else {
					this.$el.find('.active').removeClass('active');
					$(ev.currentTarget).addClass('active');
					$(ev.currentTarget).parent().find('li:first-child').addClass('active');
				}
			},
			'click .phytoplankton-menu__list__item a': function() {
				$('.js-phytoplankton-menu').removeClass('is-active');
				$('body').removeClass('is-opaque is-locked');
			},
			'click .phytoplankton-menu__list__item ul li ul li a': function(ev) {
				ev.preventDefault();
				var scrollAnchor = $(ev.currentTarget).attr('href');
				var scrollAnchor = scrollAnchor.substr(scrollAnchor.lastIndexOf('#') + 1);
				var scrollPoint = $('.phytoplankton-page__item *[id="' + scrollAnchor + '"]').offset().top - (50 + 40);
				$('html, body').animate({
					scrollTop: scrollPoint
				}, '200');
			}
		},
		render: function () {

			var that = this;

			that.$el.html('Loading styles');

			var page = {blocks:[]};

			require(['text!' + config.css_path], function (styles) {
				// Default "imports.css"
				var markedOpts = _.extend({
										sanitize: false,
										gfm: true
									},
									config.marked_options || {}
								);
				marked.setOptions(markedOpts);

				var parser = new jscssp();
				var stylesheet = parser.parse(styles, false, true);
				var menus = [];
				var menuTitle = '';
				var currentMenu = {
					sheets: [],
					category: ''
				};
				var sheetPath;

				_.each(stylesheet.cssRules, function(rule) {
					// If /* Comment */
					if(rule.type === 101) {
						var comment = rule.parsedCssText;
						comment = comment.replace('/*', '');
						comment = comment.replace('*/', '');

						var comments = marked.lexer(comment);
						var defLinks = comments.links || {};
						_.each(comments, function (comment) {
							var tokens = [comment];
							tokens.links = defLinks;
							if(comment.type === 'heading' && comment.depth === 1) {
								menus.push(_.extend({}, currentMenu));
								currentMenu.sheets = [];
								currentMenu.category = comment.text;
							}
						});
					}
					// If @import url('');
					if(rule.type === 3) {
						// Removes @import url(''); leaving just the style sheet name.
						var sheet = rule.href.substr(rule.href.indexOf('(')+2, rule.href.indexOf(')')-rule.href.indexOf('(')-3);

						var regex = /(?:.*\/)(.*)\.(css|sass|scss|less)$/gi;
						var result = [];
						if((result = regex.exec(sheet)) !== null) {
							// result[0] Original Input.
							// result[1] Filename.
							// result[2] Extension.

							// Returns the path before 'extension/'.
							sheetPath = result[0].substr(0, result[0].lastIndexOf('' + result[2] + '/') + (result[2].length + 1));
							// Removes 'sheetPath' from 'sheet' leaving the path after 'extension/'.
							sheet = result[0].replace(sheetPath, '');
						}
						// Pushes style sheet to currentMenu.
						currentMenu.sheets.push(sheet);
					}
				});

				if(config.css_paths) {
					for(var i = 0; i < config.css_paths.length; i++) {
						var regex = /(?:.*\/)(.*)\.(css|sass|scss|less)$/gi;
						var result = [];
						if((result = regex.exec(config.css_paths[i])) !== null) {
							// result[0] Original Input.
							// result[1] Filename.
							// result[2] Extension.

							// Returns the path before 'extension/'.
							sheetPath = result[0].substr(0, result[0].lastIndexOf('' + result[2] + '/') + (result[2].length + 1));
							// Removes 'sheetPath' from 'sheet' leaving the path after 'extension/'.
							config.css_paths[i] = result[0].replace(sheetPath, '');
						}
						// Pushes style sheet to currentMenu.
						currentMenu.sheets.push(config.css_paths[i]);
					}
				}

				// Removes first item in 'menus' array, I don't know why but we have to do it...
				menus.shift();
				// Pushes the corrected version of 'menus'.
				menus.push(currentMenu);

				$(that.el).html(_.template(dashboardPageTemplate, {_:_, menus: menus}));
				$('[href="' + window.location.hash + '"]').addClass('active');
				if(window.location.hash === '') {
					$('.js-phytoplankton-home').addClass('active');
				}

			});
		}
	});
	return DashboardPage;
});<|endoftext|>