<commit_before>/*  NETPIE Microgear Freeboard plugin                             */
/*  Developed by Chavee Issariyapat                               */
/*  More information about NETPIE please visit https://netpie.io  */

if (typeof dsstore === "undefined") {
    dsstore = {};
}

(function()
{
    freeboard.loadDatasourcePlugin({
        "type_name"   : "netpie_feed",
        "display_name": "NETPIE Feed",
        "description" : "NETPIE Feed Datasource.",
        "external_scripts" : [
            "https://cdn.netpie.io/microgear.js"
        ],
        "settings"    : [
            {
                "name"         : "feedid",
                "display_name" : "Feed ID",
                "type"         : "text",
                //"description"  : "Feed ID",
                "required" : true
            },
            {
                "name"         : "apikey",
                "display_name" : "API Key",
                "type"         : "text",
                //"description"  : "Key",
                //"required"     : true
            },
            {
                "name"         : "granularity_value",
                "display_name" : "Granularity",
                "type"         : "text",
                "default_value": "5",
                "required"     : false,
            },
            {
                name: "granularity_unit",
                display_name: "",
                type: "option",
                "description"  : "Resolution of the data points.",
                options:[
                    {
                        name: "Second",
                        value: "seconds"
                    },
                    {
                        name: "Minute",
                        value: "minutes"
                    },
                    {
                        name: "Hour",
                        value: "hours"
                    },
                    {
                        name: "Day",
                        value: "days"
                    },
                    {
                        name: "Month",
                        value: "months"
                    },
                    {
                        name: "Year",
                        value: "years"
                    }
                ],
                "default_value": "minutes",
            },
            {
                "name"         : "since_value",
                "display_name" : "Since",
                "type"         : "text",
                "default_value": "6",
                "required"     : false,
            },
            {
                name: "since_unit",
                display_name: "",
                type: "option",
                "description"  : "Display data points since ... ago.",
                options:[
                    {
                        name: "Second",
                        value: "seconds"
                    },
                    {
                        name: "Minute",
                        value: "minutes"
                    },
                    {
                        name: "Hour",
                        value: "hours"
                    },
                    {
                        name: "Day",
                        value: "days"
                    },
                    {
                        name: "Month",
                        value: "months"
                    },
                    {
                        name: "Year",
                        value: "years"
                    }
                ],
                "default_value": "hours",
            },
            {
                "name"         : "from_value",
                "display_name" : "From",
                "type"         : "text",
                "default_value": "",
                "description"  : "Timestamp in milliseconds.",
                "required"     : false,
            },
            {
                "name"         : "to_value",
                "display_name" : "To",
                "type"         : "text",
                "default_value": "",
                "description"  : "Timestamp in milliseconds",
                "required"     : false,
            },
            {
                "name"          : "interval",
                "display_name"  : "Reload Every",
                "type"          : "text",
                "description"   : "Data reload interval (seconds)",
                "default_value" : "15"
            }

        ],

        newInstance : function(settings, newInstanceCallback, updateCallback) {
            newInstanceCallback(new feedDatasourcePlugin(settings, updateCallback));
        }
    });

    var feedDatasourcePlugin = function(settings, updateCallback) {
        var self = this;
        var apiChanged = false;
        var currentSettings = settings;
        var interval = settings.interval;
        var data = {};
        dsstore[currentSettings.name] = {};
        var timelist ={seconds:1000,minutes:1000*60,hours:1000*60*60,days:1000*60*60*24,months:1000*60*60*24*30,years:1000*60*60*24*30*12}

        function reloadhData(s) {
            if(typeof data['data'] !== "undefined"){
                var timenow = new Date().getTime();
                var lasttime;
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    for (var j = 0; j<data['data']['data'][i]['values'].length; j++) {
                        if(typeof data['data']['data'][i]['values'][j] !== "undefined"){
                            if(data['data']['data'][i]['values'][j][0]+s.since_value*timelist[s.since_unit]<timenow){
                                data['data']['data'][i]['values'].splice(j, 1)
                            }
                        }
                        lasttime = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                    }
                }

                var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+lasttime+'&to='+timenow;
                $.getJSON( apiurl, function(datajson) {
                    if(typeof datajson['lastest_data'] !== "undefined"){
                        for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                            data['data']['data'][i]['values'].splice(data['data']['data'][i]['values'].length-1, 1)
                            data['data']['data'][i]['values'] = data['data']['data'][i]['values'].concat(datajson['data'][i]['values']);
                        }
                        data['data']['to'] = timenow;
                        updateCallback(data);
                    }
                });
            }
            else{
                var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&since='+s.since_value+s.since_unit;
                $.getJSON( apiurl, function(datajson) {
                    data['data'] = datajson;
                    var newfrom;
                    var newto;
                    if(typeof data['data']['lastest_data'] !== "undefined"){
                        for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                            var timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                            if(data['data']['lastest_data'][i]['values'][0][0]>timelastitem+timelist[data['data']['granularity'][1]]*data['data']['granularity'][0]){
                                if(typeof newfrom === "undefined"){
                                    newfrom = timelastitem+1000;
                                    newto = data['data']['lastest_data'][i]['values'][0][0];
                                }
                                else{
                                    if(newfrom>timelastitem){
                                        newfrom = timelastitem;
                                    }
                                }
                            }
                        }
                    }
                    updateCallback(data);
                    if(typeof newfrom !== "undefined"){
                        reloadjData(s,newfrom,newto)
                    }
                });
            }
        }
        function reloadiData(s) {
            if(typeof data['data'] !== "undefined"){
                var timenow = new Date().getTime();
                var timelastitem;
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    if(typeof timelastitem === "undefined"){
                        timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                    }
                    else{
                        if(timelastitem<data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0]){
                            timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                        }
                    }

                }
                if(s.to_value>timenow){
                    var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+timelastitem+'&to='+s.to_value;
                    $.getJSON( apiurl, function(datajson) {
                        if(typeof datajson['lastest_data'] !== "undefined"){
                            for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                                data['data']['data'][i]['values'].splice(data['data']['data'][i]['values'].length-1, 1)
                                data['data']['data'][i]['values'] = data['data']['data'][i]['values'].concat(datajson['data'][i]['values']);
                            }
                            updateCallback(data);
                        }
                    });
                }

            }
            else{
                var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+s.from_value+'&to='+s.to_value;
                $.getJSON( apiurl, function(datajson) {
                    data['data'] = datajson;
                    var newfrom;
                    var newto;
                    if(typeof data['data']['lastest_data'] !== "undefined"){
                        for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                            var timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                            if(data['data']['lastest_data'][i]['values'][0][0]>timelastitem+timelist[data['data']['granularity'][1]]*data['data']['granularity'][0]){
                                if(typeof newfrom === "undefined"){
                                    newfrom = timelastitem+1000;
                                    newto = data['data']['lastest_data'][i]['values'][0][0];
                                }
                                else{
                                    if(newfrom>timelastitem){
                                        newfrom = timelastitem;
                                    }
                                }
                            }
                        }
                    }
                    updateCallback(data);
                    if(typeof newfrom !== "undefined"){
                        reloadjData(s,newfrom,newto)
                    }
                });
            }
        }

        function reloadjData(s,from,to) {
            var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+from+'&to='+to;
            $.getJSON( apiurl, function(datajson) {
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    data['data']['data'][i]['values'] = data['data']['data'][i]['values'].concat(datajson['data'][i]['values']);
                }
                var newfrom;
                var newto;
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    var timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                    if(data['data']['lastest_data'][i]['values'][0][0]>timelastitem+timelist[data['data']['granularity'][1]]*data['data']['granularity'][0]){
                        if(typeof newfrom === "undefined"){
                            newfrom = timelastitem+1000;
                            newto = data['data']['lastest_data'][i]['values'][0][0];
                            //data['data']['to'] = newto;
                        }
                        else{
                            if(newfrom>timelastitem){
                                newfrom = timelastitem;
                            }
                        }
                    }
                }
                updateCallback(data);
                if(typeof newfrom !== "undefined"){
                    reloadjData(s,newfrom,newto)
                }
            });
        }

        if (currentSettings.interval > 0) {

            setTimeout(function() {
                if(typeof currentSettings.from_value !== "undefined" && typeof currentSettings.to_value!== "undefined"){
                    if(currentSettings.from_value.length!=0&&currentSettings.to_value!=0){
                        reloadiData(currentSettings);
                    }
                    else{
                        reloadhData(currentSettings);
                    }
                }
                else{
                    reloadhData(currentSettings);
                }
            },500);

            dsstore[currentSettings.name]['timer'] = setInterval(function() {
                if(currentSettings.from_value.length!=0 &&currentSettings.to_value.length!=0){
                    reloadiData(currentSettings);
                }
                else{
                    reloadhData(currentSettings);
                }
            }, currentSettings.interval*1000);
        }

        self.updateNow = function() {

        }

        self.onSettingsChanged = function(newSettings) {
            if (currentSettings.name != newSettings.name) {
                if (dsstore && dsstore[currentSettings.name] && dsstore[currentSettings.name]['timer']) {
                    clearInterval(dsstore[currentSettings.name]['timer']);
                }
                dsstore[newSettings.name] = dsstore[currentSettings.name];
                dsstore[currentSettings.name] = null;
                delete(dsstore[currentSettings.name]);
            }

            if (
                newSettings.interval != currentSettings.interval ||
                newSettings.granularity_value != currentSettings.granularity_value ||
                newSettings.granularity_unit != currentSettings.granularity_unit ||
                newSettings.since_value != currentSettings.since_value ||
                newSettings.since_unit != currentSettings.since_unit ||
                newSettings.from_value != currentSettings.from_value ||
                newSettings.to_value != currentSettings.to_value ||
                false ) apiChanged = true;

            if (apiChanged) {
                if (dsstore && dsstore[newSettings.name] && dsstore[newSettings.name]['timer']) {
                    clearInterval(dsstore[newSettings.name]['timer']);
                }
                dsstore[newSettings.name]['timer'] = setInterval(function() {
                    if(currentSettings.from_value.length!=0 &&currentSettings.to_value.length!=0){
                        reloadiData(currentSettings);
                    }
                    else{
                        reloadhData(currentSettings);
                    }
                }, newSettings.interval*1000);
                apiChanged = false;
            }

            currentSettings = newSettings;
            setTimeout(function(){
                data = {};
                if(currentSettings.from_value.length!=0 &&currentSettings.to_value.length!=0){
                    reloadiData(currentSettings);
                }
                else{
                    reloadhData(currentSettings);
                }
            },500);

        }

        self.onDispose = function() {
            delete(self.mg);
        }

    }
}());
<commit_msg>update feedview to support rate limit exceeded<commit_after>/*  NETPIE Microgear Freeboard plugin                             */
/*  Developed by Chavee Issariyapat                               */
/*  More information about NETPIE please visit https://netpie.io  */

if (typeof dsstore === "undefined") {
    dsstore = {};
}

(function()
{
    freeboard.loadDatasourcePlugin({
        "type_name"   : "netpie_feed",
        "display_name": "NETPIE Feed",
        "description" : "NETPIE Feed Datasource.",
        "external_scripts" : [
            "https://cdn.netpie.io/microgear.js"
        ],
        "settings"    : [
            {
                "name"         : "feedid",
                "display_name" : "Feed ID",
                "type"         : "text",
                //"description"  : "Feed ID",
                "required" : true
            },
            {
                "name"         : "apikey",
                "display_name" : "API Key",
                "type"         : "text",
                //"description"  : "Key",
                //"required"     : true
            },
            {
                "name"         : "granularity_value",
                "display_name" : "Granularity",
                "type"         : "text",
                "default_value": "5",
                "required"     : false,
            },
            {
                name: "granularity_unit",
                display_name: "",
                type: "option",
                "description"  : "Resolution of the data points.",
                options:[
                    {
                        name: "Second",
                        value: "seconds"
                    },
                    {
                        name: "Minute",
                        value: "minutes"
                    },
                    {
                        name: "Hour",
                        value: "hours"
                    },
                    {
                        name: "Day",
                        value: "days"
                    },
                    {
                        name: "Month",
                        value: "months"
                    },
                    {
                        name: "Year",
                        value: "years"
                    }
                ],
                "default_value": "minutes",
            },
            {
                "name"         : "since_value",
                "display_name" : "Since",
                "type"         : "text",
                "default_value": "6",
                "required"     : false,
            },
            {
                name: "since_unit",
                display_name: "",
                type: "option",
                "description"  : "Display data points since ... ago.",
                options:[
                    {
                        name: "Second",
                        value: "seconds"
                    },
                    {
                        name: "Minute",
                        value: "minutes"
                    },
                    {
                        name: "Hour",
                        value: "hours"
                    },
                    {
                        name: "Day",
                        value: "days"
                    },
                    {
                        name: "Month",
                        value: "months"
                    },
                    {
                        name: "Year",
                        value: "years"
                    }
                ],
                "default_value": "hours",
            },
            {
                "name"         : "from_value",
                "display_name" : "From",
                "type"         : "text",
                "default_value": "",
                "description"  : "Timestamp in milliseconds.",
                "required"     : false,
            },
            {
                "name"         : "to_value",
                "display_name" : "To",
                "type"         : "text",
                "default_value": "",
                "description"  : "Timestamp in milliseconds",
                "required"     : false,
            },
            {
                "name"          : "interval",
                "display_name"  : "Reload Every",
                "type"          : "text",
                "description"   : "Data reload interval (seconds)",
                "default_value" : "15"
            }

        ],

        newInstance : function(settings, newInstanceCallback, updateCallback) {
            newInstanceCallback(new feedDatasourcePlugin(settings, updateCallback));
        }
    });

    var feedDatasourcePlugin = function(settings, updateCallback) {
        var self = this;
        var apiChanged = false;
        var currentSettings = settings;
        var interval = settings.interval;
        var data = {};
        dsstore[currentSettings.name] = {};
        var timelist ={seconds:1000,minutes:1000*60,hours:1000*60*60,days:1000*60*60*24,months:1000*60*60*24*30,years:1000*60*60*24*30*12}

        function reloadhData(s) {
            if(typeof data['data'] !== "undefined"){
                var timenow = new Date().getTime();
                var lasttime;
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    for (var j = 0; j<data['data']['data'][i]['values'].length; j++) {
                        if(typeof data['data']['data'][i]['values'][j] !== "undefined"){
                            if(data['data']['data'][i]['values'][j][0]+s.since_value*timelist[s.since_unit]<timenow){
                                data['data']['data'][i]['values'].splice(j, 1)
                            }
                        }
                        lasttime = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                    }
                }

                var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+lasttime+'&to='+timenow;
                $.getJSON( apiurl, function(datajson) {
                    if(typeof datajson['lastest_data'] !== "undefined"){
                        for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                            data['data']['data'][i]['values'].splice(data['data']['data'][i]['values'].length-1, 1)
                            data['data']['data'][i]['values'] = data['data']['data'][i]['values'].concat(datajson['data'][i]['values']);
                        }
                        data['data']['to'] = timenow;
                        updateCallback(data);
                    }
                });
            }
            else{
                var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&since='+s.since_value+s.since_unit;
                $.getJSON( apiurl, function(datajson) {
                    data['data'] = datajson;
                    var newfrom;
                    var newto;
                    if(typeof data['data']['lastest_data'] !== "undefined"){
                        for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                            var timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                            if(data['data']['lastest_data'][i]['values'][0][0]>timelastitem+timelist[data['data']['granularity'][1]]*data['data']['granularity'][0]){
                                if(typeof newfrom === "undefined"){
                                    newfrom = timelastitem+1000;
                                    newto = data['data']['lastest_data'][i]['values'][0][0];
                                }
                                else{
                                    if(newfrom>timelastitem){
                                        newfrom = timelastitem;
                                    }
                                }
                            }
                        }
                    }
                    updateCallback(data);
                    if(typeof newfrom !== "undefined"){
                        reloadjData(s,newfrom,newto)
                    }
                });
            }
        }
        function reloadiData(s) {
            if(typeof data['data'] !== "undefined"){
                var timenow = new Date().getTime();
                var timelastitem;
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    if(typeof timelastitem === "undefined"){
                        timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                    }
                    else{
                        if(timelastitem<data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0]){
                            timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                        }
                    }

                }
                if(s.to_value>timenow){
                    var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+timelastitem+'&to='+s.to_value;
                    $.getJSON( apiurl, function(datajson) {
                        if(typeof datajson['lastest_data'] !== "undefined"){
                            for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                                data['data']['data'][i]['values'].splice(data['data']['data'][i]['values'].length-1, 1)
                                data['data']['data'][i]['values'] = data['data']['data'][i]['values'].concat(datajson['data'][i]['values']);
                            }
                            updateCallback(data);
                        }
                    });
                }

            }
            else{
                var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+s.from_value+'&to='+s.to_value;
                $.getJSON( apiurl, function(datajson) {
                    data['data'] = datajson;
                    var newfrom;
                    var newto;
                    if(typeof data['data']['lastest_data'] !== "undefined"){
                        for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                            var timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                            if(data['data']['lastest_data'][i]['values'][0][0]>timelastitem+timelist[data['data']['granularity'][1]]*data['data']['granularity'][0]){
                                if(typeof newfrom === "undefined"){
                                    newfrom = timelastitem+1000;
                                    newto = data['data']['lastest_data'][i]['values'][0][0];
                                }
                                else{
                                    if(newfrom>timelastitem){
                                        newfrom = timelastitem;
                                    }
                                }
                            }
                        }
                    }
                    updateCallback(data);
                    if(typeof newfrom !== "undefined"){
                        reloadjData(s,newfrom,newto)
                    }
                });
            }
        }

        function reloadjData(s,from,to) {
            var apiurl = 'https://api.netpie.io/feed/'+s.feedid+'?apikey='+s.apikey+'&granularity='+s.granularity_value+s.granularity_unit+'&aggregate=avg&from='+from+'&to='+to;
            $.getJSON( apiurl, function(datajson) {
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    data['data']['data'][i]['values'] = data['data']['data'][i]['values'].concat(datajson['data'][i]['values']);
                }
                var newfrom;
                var newto;
                for (var i = 0; i<data['data']['lastest_data'].length ; i++) {
                    var timelastitem = data['data']['data'][i]['values'][data['data']['data'][i]['values'].length-1][0];
                    if(data['data']['lastest_data'][i]['values'][0][0]>timelastitem+timelist[data['data']['granularity'][1]]*data['data']['granularity'][0]){
                        if(typeof newfrom === "undefined"){
                            newfrom = timelastitem+1000;
                            newto = data['data']['lastest_data'][i]['values'][0][0];
                            //data['data']['to'] = newto;
                        }
                        else{
                            if(newfrom>timelastitem){
                                newfrom = timelastitem;
                            }
                        }
                    }
                }
                updateCallback(data);
                if(typeof newfrom !== "undefined"){
                    reloadjData(s,newfrom,newto)
                }
            });
        }

        if (currentSettings.interval > 0) {

            setTimeout(function() {
                if(typeof currentSettings.from_value !== "undefined" && typeof currentSettings.to_value!== "undefined"){
                    if(currentSettings.from_value.length!=0&&currentSettings.to_value!=0){
                        reloadiData(currentSettings);
                    }
                    else{
                        reloadhData(currentSettings);
                    }
                }
                else{
                    reloadhData(currentSettings);
                }
            },500);

            dsstore[currentSettings.name]['timer'] = setInterval(function() {
                if(typeof currentSettings.from_value !== "undefined" && typeof currentSettings.to_value!== "undefined"){
                    if(currentSettings.from_value.length!=0&&currentSettings.to_value!=0){
                        reloadiData(currentSettings);
                    }
                    else{
                        reloadhData(currentSettings);
                    }
                }
                else{
                    reloadhData(currentSettings);
                }
            }, currentSettings.interval*1000);
        }

        self.updateNow = function() {

        }

        self.onSettingsChanged = function(newSettings) {
            if (currentSettings.name != newSettings.name) {
                if (dsstore && dsstore[currentSettings.name] && dsstore[currentSettings.name]['timer']) {
                    clearInterval(dsstore[currentSettings.name]['timer']);
                }
                dsstore[newSettings.name] = dsstore[currentSettings.name];
                dsstore[currentSettings.name] = null;
                delete(dsstore[currentSettings.name]);
            }

            if (
                newSettings.interval != currentSettings.interval ||
                newSettings.granularity_value != currentSettings.granularity_value ||
                newSettings.granularity_unit != currentSettings.granularity_unit ||
                newSettings.since_value != currentSettings.since_value ||
                newSettings.since_unit != currentSettings.since_unit ||
                newSettings.from_value != currentSettings.from_value ||
                newSettings.to_value != currentSettings.to_value ||
                false ) apiChanged = true;

            if (apiChanged) {
                if (dsstore && dsstore[newSettings.name] && dsstore[newSettings.name]['timer']) {
                    clearInterval(dsstore[newSettings.name]['timer']);
                }
                dsstore[newSettings.name]['timer'] = setInterval(function() {
                    if(currentSettings.from_value.length!=0 &&currentSettings.to_value.length!=0){
                        reloadiData(currentSettings);
                    }
                    else{
                        reloadhData(currentSettings);
                    }
                }, newSettings.interval*1000);
                apiChanged = false;
            }

            currentSettings = newSettings;
            setTimeout(function(){
                data = {};
                if(currentSettings.from_value.length!=0 &&currentSettings.to_value.length!=0){
                    reloadiData(currentSettings);
                }
                else{
                    reloadhData(currentSettings);
                }
            },500);

        }

        self.onDispose = function() {
            delete(self.mg);
        }

    }
}());
<|endoftext|>


<commit_before>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * Taolin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation version 3 of the License.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Taolin. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
  * Ext.ux.fbk.sonet.UserProfile
  *
  * @author  Marco Frassoni and Davide Setti
  * @class Ext.ux.fbk.sonet.UserProfile
  * #@extends Ext.Panel
  * Shows a user's profile
  *
  */
Ext.ns( 'Ext.ux.fbk.sonet' );

Ext.ux.fbk.sonet.UserProfile = Ext.extend(Ext.Panel, {
    title:'User profile',
    autoScroll:true,
    border:false,
    collapsible:true,
    hideCollapseTool:true,
    frame:true,
    iconCls:'user_info',
    tools: toolsnotclose
    ,initComponent: function(){
        var config = {
            items: [{
                border: false,
                html:
                    '

' +
                        '' +
                            '
' +
                                '' +
                                '
' +
                                    'Change photo' +
                                    '' +
                                '
' +
                            '
' +
                        '	' +
                        '' +
                            '

' +
                        '	' +
                    '

' +
                    '
' +
                        '
' +
                            '' +
                            'Edit your profile' +
                        '
' +
                        '
' +
                            '' +
                            'Edit your photos' +
                        '
' +
                        '
' +
                           '' +
                           'Edit workplace' +
                        '
' +
                    '
'
            },{
                xtype:'tabpanel',
                border: false,
                tabWidth:115,
                enableTabScroll:true,
                autoWidth: true,
                autoHeight: true,
                activeTab: 0,
                layoutOnTabChange:true,
                plain:true,
                frame:false,
                defaults: {
                    autoScroll:true
                },
                items: [{
                        title: 'Information',
                        html: '

',
                        autoHeight: true
                    },{
                        title: 'Events'
                        ,xtype: 'timeline'
                        ,autoHeight: true
                        ,iconCls: null
                        ,bodyStyle: 'padding-right:15px'
                        ,id: 'user_info_timeline'
                        ,autoLoad: false
                        ,listeners:{
                            'activate': function(p){
                                if(westPanel.showedUser.id != p.view.store.baseParams.u_id) {
                                    console.log('Cambio!');
                                    p.view.store.setBaseParam('u_id', westPanel.showedUser.id);
                                    p.view.store.reload();
                                }
                            }
                        }
                    },{
                        xtype:'userpublications'
                        ,id:'wp-publik-tab'
                    },{
                        xtype:'userphotos'
                        ,id:'wp-photos-tab'
                    }                ]
            }]

        };
        Ext.apply(this, Ext.apply(this.initialConfig, config));

        Ext.ux.fbk.sonet.UserProfile.superclass.initComponent.apply(this, arguments);

    }
});

Ext.reg('userprofile', Ext.ux.fbk.sonet.UserProfile);
<commit_msg>console.log dropped<commit_after>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * Taolin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation version 3 of the License.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Taolin. If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
  * Ext.ux.fbk.sonet.UserProfile
  *
  * @author  Marco Frassoni and Davide Setti
  * @class Ext.ux.fbk.sonet.UserProfile
  * #@extends Ext.Panel
  * Shows a user's profile
  *
  */
Ext.ns( 'Ext.ux.fbk.sonet' );

Ext.ux.fbk.sonet.UserProfile = Ext.extend(Ext.Panel, {
    title:'User profile',
    autoScroll:true,
    border:false,
    collapsible:true,
    hideCollapseTool:true,
    frame:true,
    iconCls:'user_info',
    tools: toolsnotclose
    ,initComponent: function(){
        var config = {
            items: [{
                border: false,
                html:
                    '

' +
                        '' +
                            '
' +
                                '' +
                                '
' +
                                    'Change photo' +
                                    '' +
                                '
' +
                            '
' +
                        '	' +
                        '' +
                            '

' +
                        '	' +
                    '

' +
                    '
' +
                        '
' +
                            '' +
                            'Edit your profile' +
                        '
' +
                        '
' +
                            '' +
                            'Edit your photos' +
                        '
' +
                        '
' +
                           '' +
                           'Edit workplace' +
                        '
' +
                    '
'
            },{
                xtype:'tabpanel',
                border: false,
                tabWidth:115,
                enableTabScroll:true,
                autoWidth: true,
                autoHeight: true,
                activeTab: 0,
                layoutOnTabChange:true,
                plain:true,
                frame:false,
                defaults: {
                    autoScroll:true
                },
                items: [{
                        title: 'Information',
                        html: '

',
                        autoHeight: true
                    },{
                        title: 'Events'
                        ,xtype: 'timeline'
                        ,autoHeight: true
                        ,iconCls: null
                        ,bodyStyle: 'padding-right:15px'
                        ,id: 'user_info_timeline'
                        ,autoLoad: false
                        ,listeners:{
                            'activate': function(p){
                                if(westPanel.showedUser.id != p.view.store.baseParams.u_id) {
                                    p.view.store.setBaseParam('u_id', westPanel.showedUser.id);
                                    p.view.store.reload();
                                }
                            }
                        }
                    },{
                        xtype:'userpublications'
                        ,id:'wp-publik-tab'
                    },{
                        xtype:'userphotos'
                        ,id:'wp-photos-tab'
                    }                ]
            }]

        };
        Ext.apply(this, Ext.apply(this.initialConfig, config));

        Ext.ux.fbk.sonet.UserProfile.superclass.initComponent.apply(this, arguments);

    }
});

Ext.reg('userprofile', Ext.ux.fbk.sonet.UserProfile);
<|endoftext|>


<commit_before>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * This file is a modified version of a file of Ext JS Library 2.0.2
 * (see copyright below).
 * According to the Ext JS Library 2.0.2 license (see
 * http://extjs.com/license ), Ext JS Library 2.0.2 is double licensed.
 * Within the license we could choose among, we release our modified
 * version under GPLv3.0.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * In order to obtain further information on GNU General Public License
 * see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * Ext JS Library 2.0.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

Ext.ux.Portlet = Ext.extend(Ext.Panel, {
    anchor: '100%',
    frame:true,
    collapsible:true,
    draggable:true,
    autoDestroy:true,
    cls:'x-portlet',
    onRender: function(){
        Ext.ux.Portlet.superclass.onRender.apply(this, arguments);

        var jPortlet = $('#' + this.getId());
        var tools = jPortlet.find('.x-tool');
        tools.css({
            visibility: 'hidden'
        });

        //hoverIntent provided some problems with tooltip so we
        //decided to switch back to hover even if it doesn't
        //completely work with IE
        jPortlet.hover(function(){
                tools.css({
                    visibility: 'visible'
                });
            }, function(){
                tools.css({
                    visibility: 'hidden'
                });
        });
    },
    listeners: {
        resize: {
            fn: function(panel, panelWidth, panelHeight){
                panel.items.last().setWidth(panelWidth);
            },
            scope: this
        }
        ,expand: function(panel){
            var w = panel.getInnerWidth();
            panel.items.last().setWidth(w-1);
            panel.items.last().setWidth(w);
        }
    },
    updateWidget: function(conf){
        if (conf)
            this.lastConf = conf;
        else
            var conf = this.lastConf;

        var w_class = Ext.util.JSON.decode(conf.string_identifier);

        //TODO: this doesn't need to be done for every instantiation
        w_class.prototype.setPortletTitle = function(title) {Ext.getCmp(this.portlet_id).setTitle(title);};
        w_class.prototype.setPref = function(pref, value) {Ext.getCmp(this.portlet_id).setPref(pref, value);};

        this.remove(this.items.last());
        this.add(new w_class(conf.widget_conf, {portlet_id: conf.id}));
        this.userParams = conf.user_params; //user's configurable params (name, type, description)
        this.widgetConf = conf.widget_conf; //params value

        this.doLayout();

    },
    showConf: function(){

        if ((!this.userParams) || (this.userParams.length == 0))
            return;

        if (this.confForm){
            this.remove(this.items.items[0], true);
            this.confForm = null;
            return;
        }
        else if(this.collapsed)
            // if the widget is collapsed, expand it before showing the confForm
            this.toggleCollapse(true);

        this.confForm = new Ext.form.FormPanel({
            //baseCls: 'feedback_widget'
            autoHeight: true
            //,title: 'Change your settings'
            ,bodyStyle:'padding:10px;background:transparent'
            ,style:'background:#F5F5F5 url(img/portlet_conf_bg.png) repeat-x scroll center top;border-style:none none solid;border-width:0 0 1px; border-color: #DDDDDD'
            ,buttonAlign: 'center'
            ,items: [
            {
                xtype: 'hidden'
                ,name: 'id'
                ,value: this.getId()
            }],

            buttons: [{
                text: 'Change',
                handler: function(){
                    this.confForm.getForm().submit(
                        {
                            url:'users_widgets/changeconf',
                            //waitMsg:'Saving Data...',
                            scope:this,
                            success: function(form,action){
                                this.remove(this.items.items[0], true);
                                this.confForm = null;

                                this.updateWidget(action.result.widget);
                            }
                    }
                    );
                },
                scope: this,
                formBind: true
            }
            ,{
                text: 'Cancel'
                ,handler: function(){
                    this.remove(this.items.items[0], true);
                    this.confForm = null;
                }
                ,scope: this
            }
            ]
        });

        var field;
        for (var i=0, x; x = this.userParams[i++];){
            field = {};
            if(x.type=='string') {
                field.xtype = 'textfield';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
            }
            else if(x.type=='integer') {
                field.xtype = 'textfield';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
            }
            else if(x.type=='boolean') {
                field.xtype = 'checkbox';
                field.boxLabel = x.description ? x.description : x.name;
                field.hideLabel = true;
                if (this.widgetConf[x.name])
                    field.checked = this.widgetConf[x.name];
            }
            else if(x.type=='color') {
                field.xtype = 'colorpickerfield';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
            }
            else if(x.type=='BooleanList') {
                field.xtype = 'checkboxgroup';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                field.columns = 2;
                field.items = new Array();

                var i = 0;
                for (var k in x.values){ //create checkboxes
                    // use key as checkbox label unless a title has been specified
                    var label = k;
                    if ('title' in x.values[k])
                        label = x.values[k].title;

                    var cb = { //checkbox
                        xtype: 'checkbox'
                        ,boxLabel: label
                        ,inputValue: k
                        ,name: x.name+"_"+i
                    };

                    field.items.push(cb);
                    i++;
                }

                this.confForm.add({
                    xtype: 'hidden'
                    ,name: x.name //length
                    ,value: i
                });

                /*

                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
                */
            }
            field.name = x.name;
            this.confForm.add(field);
        }

        this.insert(0, this.confForm);
        this.doLayout();
    }
    ,setPref:function(pref, value, callbackfun){

        var params = {id: this.getId()};
        params[pref] = value;

        Ext.Ajax.request({
            url : 'users_widgets/changeconf'
            ,method: 'POST'
            ,params: params
            ,callback: callbackfun
       });
    }
});
Ext.reg('portlet', Ext.ux.Portlet);
<commit_msg>If the tab is already present in the widget,<commit_after>/**
 * This file is part of taolin project (http://taolin.fbk.eu)
 * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
 * Authors: SoNet Group (see AUTHORS.txt)
 *
 * This file is a modified version of a file of Ext JS Library 2.0.2
 * (see copyright below).
 * According to the Ext JS Library 2.0.2 license (see
 * http://extjs.com/license ), Ext JS Library 2.0.2 is double licensed.
 * Within the license we could choose among, we release our modified
 * version under GPLv3.0.
 *
 * Taolin is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * In order to obtain further information on GNU General Public License
 * see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * Ext JS Library 2.0.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

Ext.ux.Portlet = Ext.extend(Ext.Panel, {
    anchor: '100%',
    frame:true,
    collapsible:true,
    draggable:true,
    autoDestroy:true,
    cls:'x-portlet',
    onRender: function(){
        Ext.ux.Portlet.superclass.onRender.apply(this, arguments);

        var jPortlet = $('#' + this.getId());
        var tools = jPortlet.find('.x-tool');
        tools.css({
            visibility: 'hidden'
        });

        //hoverIntent provided some problems with tooltip so we
        //decided to switch back to hover even if it doesn't
        //completely work with IE
        jPortlet.hover(function(){
                tools.css({
                    visibility: 'visible'
                });
            }, function(){
                tools.css({
                    visibility: 'hidden'
                });
        });
    },
    listeners: {
        resize: {
            fn: function(panel, panelWidth, panelHeight){
                panel.items.last().setWidth(panelWidth);
            },
            scope: this
        }
        ,expand: function(panel){
            var w = panel.getInnerWidth();
            panel.items.last().setWidth(w-1);
            panel.items.last().setWidth(w);
        }
    },
    updateWidget: function(conf){
        if (conf)
            this.lastConf = conf;
        else
            var conf = this.lastConf;

        var w_class = Ext.util.JSON.decode(conf.string_identifier);

        //TODO: this doesn't need to be done for every instantiation
        w_class.prototype.setPortletTitle = function(title) {Ext.getCmp(this.portlet_id).setTitle(title);};
        w_class.prototype.setPref = function(pref, value) {Ext.getCmp(this.portlet_id).setPref(pref, value);};

        this.remove(this.items.last());
        this.add(new w_class(conf.widget_conf, {portlet_id: conf.id}));
        this.userParams = conf.user_params; //user's configurable params (name, type, description)
        this.widgetConf = conf.widget_conf; //params value

        this.doLayout();

    },
    showConf: function(){

        if ((!this.userParams) || (this.userParams.length == 0))
            return;

        if (this.confForm){
            this.remove(this.items.items[0], true);
            this.confForm = null;
            return;
        }
        else if(this.collapsed)
            // if the widget is collapsed, expand it before showing the confForm
            this.toggleCollapse(true);

        this.confForm = new Ext.form.FormPanel({
            //baseCls: 'feedback_widget'
            autoHeight: true
            //,title: 'Change your settings'
            ,bodyStyle:'padding:10px;background:transparent'
            ,style:'background:#F5F5F5 url(img/portlet_conf_bg.png) repeat-x scroll center top;border-style:none none solid;border-width:0 0 1px; border-color: #DDDDDD'
            ,buttonAlign: 'center'
            ,items: [
            {
                xtype: 'hidden'
                ,name: 'id'
                ,value: this.getId()
            }],

            buttons: [{
                text: 'Change',
                handler: function(){
                    this.confForm.getForm().submit(
                        {
                            url:'users_widgets/changeconf',
                            //waitMsg:'Saving Data...',
                            scope:this,
                            success: function(form,action){
                                this.remove(this.items.items[0], true);
                                this.confForm = null;

                                this.updateWidget(action.result.widget);
                            }
                    }
                    );
                },
                scope: this,
                formBind: true
            }
            ,{
                text: 'Cancel'
                ,handler: function(){
                    this.remove(this.items.items[0], true);
                    this.confForm = null;
                }
                ,scope: this
            }
            ]
        });

        var field;
        for (var i=0, x; x = this.userParams[i++];){
            field = {};
            if(x.type=='string') {
                field.xtype = 'textfield';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
            }
            else if(x.type=='integer') {
                field.xtype = 'textfield';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
            }
            else if(x.type=='boolean') {
                field.xtype = 'checkbox';
                field.boxLabel = x.description ? x.description : x.name;
                field.hideLabel = true;
                if (this.widgetConf[x.name])
                    field.checked = this.widgetConf[x.name];
            }
            else if(x.type=='color') {
                field.xtype = 'colorpickerfield';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
            }
            else if(x.type=='BooleanList') {
                field.xtype = 'checkboxgroup';
                field.fieldLabel = x.description ? x.description : x.name;
                field.anchor = '100%';
                field.columns = 2;
                field.items = new Array();

                var i = 0;
                for (var k in x.values){ //create checkboxes
                    // use key as checkbox label unless a title has been specified
                    var label = k;
                    if ('title' in x.values[k])
                        label = x.values[k].title;

                    var cb = { //checkbox
                        xtype: 'checkbox'
                        ,boxLabel: label
                        ,inputValue: k
                        ,name: x.name+"_"+i
                    };

                    /* If the tab is already present in the widget,
                     * the corrisponding checkbox is checked
                     */
                    if(this.widgetConf[x.name][k])
                        cb.checked = true;

                    field.items.push(cb);
                    i++;
                }

                this.confForm.add({
                    xtype: 'hidden'
                    ,name: x.name //length
                    ,value: i
                });

                /*

                if (this.widgetConf[x.name])
                    field.value = this.widgetConf[x.name];
                */
            }
            field.name = x.name;
            this.confForm.add(field);
        }

        this.insert(0, this.confForm);
        this.doLayout();
    }
    ,setPref:function(pref, value, callbackfun){

        var params = {id: this.getId()};
        params[pref] = value;

        Ext.Ajax.request({
            url : 'users_widgets/changeconf'
            ,method: 'POST'
            ,params: params
            ,callback: callbackfun
       });
    }
});
Ext.reg('portlet', Ext.ux.Portlet);
<|endoftext|>


<commit_before>'use strict';
(function (ns) {
  ns.InvoiceEditor = tp.view.Loader.extend({
    $invoiceList: null,
    events: _.extend({
      'click .export-button': 'exportButton_clickHandler',
      'blur [name=header]': 'header_blurHandler',
      'success form': 'form_successHandler'
    }, tp.view.Loader.prototype.events),
    $context: null,
    render: function () {
      this.getProductList = _.bind(this.getProductList, this);
      tp.view.Loader.prototype.render.call(this);
      tp.component.Manager.loadMediatorClass([], 'tp.component.SmartTable', this.$('#ad_table'), this.getProductList);
      $('.invalid-' + this.model.get('channel')).addClass('invalid');
      $('.invoice-list form').removeClass('processing');
      $('.apply .fa-spinner').remove();
    },
    exportButton_clickHandler: function (event) {
      event.currentTarget.href = this.exportHref;
    },
    tableToExcel: function (template) {
      this.excelTemplate = template;
      var tables = []
        , uri = 'data:application/vnd.ms-excel;base64,'
        , tableList = this.$('.print-table').clone()
        , html = Handlebars.compile(template)
        , acceptAccount = '~' + this.$('#accept-account').text();

      for (var i = 0; i < tableList.length; i++) {
        tableList.eq(i).find('a').replaceWith(function () {
          return this.innerHTML;
        });
        if (i === 0) {
          var table = tableList.eq(i);
          table.find('.do-not-print').remove();
          table.find('.print-title').text(function () {
            return $(this).data('printTitle');
          });
          table.find('#rmb,#reason,#income-total').attr('colspan', function () {
            return $(this).data('colspan');
          });
          table.find('th,td').css('border', '1px solid #ddd');
        }
        if (i === 2) {
          tableList.eq(i).find('#accept-account').text(acceptAccount);
        }
        tables.push(tableList[i].innerHTML);
      }
      var data = {
        worksheet: '对账单',
        tables: tables,
        agreement_number: this.$('#agreement-number').text(),
        invoice_title: this.$('#invoice-title').text()
      };
      this.exportHref = uri + this.base64(html(data));
    },
    base64: function (str) {
      return window.btoa(unescape(encodeURIComponent(str)));
    },
    getProductList: function (components) {
      var products = this.model.get('products')
        , options = this.model.options;
      this.productList = components[0];
      products.push({amount: true});
      this.productList.collection.on('change', this.collection_changeHandler, this);
      this.productList.collection.options = options;
      this.productList.collection.reset(products);
      products.pop();
      $.get(tp.path + 'template/table-to-excel.hbs', _.bind(this.tableToExcel, this), 'html');
    },
    collection_changeHandler: function (data) {
      var model = this.model
        , products = model.get('products')
        , product = _.findWhere(products, {id: data.id});
      _.extend(product, data.toJSON());
      products = model.toJSON().products;
      products.push({amount: true});
      data.collection.reset(products);
      products.pop();
      this.$('#ad_income').text(model.get('ad_income'));
      this.$('#ios_income').text(model.get('ios_income'));
      this.tableToExcel(this.excelTemplate);
      if (model.isNew()) {
        $('.modal').modal('hide');
      }
    },
    remove: function () {
      $('.invalid-' + this.model.get('channel')).removeClass('invalid');
      Backbone.View.prototype.remove.call(this);
      if (this.productList) {
        this.productList.collection.off();
        this.productList = null;
      }
    },
    form_successHandler: function () {
      var channel = this.model.get('channel')
        , models = this.$invoiceList.where({channel: _.isString(channel) ? channel : channel.toString()});
      this.$invoiceList.remove(models);
    },
    header_blurHandler: function (event) {
      this.$('.header').text(event.target.value);
    }
  });
}(Nervenet.createNameSpace('tp.page')));<commit_msg>  修正0不显示的问题<commit_after>'use strict';
(function (ns) {
  ns.InvoiceEditor = tp.view.Loader.extend({
    $invoiceList: null,
    events: _.extend({
      'click .export-button': 'exportButton_clickHandler',
      'blur [name=header]': 'header_blurHandler',
      'success form': 'form_successHandler'
    }, tp.view.Loader.prototype.events),
    $context: null,
    render: function () {
      this.getProductList = _.bind(this.getProductList, this);
      tp.view.Loader.prototype.render.call(this);
      tp.component.Manager.loadMediatorClass([], 'tp.component.SmartTable', this.$('#ad_table'), this.getProductList);
      $('.invalid-' + this.model.get('channel')).addClass('invalid');
      $('.invoice-list form').removeClass('processing');
      $('.apply .fa-spinner').remove();
    },
    exportButton_clickHandler: function (event) {
      event.currentTarget.href = this.exportHref;
    },
    tableToExcel: function (template) {
      this.excelTemplate = template;
      var tables = []
        , uri = 'data:application/vnd.ms-excel;base64,'
        , tableList = this.$('.print-table').clone()
        , html = Handlebars.compile(template)
        , acceptAccount = '~' + this.$('#accept-account').text();

      for (var i = 0; i < tableList.length; i++) {
        tableList.eq(i).find('a').replaceWith(function () {
          return this.innerHTML;
        });
        if (i === 0) {
          var table = tableList.eq(i);
          table.find('.do-not-print').remove();
          table.find('.print-title').text(function () {
            return $(this).data('printTitle');
          });
          table.find('#rmb,#reason,#income-total').attr('colspan', function () {
            return $(this).data('colspan');
          });
          table.find('th,td').attr('style', 'border:1px solid #ddd; mso-number-format:"\@";');
        }
        if (i === 2) {
          tableList.eq(i).find('#accept-account').text(acceptAccount);
        }
        tables.push(tableList[i].innerHTML);
      }
      var data = {
        worksheet: '对账单',
        tables: tables,
        agreement_number: this.$('#agreement-number').text(),
        invoice_title: this.$('#invoice-title').text()
      };
      this.exportHref = uri + this.base64(html(data));
    },
    base64: function (str) {
      return window.btoa(unescape(encodeURIComponent(str)));
    },
    getProductList: function (components) {
      var products = this.model.get('products')
        , options = this.model.options;
      this.productList = components[0];
      products.push({amount: true});
      this.productList.collection.on('change', this.collection_changeHandler, this);
      this.productList.collection.options = options;
      this.productList.collection.reset(products);
      products.pop();
      $.get(tp.path + 'template/table-to-excel.hbs', _.bind(this.tableToExcel, this), 'html');
    },
    collection_changeHandler: function (data) {
      var model = this.model
        , products = model.get('products')
        , product = _.findWhere(products, {id: data.id});
      _.extend(product, data.toJSON());
      products = model.toJSON().products;
      products.push({amount: true});
      data.collection.reset(products);
      products.pop();
      this.$('#ad_income').text(model.get('ad_income'));
      this.$('#ios_income').text(model.get('ios_income'));
      this.tableToExcel(this.excelTemplate);
      if (model.isNew()) {
        $('.modal').modal('hide');
      }
    },
    remove: function () {
      $('.invalid-' + this.model.get('channel')).removeClass('invalid');
      Backbone.View.prototype.remove.call(this);
      if (this.productList) {
        this.productList.collection.off();
        this.productList = null;
      }
    },
    form_successHandler: function () {
      var channel = this.model.get('channel')
        , models = this.$invoiceList.where({channel: _.isString(channel) ? channel : channel.toString()});
      this.$invoiceList.remove(models);
    },
    header_blurHandler: function (event) {
      this.$('.header').text(event.target.value);
    }
  });
}(Nervenet.createNameSpace('tp.page')));<|endoftext|>


<commit_before>(function (Popcorn) {

	'use strict';

	var instances = {},
		resizeTimeout,
		lastResize = 0,

		windowWidth = 0,
		windowHeight = 0,

		RESIZE_THROTTLE = 30;

	function resize(popcorn) {
		var instance = instances[popcorn.id],
			list,
			videoAspect,
			windowAspect,
			options,
			video,

			scale,
			min,
			clipDim,
			videoWidth,
			videoHeight,
			transform = '',

			i;

		if (!instance) {
			return;
		}

		list = instance.events;
		video = popcorn.media;

		videoWidth = video.videoWidth;
		videoHeight = video.videoHeight;
		videoAspect = videoWidth / videoHeight;
		windowAspect = windowWidth / windowHeight;

		//todo: loop, match min/max aspect. for (i = 0; )
		for (i = 0; i < list.length; i++) {
			options = list[i];
			if (windowAspect > videoAspect) {
				//window is not tall enough
				if (!options.minAspect || windowAspect >= options.minAspect) {
					scale = windowWidth / videoWidth;
					min = options.y;

					clipDim = videoWidth / windowAspect;
					if (clipDim < options.height) {
						//window is REALLY not tall enough, so we need to pillarbox
						scale = windowHeight / options.height;
						transform = 'scale(' + scale + ') translate(' +
							(windowWidth - videoWidth * scale) / 2 + 'px, ' +
							-min +
							'px)';
					} else {
						transform = 'scale(' + scale + ') translateY(' +
							-((videoHeight - clipDim) * min / (videoHeight - options.height)) +
							'px)';
					}
					break;
				}
			} else {
				//window is not wide enough
				if (!options.maxAspect || windowAspect <= options.maxAspect) {
					scale = windowHeight / videoHeight;
					min = options.x;

					clipDim = videoHeight * windowAspect;
					if (clipDim < options.width) {
						//window is REALLY not wide enough, so we need to letterbox
						scale = windowWidth / options.width;
						transform = 'scale(' + scale + ') translate(' +
							-min + 'px,' +
							(windowHeight - videoHeight * scale) / 2 +
							'px)';
					} else {
						transform = 'scale(' + scale + ') translateX(' +
							-((videoWidth - clipDim) * min / (videoWidth - options.width)) +
							'px)';
					}
					break;
				}
			}
		}

		video.style.webkitTransform = transform;
		video.style.msTransform = transform;
		video.style.mozTransform = transform;
		video.style.transform = transform;
	}

	function resizeAll() {
		lastResize = Date.now();
		if (windowHeight === window.innerHeight &&
				windowWidth === window.innerWidth) {

			return;
		}

		windowHeight = window.innerHeight;
		windowWidth = window.innerWidth;

		/*
		Hack for mobile safari. Because video element is full size and only
		appears smaller because of CSS transforms, body enlarges to fit the
		full size video. We need to shrink it to correctly position the play
		controls.
		*/
		document.body.style.width = windowWidth + 'px';
		document.body.style.height = windowHeight + 'px';

		Popcorn.instances.forEach(resize);
	}

	function resizeWindow() {
		if (Date.now() - lastResize < RESIZE_THROTTLE) {
			clearTimeout(resizeTimeout);
			resizeTimeout = setTimeout(resizeTimeout, RESIZE_THROTTLE);
		} else {
			resizeAll();
		}
	}

	function sortEvents(a, b) {
		if (a.minAspect !== b.minAspect) {
			return (b.minAspect || 0) - (a.minAspect || 0);
		}

		if (a.maxAspect !== b.maxAspect) {
			return (a.maxAspect || Infinity) - (b.maxAspect || Infinity);
		}

		//prioritize whichever one is shorter
		return (a.end - a.start) - (b.end - b.start);
	}

	function addEvent(popcorn, event) {
		var instance = instances[popcorn.id];
		if (!instance) {
			instance = instances[popcorn.id] = {
				events: [],
				x: -1,
				y: -1
			};
			popcorn.on('loadedmetadata', function () {
				resize(popcorn);
			});
		}

		if (instance.events.indexOf(event) < 0) {
			instance.events.push(event);
			instance.events.sort(sortEvents);
			resize(popcorn);
		}
		return instance;
	}

	function removeEvent(popcorn, event) {
		var instance = instances[popcorn.id],
			list = instance && instance.events,
			index;

		if (list) {
			index = list.indexOf(event);
			if (index >= 0) {
				list.splice(index, 1);
				resize(popcorn);
			}
		}
	}

	/*
	todo: only attach these if there is at least one event,
	detach when the last event is destroyed
	*/
	window.addEventListener('resize', resizeWindow, false);
	window.addEventListener('orientationchange', resizeAll, false);
	resizeAll();

	Popcorn.basePlugin('responsive', function (options, base) {
		var popcorn = base.popcorn;

		base.animate('x', function () {
			resize(popcorn);
		});

		base.animate('y', function () {
			resize(popcorn);
		});

		base.animate('width', function () {
			resize(popcorn);
		});

		base.animate('height', function () {
			resize(popcorn);
		});

		return {
			start: function() {
				addEvent(popcorn, base.options);
			},
			end: function() {
				removeEvent(popcorn, base.options);
			}
		};
	}, {
		about: {
			name: 'Popcorn Responsive Video Plugin',
			version: '0.1',
			author: 'Brian Chirls, @bchirls',
			website: 'http://github.com/brianchirls'
		}
	});
}(window.Popcorn));
<commit_msg>Fix letterbox/pillarbox position (#3)<commit_after>(function (Popcorn) {

	'use strict';

	var instances = {},
		resizeTimeout,
		lastResize = 0,

		windowWidth = 0,
		windowHeight = 0,

		RESIZE_THROTTLE = 30;

	function resize(popcorn) {
		var instance = instances[popcorn.id],
			list,
			videoAspect,
			windowAspect,
			options,
			video,

			scale,
			min,
			clipDim,
			videoWidth,
			videoHeight,
			transform = '',

			i;

		if (!instance) {
			return;
		}

		list = instance.events;
		video = popcorn.media;

		videoWidth = video.videoWidth;
		videoHeight = video.videoHeight;
		videoAspect = videoWidth / videoHeight;
		windowAspect = windowWidth / windowHeight;

		//todo: loop, match min/max aspect. for (i = 0; )
		for (i = 0; i < list.length; i++) {
			options = list[i];
			if (windowAspect > videoAspect) {
				//window is not tall enough
				if (!options.minAspect || windowAspect >= options.minAspect) {
					scale = windowWidth / videoWidth;
					min = options.y;

					clipDim = videoWidth / windowAspect;
					if (clipDim < options.height) {
						//window is REALLY not tall enough, so we need to pillarbox
						scale = windowHeight / options.height;
						transform = 'scale(' + scale + ') translate(' +
							(windowWidth - videoWidth * scale) / 2 / scale + 'px, ' +
							-min +
							'px)';
					} else {
						transform = 'scale(' + scale + ') translateY(' +
							-((videoHeight - clipDim) * min / (videoHeight - options.height)) +
							'px)';
					}
					break;
				}
			} else {
				//window is not wide enough
				if (!options.maxAspect || windowAspect <= options.maxAspect) {
					scale = windowHeight / videoHeight;
					min = options.x;

					clipDim = videoHeight * windowAspect;
					if (clipDim < options.width) {
						//window is REALLY not wide enough, so we need to letterbox
						scale = windowWidth / options.width;
						transform = 'scale(' + scale + ') translate(' +
							-min + 'px,' +
							(windowHeight - videoHeight * scale) / 2 / scale+
							'px)';
					} else {
						transform = 'scale(' + scale + ') translateX(' +
							-((videoWidth - clipDim) * min / (videoWidth - options.width)) +
							'px)';
					}
					break;
				}
			}
		}

		video.style.webkitTransform = transform;
		video.style.msTransform = transform;
		video.style.mozTransform = transform;
		video.style.transform = transform;
	}

	function resizeAll() {
		lastResize = Date.now();
		if (windowHeight === window.innerHeight &&
				windowWidth === window.innerWidth) {

			return;
		}

		windowHeight = window.innerHeight;
		windowWidth = window.innerWidth;

		/*
		Hack for mobile safari. Because video element is full size and only
		appears smaller because of CSS transforms, body enlarges to fit the
		full size video. We need to shrink it to correctly position the play
		controls.
		*/
		document.body.style.width = windowWidth + 'px';
		document.body.style.height = windowHeight + 'px';

		Popcorn.instances.forEach(resize);
	}

	function resizeWindow() {
		if (Date.now() - lastResize < RESIZE_THROTTLE) {
			clearTimeout(resizeTimeout);
			resizeTimeout = setTimeout(resizeTimeout, RESIZE_THROTTLE);
		} else {
			resizeAll();
		}
	}

	function sortEvents(a, b) {
		if (a.minAspect !== b.minAspect) {
			return (b.minAspect || 0) - (a.minAspect || 0);
		}

		if (a.maxAspect !== b.maxAspect) {
			return (a.maxAspect || Infinity) - (b.maxAspect || Infinity);
		}

		//prioritize whichever one is shorter
		return (a.end - a.start) - (b.end - b.start);
	}

	function addEvent(popcorn, event) {
		var instance = instances[popcorn.id];
		if (!instance) {
			instance = instances[popcorn.id] = {
				events: [],
				x: -1,
				y: -1
			};
			popcorn.on('loadedmetadata', function () {
				resize(popcorn);
			});
		}

		if (instance.events.indexOf(event) < 0) {
			instance.events.push(event);
			instance.events.sort(sortEvents);
			resize(popcorn);
		}
		return instance;
	}

	function removeEvent(popcorn, event) {
		var instance = instances[popcorn.id],
			list = instance && instance.events,
			index;

		if (list) {
			index = list.indexOf(event);
			if (index >= 0) {
				list.splice(index, 1);
				resize(popcorn);
			}
		}
	}

	/*
	todo: only attach these if there is at least one event,
	detach when the last event is destroyed
	*/
	window.addEventListener('resize', resizeWindow, false);
	window.addEventListener('orientationchange', resizeAll, false);
	resizeAll();

	Popcorn.basePlugin('responsive', function (options, base) {
		var popcorn = base.popcorn;

		base.animate('x', function () {
			resize(popcorn);
		});

		base.animate('y', function () {
			resize(popcorn);
		});

		base.animate('width', function () {
			resize(popcorn);
		});

		base.animate('height', function () {
			resize(popcorn);
		});

		return {
			start: function() {
				addEvent(popcorn, base.options);
			},
			end: function() {
				removeEvent(popcorn, base.options);
			}
		};
	}, {
		about: {
			name: 'Popcorn Responsive Video Plugin',
			version: '0.1',
			author: 'Brian Chirls, @bchirls',
			website: 'http://github.com/brianchirls'
		}
	});
}(window.Popcorn));
<|endoftext|>