<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {

    /*---------------app object property -------------------------------------------------------------------------------*/
    // Application Constructor
    initialize: function() {
        this.bindEvents();
        app.goingState = "start-app";
                                                                              //  alert("From initialize " + app.goingState);
    },

    /*---------------app object property -------------------------------------------------------------------------------*/
    // Bind Event Listeners
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.

    bindEvents: function() {
        document.addEventListener('deviceready', app.onDeviceReady, false);
                                                                             //    alert ("First Eventlistener");
        document.addEventListener('online', app.onOnline, false);
        document.addEventListener('offline', function(){
                                                                               //  alert("Timeout");
                //  setTimeout(function(){app.onOffline(), 40000});
                app.onOffline();
            }, false
        );

                                                                                //    alert("Next  listeners");

    },

    /*---------------app object property, Main Allication  Handler-------------------------------------------------------------------------------*/

    mainAppHandler: function(calledFrom){
        switch(calledFrom){
            case "onDeviceReady":
            {
                                                                                //      alert("Enter mainAppHandler");
                app.checkConnection();
                                                                                //     alert(app.myNetworkState);
                if (app.goingState == "start-app" && app.myNetworkState == "connected") {
                                                                        //                alert(app.goingState);
                    var pizzamPortalURL = "http://pizzam.de";
                    app.goToPortalSite(pizzamPortalURL);

                }
            }
                break;

        }

    },

    /*---------------app object property -------------------------------------------------------------------------------*/
    // deviceready Event Handler

    onDeviceReady: function() {
        window.open = cordova.InAppBrowser.open;
                                                                //    alert("From onDeviceReady " + app.goingState);

        app.mainAppHandler("onDeviceReady");

    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    stopRotation: function(){
                                                                         //   alert("Enter stopRotation");
        //    app.goingState = "stopped";
        var circularProgressContainer = document.querySelector('#circular-progress');
                                                                         //   alert(circularProgressContainer);
        circularProgressContainer.classList.remove("visible");
        circularProgressContainer.classList.add("not-visible");
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    startRotation: function(){
        var circularProgressContainer = document.querySelector('#circular-progress');
        circularProgressContainer.classList.remove("not-visible");
        circularProgressContainer.classList.add("visible");
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    checkConnection: function(){
        var networkState = navigator.connection.type;
        if (networkState == Connection.NONE){
            app.onOffline();
        }
        else{
            app.onOnline();
        }
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    onOffline: function(){
        setTimeout(closeOnOffline, 1000);
        function closeOnOffline() {
            var netState = navigator.connection.type;
                                                                            //    alert("NetworkState = "+netState);
            if (netState == Connection.NONE){
                app.myNetworkState = "no-internet";
                app.stopRotation();
                                                                           //   alert("No connection!"); //Debug
                app.myChildWindowClose();
             //   alert("Leider gibt es keine Internetverbindung.  Die Bestellung konnte nicht aufgegeben werden. Schließen Sie bitee die App um später zu probieren.");
                var noInternetMsgContainer = document.querySelector('#no-internet-msg-container');
                noInternetMsgContainer.classList.remove("not-visible");
                noInternetMsgContainer.classList.add("visible");
            };
        }
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    onOnline: function(){
        app.myNetworkState = "connected";
        //  app.startRotation();
                                                                                //   alert("Connected!");
        var noInternetMsgContainer = document.querySelector('#no-internet-msg-container');
        noInternetMsgContainer.classList.remove("visible");
        noInternetMsgContainer.classList.add("not-visible");
    //    app.mainAppHandler("onOnline");
    },

   /*---------------app object property -------------------------------------------------------------------------------*/

    myChildWindowOpen: function(shopURL){

        var ref = window.open(shopURL, '_blank', 'location=no,hidden=yes,closebuttoncaption=Done,toolbar=no');
        //   var ref = window.open('http://google.com/', '_blank', 'location=yes,hidden=yes,closebuttoncaption=Done,toolbar=no,hardwareback=no');
        app.myCildWindowState = "loading";
        app.myChildWindow = ref;
                                                          //   alert("This is app.myChildWindow "+app.myChildWindow);
        var loadStopCallback = function (event) {
                                                                                //     alert('stop: ' + event.url);
            //  setTimeout(function(){ app.stopRotation()},40);
            app.stopRotation();
            ref.show();
            //    setTimeout(function(){ ref.close()},15000);
            app.myCildWindowState = "showing";
        }
        ref.addEventListener('loadstop', loadStopCallback);
        ref.addEventListener('exit', function(){ ref = null;});

    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    myChildWindowClose: function(){
                                                                            //   alert("Enter myChildWindowClose");
        if(!((app.myChildWindow == undefined) || (app.myChildWindow == null))){
                                                                             //     alert("In loop");
                                                                            //    alert("This is app.myChildWindow "+app.myChildWindow);
            app.myChildWindow.close();
            app.myCildWindowState = "closed";
            return;
        }
        else{return}
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    goToPortalSite: function(portalURL){
                                                          //   alert("Button Click!");
        app.startRotation();
        app.myChildWindowOpen(portalURL);
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get goingState() {
        return this.goState;
    },

    set goingState(value){
        this.goState = value;
                                                             //   alert("Just state = " + this.state)
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get myNetworkState() {
        return this.networkState;
    },

    set myNetworkState(value){
        this.networkState = value;
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get myChildWindowState() {
        return this.childWindowState;
    },

    set myCildWindowState(value){
        this.childWindowState = value;
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get myChildWindow(){
        return this.childWindow;
    },

    set myChildWindow(value){
        this.childWindow = value;
    },

    /*---------------app object end -------------------------------------------------------------------------------*/
};
<commit_msg>Changes 241016 2152<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {

    /*---------------app object property -------------------------------------------------------------------------------*/
    // Application Constructor
    initialize: function() {
        this.bindEvents();
        app.goingState = "start-app";
                                                                              //  alert("From initialize " + app.goingState);
    },

    /*---------------app object property -------------------------------------------------------------------------------*/
    // Bind Event Listeners
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.

    bindEvents: function() {
        document.addEventListener('deviceready', app.onDeviceReady, false);
                                                                             //    alert ("First Eventlistener");
        document.addEventListener('online', app.onOnline, false);
        document.addEventListener('offline', function(){
                                                                               //  alert("Timeout");
                //  setTimeout(function(){app.onOffline(), 40000});
                app.onOffline();
            }, false
        );

                                                                                //    alert("Next  listeners");

    },

    /*---------------app object property, Main Allication  Handler-------------------------------------------------------------------------------*/

    mainAppHandler: function(calledFrom){
        switch(calledFrom){
            case "onDeviceReady":
            {
                                                                                //      alert("Enter mainAppHandler");
                app.checkConnection();

                if (app.goingState == "start-app" && app.myNetworkState == "connected") {

                    var pizzamPortalURL = "http://pizzam.de";
                    var bodyTag = document.getElementsByTagName('body')[0];
                    bodyTag.addEventListener("click", function(){app.goToPortalSite(pizzamPortalURL);}, false);
                    app.goToPortalSite(pizzamPortalURL);

                }
            }
                break;

        }

    },

    /*---------------app object property -------------------------------------------------------------------------------*/
    // deviceready Event Handler

    onDeviceReady: function() {
        window.open = cordova.InAppBrowser.open;
                                                                //    alert("From onDeviceReady " + app.goingState);

        app.mainAppHandler("onDeviceReady");

    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    stopRotation: function(){
                                                                         //   alert("Enter stopRotation");
        //    app.goingState = "stopped";
        var circularProgressContainer = document.querySelector('#circular-progress');
                                                                         //   alert(circularProgressContainer);
        circularProgressContainer.classList.remove("visible");
        circularProgressContainer.classList.add("not-visible");
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    startRotation: function(){
        var circularProgressContainer = document.querySelector('#circular-progress');
        circularProgressContainer.classList.remove("not-visible");
        circularProgressContainer.classList.add("visible");
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    checkConnection: function(){
        var networkState = navigator.connection.type;
        if (networkState == Connection.NONE){
            app.onOffline();
        }
        else{
            app.onOnline();
        }
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    onOffline: function(){
        setTimeout(closeOnOffline, 1000);
        function closeOnOffline() {
            var netState = navigator.connection.type;
                                                                            //    alert("NetworkState = "+netState);
            if (netState == Connection.NONE){
                app.myNetworkState = "no-internet";
                app.stopRotation();
                                                                           //   alert("No connection!"); //Debug
                app.myChildWindowClose();
             //   alert("Leider gibt es keine Internetverbindung.  Die Bestellung konnte nicht aufgegeben werden. Schließen Sie bitee die App um später zu probieren.");
                var noInternetMsgContainer = document.querySelector('#no-internet-msg-container');
                noInternetMsgContainer.classList.remove("not-visible");
                noInternetMsgContainer.classList.add("visible");
            };
        }
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    onOnline: function(){
        app.myNetworkState = "connected";
        //  app.startRotation();
                                                                                //   alert("Connected!");
        var noInternetMsgContainer = document.querySelector('#no-internet-msg-container');
        noInternetMsgContainer.classList.remove("visible");
        noInternetMsgContainer.classList.add("not-visible");
    //    app.mainAppHandler("onOnline");
    },

   /*---------------app object property -------------------------------------------------------------------------------*/

    myChildWindowOpen: function(shopURL){

        var ref = window.open(shopURL, '_blank', 'location=no,hidden=yes,closebuttoncaption=Done,toolbar=no');
        //   var ref = window.open('http://google.com/', '_blank', 'location=yes,hidden=yes,closebuttoncaption=Done,toolbar=no,hardwareback=no');
        app.myCildWindowState = "loading";
        app.myChildWindow = ref;
                                                          //   alert("This is app.myChildWindow "+app.myChildWindow);
        var loadStopCallback = function (event) {
                                                                                //     alert('stop: ' + event.url);
            //  setTimeout(function(){ app.stopRotation()},40);
            app.stopRotation();
            ref.show();
            //    setTimeout(function(){ ref.close()},15000);
            app.myCildWindowState = "showing";
        }
        ref.addEventListener('loadstop', loadStopCallback);
        ref.addEventListener('exit', function(){ ref = null;});

    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    myChildWindowClose: function(){
                                                                            //   alert("Enter myChildWindowClose");
        if(!((app.myChildWindow == undefined) || (app.myChildWindow == null))){
                                                                             //     alert("In loop");
                                                                            //    alert("This is app.myChildWindow "+app.myChildWindow);
            app.myChildWindow.close();
            app.myCildWindowState = "closed";
            return;
        }
        else{return}
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    goToPortalSite: function(portalURL){
                                                          //   alert("Button Click!");
        app.startRotation();
        app.myChildWindowOpen(portalURL);
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get goingState() {
        return this.goState;
    },

    set goingState(value){
        this.goState = value;
                                                             //   alert("Just state = " + this.state)
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get myNetworkState() {
        return this.networkState;
    },

    set myNetworkState(value){
        this.networkState = value;
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get myChildWindowState() {
        return this.childWindowState;
    },

    set myCildWindowState(value){
        this.childWindowState = value;
    },

    /*---------------app object property -------------------------------------------------------------------------------*/

    get myChildWindow(){
        return this.childWindow;
    },

    set myChildWindow(value){
        this.childWindow = value;
    },

    /*---------------app object end -------------------------------------------------------------------------------*/
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);

		// puship
		var Puship = window.plugins.puship;
		Puship.EnableLog = true;
		Puship.PushipAppId = "ZbFGAsv3SScGkQV"; // I.E.: puship_id = "h1mCVGaP9dtGnwG"

		if (Puship.Common.GetCurrentOs()==Puship.OS.ANDROID){
			var GCMCode = "854409438626"; // This is the senderID provided by Google. I.E.: "28654934133"
			Puship.GCM.Register(GCMCode,
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.IOS){
			Puship.APNS.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.WP){
			Puship.WP.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else {
			Console.log("Not supported platform");
		}

		Puship.Common.OnPushReceived(function(event) {
			console.log("Push received");
			console.log("Message: " + event.notification.Alert);
			console.log("Sound: " + event.notification.Sound);
			console.log("Badge: " + event.notification.Badge);
			console.log("Param1: " + event.notification.Param1);
			alert(event.notification.Alert);
		});
    }
};
// notif event
(function($){
$(document)
// Login
.ready(function()
{
	$('#close').click(function()
	{
		$("#hasil").hide("slow");
		$("#close").hide("slow");
	})
	$('#cek').click(function()
	{
		var rootUrl = 'http://www.sastrahost.com/mutasi-bank/';
		var origin = rootUrl + 'cekApp.php';
		var dataString = 'token=true';
		$.ajax({
		type: "POST",
		url: origin,
		data: dataString,
		cache: false,
		beforeSend: function(){ $("#cek").text('Connecting...');},
		success: function(data){
		if(data != "false"){
			//alert(data);
			$("#cek").text('Cek Lagi');
			$("#hasil").show("slow");
			$("#close").show("slow");
			$("#hasil").html("
"+data+"
");
			//alert('harusnya bisa');
		}else{
			$("#hasil").html("Error: Invalid email and password. ");
			//alert('API nya gagal');
		}
	  },
	  error: function(XMLHttpRequest, textStatus, errorThrown) {
		alert(textStatus);
	  }
	});
	return false;
 });
})
})(jQuery);
<commit_msg>update js 1<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);

		// puship
		var Puship = window.plugins.puship;
		Puship.EnableLog = true;
		Puship.PushipAppId = "ZbFGAsv3SScGkQV"; // I.E.: puship_id = "h1mCVGaP9dtGnwG"

		if (Puship.Common.GetCurrentOs()==Puship.OS.ANDROID){
			var GCMCode = "854409438626"; // This is the senderID provided by Google. I.E.: "28654934133"
			Puship.GCM.Register(GCMCode,
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.IOS){
			Puship.APNS.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else if (Puship.Common.GetCurrentOs()==Puship.OS.WP){
			Puship.WP.Register(
			{
				successCallback: function (pushipresult){
					navigator.notification.alert("device registered with DeviceId:" + pushipresult.DeviceId);
				},
				failCallback: function (pushipresult){
					navigator.notification.alert("error during registration: "+ JSON.stringify(pushipresult));
				}
			});
		} else {
			Console.log("Not supported platform");
		}

		Puship.Common.OnPushReceived(function(event) {
			console.log("Push received");
			console.log("Message: " + event.notification.Alert);
			console.log("Sound: " + event.notification.Sound);
			console.log("Badge: " + event.notification.Badge);
			console.log("Param1: " + event.notification.Param1);
			alert(event.notification.Alert);
		});
    }
};
// notif event
(function($){
$(document)
// Login
.ready(function()
{
	$('#close').click(function()
	{
		$("#hasil").hide("slow");
		$("#close").hide("slow");
	})
	$('#cek').click(function()
	{
		var origin = rootUrl + 'cekApp.php';
		var dataString = 'token=true';
		$.ajax({
		type: "POST",
		url: '',
		data: dataString,
		cache: false,
		beforeSend: function(){ $("#cek").text('Connecting...');},
		success: function(data){
		if(data != "false"){
			//alert(data);
			$("#cek").text('Cek Lagi');
			$("#hasil").show("slow");
			$("#close").show("slow");
			$("#hasil").html("
"+data+"
");
			//alert('harusnya bisa');
		}else{
			$("#hasil").html("Error: Invalid email and password. ");
			//alert('API nya gagal');
		}
	  },
	  error: function(XMLHttpRequest, textStatus, errorThrown) {
		alert(textStatus);
	  }
	});
	return false;
 });
})
})(jQuery);
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        //callNativeFunction();
        document.getElementById('capture-image').addEventListener('click',function(){
              var element = document.getElementsByClassName('red-container');
              html2canvas(element, {
                onrendered: function(canvas) {
                    var dataURL = canvas.toDataURL();
                    document.getElementById("screenshot").src = dataURL;
                }
              });

        },false);

        document.getElementById('email-image').addEventListener('click',function(){
              var imgData = document.getElementById("screenshot").src;
              cordova.plugins.email.isAvailable(
                function (isAvailable) {
                    cordova.plugins.email.open({
                        to:      '',
                        cc:      '',
                        bcc:     [],
                        subject: '',
                        //attachments: imgData,
                        body:    ''
                    });
               });

        },false);

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {

    }
};

app.initialize();
<commit_msg>Updated container name<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        //callNativeFunction();
        document.getElementById('capture-image').addEventListener('click',function(){
              var element = document.getElementsByClassName('source-container');
              html2canvas(element, {
                onrendered: function(canvas) {
                    var dataURL = canvas.toDataURL();
                    document.getElementById("screenshot").src = dataURL;
                }
              });

        },false);

        document.getElementById('email-image').addEventListener('click',function(){
              var imgData = document.getElementById("screenshot").src;
              cordova.plugins.email.isAvailable(
                function (isAvailable) {
                    cordova.plugins.email.open({
                        to:      '',
                        cc:      '',
                        bcc:     [],
                        subject: '',
                        //attachments: imgData,
                        body:    ''
                    });
               });

        },false);

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {

    }
};

app.initialize();
<|endoftext|>


<commit_before>function captureEmail()
{
	//check validity
	var x = document.forms["myform"]["txtEmail"].value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address");
        return false;
    }

	//store email address
	persist();
}

function persist()
{
	localStorage.userName = document.getElementById("txtName").value;
	localStorage.userSurname = document.getElementById('txtSurname').value;
	localStorage.userEmail = document.getElementById('txtEmail').value;
}

function populate()
{
	if (localStorage.userName!=null) {document.getElementById('txtName').value=localStorage.userName} else {document.getElementById('txtName').value=''};
	if (localStorage.userSurname!=null) {document.getElementById('txtSurname').value=localStorage.userSurname} else {document.getElementById('txtSurname').value=''};
	if (localStorage.userEmail!=null) {document.getElementById('txtEmail').value=localStorage.userEmail} else {document.getElementById('txtEmail').value=''};
}

function load()
{
	localStorage.clear();
	if (!localStorage["isSubmit"]) {
		localStorage.isSubmit = 0;   //set to 0 if not initialised
	}

	populate();
	//recalc();
	//section();
}

function storageAvailable(type) {
	try {
		var storage = window[type],
			x = '__storage_test__';
		storage.setItem(x, x);
		storage.removeItem(x);
		return true;
	}
	catch(e) {
		return false;
	}
}

function section() {
	if (localStorage.getItem('isSubmit')==1) {
		div = document.getElementById('submit');
		div.style.display = 'block';

		div = document.getElementById('login');
		div.style.display = 'none';
	} else
	if (localStorage.getItem('isSubmit')==0/* or localStorage.getItem('isSubmit')==null*/) {
		div = document.getElementById('submit');
		div.style.display = 'none';

		div = document.getElementById('login');
		div.style.display = 'block';
	}
}<commit_msg>fixed local storage clear<commit_after>function captureEmail()
{
	//check validity
	var x = document.forms["myform"]["txtEmail"].value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address");
        return false;
    }

	//store email address
	persist();
}

function persist()
{
	localStorage.userName = document.getElementById("txtName").value;
	localStorage.userSurname = document.getElementById('txtSurname').value;
	localStorage.userEmail = document.getElementById('txtEmail').value;
}

function populate()
{
	if (localStorage.userName!=null) {document.getElementById('txtName').value=localStorage.userName} else {document.getElementById('txtName').value=''};
	if (localStorage.userSurname!=null) {document.getElementById('txtSurname').value=localStorage.userSurname} else {document.getElementById('txtSurname').value=''};
	if (localStorage.userEmail!=null) {document.getElementById('txtEmail').value=localStorage.userEmail} else {document.getElementById('txtEmail').value=''};
}

function load()
{
	//localStorage.clear();
	if (!localStorage["isSubmit"]) {
		localStorage.isSubmit = 0;   //set to 0 if not initialised
	}

	populate();
	//recalc();
	//section();
}

function storageAvailable(type) {
	try {
		var storage = window[type],
			x = '__storage_test__';
		storage.setItem(x, x);
		storage.removeItem(x);
		return true;
	}
	catch(e) {
		return false;
	}
}

function section() {
	if (localStorage.getItem('isSubmit')==1) {
		div = document.getElementById('submit');
		div.style.display = 'block';

		div = document.getElementById('login');
		div.style.display = 'none';
	} else
	if (localStorage.getItem('isSubmit')==0/* or localStorage.getItem('isSubmit')==null*/) {
		div = document.getElementById('submit');
		div.style.display = 'none';

		div = document.getElementById('login');
		div.style.display = 'block';
	}
}<|endoftext|>


<commit_before>jsPlumb.ready(function() {

	var defaultConnectorStyle = {
			strokeStyle:"black",
			lineWidth:2,
			outlineColor:"transparent",
			outlineWidth:4
	};

	var dashedConnectorStyle = {
			strokeStyle:"black",
			lineWidth:2,
			outlineColor:"transparent",
			outlineWidth:4,
			dashstyle:"4"
	};

	var connectorHoverStyle = {
			lineWidth:4,
			strokeStyle:"#1e8151",
			outlineWidth:2,
			outlineColor:"white"
	};

	var diamondOverlay = [ [ "Diamond", {
		length : 35,
		width : 18,
		location : 35,
		paintStyle : {
			strokeStyle : "black",
			fillStyle : "white"
		}
	} ] ];

	var triangle = function(color, position){
//		return [ "PlainArrow", {
//			length:25,
//			width: 25,
//			location: position,
//			direction:-1,
//			paintStyle:{
//				strokeStyle:"black",
//				fillStyle:color
//			},
//			id: "generalization-triangle",
//		}];

		return ["Custom", {
        	create:function(component) {
        		return $('<svg class="generalization-triangle" height="26" width="26"><polygon points="1,25 13,1 25,25" stroke="black" stroke-width="1" fill="'+ color +'" /></svg>');
        	},
        	location:position,
        	id: "generalization-triangle",
        }];
	};

	var circle = function(position){
		return ["Custom", {
        	create:function(component) {
        		return $('<svg width="16px" height="16px"><circle cx="8" cy="8" r="8" stroke="black" stroke-width="0" fill="black" /></svg>');
        	},
        	location:position,
        }];
	};

	var square = function(color, position){
		return ["Custom", {
        	create: function(component) {
        		return $('<svg class="cartographic-square" width="16px" height="16px"><rect width="15px" height="15px"  stroke="black" stroke-width="2" fill="'+ color +'" /></svg>');
        	},
        	location: position,
        	id: "cartographic-square",
        }];
	};

	// Plumbing default setup
	app.plumb = jsPlumb.getInstance({
		Anchor : "Continuous",
		ConnectionsDetachable : false,
		Connector : "Flowchart",
		Container : "canvas",
		DragOptions : {cursor : "pointer", zIndex : 2000},
		Endpoint : "Blank",
		HoverPaintStyle: connectorHoverStyle,
	});

	// Define all the connection types
	app.plumb.registerConnectionTypes({
		"association" : {
			paintStyle : defaultConnectorStyle,
			overlays : [[ "Label", { label:"", location:0.5, id:"description-label", cssClass: "description-label" } ],
			            [ "Label", { label:"", location:45, id:"cardinality-labelA", cssClass: "cardinality-label" } ],
			            [ "Label", { label:"", location:-45, id:"cardinality-labelB", cssClass: "cardinality-label" } ]],
			parameters: {
				"minA" : "",
				"maxA" : "",
				"minB" : "",
				"maxB" : "",
			},
		},
		"spatial-association" : {
			paintStyle : dashedConnectorStyle,
			overlays : [[ "Label", { label:"", location:0.5, id:"description-label", cssClass: "description-label" } ],
			            [ "Label", { label:"", location:45, id:"cardinality-labelA", cssClass: "cardinality-label" } ],
			            [ "Label", { label:"", location:-45, id:"cardinality-labelB", cssClass: "cardinality-label" } ]],
			parameters: {
				"minA" : "",
				"maxA" : "",
				"minB" : "",
				"maxB" : "",
			},
		},
		"aggregation" : {
			paintStyle : defaultConnectorStyle,
			overlays : diamondOverlay,
		},
		"spatial-aggregation" : {
			paintStyle : dashedConnectorStyle,
			overlays : diamondOverlay,
		},
		"generalization-disjoint-partial" : {
			anchors : [ "Bottom", "Top" ],
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [ triangle("white", 13) ],
			parameters:{
				"participation":"partial",
				"disjointness":"disjoint",
			},
		},
		"generalization-overlapping-partial" : {
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [ triangle("black", 13) ],
			parameters:{
				"participation":"partial",
				"disjointness":"overlapping",
			},
		},
		"generalization-disjoint-total" : {
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [circle(9), triangle("white", 30) ],
			parameters:{
				"participation":"total",
				"disjointness":"overlapping",
			},
		},
		"generalization-overlapping-total" : {
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [circle(9), triangle("black", 30) ],
			parameters:{
				"participation":"total",
				"disjointness":"overlapping",
			},
		},
		"generalization-leg" : {
			connector: ["Flowchart", {stub: [30, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
		},
		"arc-network" : {
			connector: "Straight",
			paintStyle : dashedConnectorStyle,
			overlays : [[ "Label", { label:"network", location:0.5, id:"description-label", cssClass: "arc-network-label" } ]],
		},
		"arc-network-sibling" : {
			connector: "Straight",
			paintStyle : dashedConnectorStyle,
		},
		"cartographic-generalization-disjoint" : {
			connector: ["Flowchart", {stub: [70, 50], alwaysRespectStubs: true}],
			paintStyle : dashedConnectorStyle,
			overlays : [square("white", 70), [ "Label", { label:"scale", location:0.5, id: "cartographic-label", cssClass: "cartographic-label" }]],
			parameters:{
				"disjointness":"disjoint"
			},
		},
		"cartographic-generalization-overlapping" : {
			connector: ["Flowchart", {stub: [70, 50], alwaysRespectStubs: true}],
			paintStyle : dashedConnectorStyle,
			overlays : [square("black", 70), [ "Label", { label:"scale", location:0.5, id: "cartographic-label", cssClass: "cartographic-label" }]],
			parameters:{
				"disjointness":"overlapping",
			},
		},
		"cartographic-leg" : {
			connector: ["Flowchart", {stub: [0, 50], alwaysRespectStubs: true}],
			paintStyle : dashedConnectorStyle,
		},
	});

	// This events checks which type of connection the user chose in the
	// toolbox, and set the type of the connection to the selected one.
	app.plumb.bind("connectionDrag", function(connection) {

		var tool = app.canvas.get('activeTool');
		if (tool && tool.get('model') == 'omtgRelation') {
			connection.setType(tool.get('name'));
			return;
		}

		// if connection comes from a cartographic square, set type as cartographic-leg
		if(connection.source.classList[0] == "cartographic-square"){
			connection.setType("cartographic-leg");
		}
		else if(connection.source.classList[0] == "generalization-triangle"){
			connection.setType("generalization-leg");
		}
	});

	// This events it is used to set some properties, like specific
	// anchors, to some connections. Here the second line of the
	// arc-network connection is also connected.
	app.plumb.bind("connection", function (info, originalEvent) {

		var type = info.connection.getType()[0];

		switch(type){
		//Adds the second line in network relationships
		case "arc-network":
			var sibling = app.plumb.connect({
				source:info.sourceId,
				target:info.targetId,
				type:"arc-network-sibling",
				parameters:{
					"sibling": info.connection
				}
			});

			info.connection.setParameter("sibling", sibling);
			break;

		case "generalization-disjoint-partial":
		case "generalization-disjoint-total":
		case "generalization-overlapping-partial":
		case "generalization-overlapping-total":
			// Set connection anchors, due to the drag
			// change of anchors, default in jsplumb, the
			// connection must be detached and re-atached
			// with the Bottom and Top anchors
			app.plumb.detach(info.connection);
			var newConn = app.plumb.connect({
				source : info.connection.sourceId,
				target : info.connection.targetId,
				anchors : [ "Bottom", "Top" ],
				type : type,
				fireEvent: false // avoids connect event loop
			});

			// Make generalization overlay a source of more connections
			app.newconn = newConn;
			app.plumb.makeSource(newConn.getOverlay("generalization-triangle").getElement(),{
				anchor: [ 0, 0.5, 0, 1 ],
//				parameters: {"sourceDiagramID" : info.connection.sourceId},
			});
			break;

		// Generalization leg type connection with top target anchor
		case "generalization-leg":
			info.connection.endpoints[1].setAnchor("Top");
			break;

		case "cartographic-generalization-disjoint":
		case "cartographic-generalization-overlapping":
			// Set connection anchors, due to the drag
			// change of anchors, default in jsplumb, the
			// connection must be detached and re-atached
			// with the Bottom and Top anchors
			app.plumb.detach(info.connection);
			var newConn = app.plumb.connect({
				source : info.connection.sourceId,
				target : info.connection.targetId,
				anchors : [ "Bottom", "Top" ],
				type : type,
				fireEvent: false  // avoids this event loop
			});

			// Make the middle square of the connection a source of connections
			app.plumb.makeSource(newConn.getOverlay("cartographic-square").getElement());
			break;

		// Cartographic leg type connection with top target anchor
		case "cartographic-leg":
			info.connection.endpoints[1].setAnchor("Top");
			break;
		}
	});

	// Event that checks for relationship restrictions. Before
	// dropping a connection to its target, the Designer checks if
	// this relationship is valid accordingly to OMT-G restrictions.
	app.plumb.bind("beforeDrop", function(info) {

		// Avoid self loop.
		// TODO: support network self loop
		if(info.sourceId == info.targetId)
			return false;

		// Get type of the connection and type of the diagrams
		var type = info.connection.getType()[0];
		var sourceType = app.canvas.get('diagrams').get(info.sourceId, 'type');
		var targetType = app.canvas.get('diagrams').get(info.targetId, 'type');

		switch(type){
		// Superclass and subclasses must have the same type
		case "generalization-disjoint-partial":
		case "generalization-overlapping-partial":
		case "generalization-disjoint-total":
		case "generalization-overlapping-total":
			return sourceType == targetType;

		// Aggregation must be between conventional classes
		case "aggregation":
			return (sourceType == "conventional") && (targetType == "conventional");

		// Superclass must be conventional and subclasses georeferenced
		// TODO: conceptual legs cannot connect conventional classes
		case "cartographic-generalization-disjoint":
		case "cartographic-generalization-overlapping":
			return (sourceType == "conventional") && (targetType != "conventional");

		case "cartographic-leg":
			return targetType != "conventional";

		// Both classes must be georeferenced
		case "spatial-association":
		case "spatial-aggregation":
			return (sourceType != "conventional") && (targetType != "conventional");

		// If source == target, they must bi bi-line or un-line.
		// if source or target is a node, the other side must be bi-line or un-line.
		case "arc-network":
			return (sourceType == targetType && (sourceType == "bi-line" || sourceType == "un-line")) ||
			(sourceType == "node" && (targetType == "bi-line" || targetType == "un-line")) ||
			(targetType == "node" && (sourceType == "bi-line" || sourceType == "un-line"));
		}

		return true;
	});

	// Event that opens modal for edit the connection or to delete it
	app.plumb.bind("dblclick", function(conn, originalEvent) {

		var param = conn;

		// Fix the bug of clicking an overlay
		if(conn instanceof jsPlumb.Overlays.Label)
			param = conn.component;

		// For arc-network when clicked in the sibling connection
		var type = param.getType()[0];
		if(type == 'arc-network-sibling')
			param = param.getParameter('sibling');

		// Connection types without attributes
		// to be edited or without legs. Only
		// opens a confirmation dialog for
		// deletion.
		if (type == 'aggregation'
			|| type == 'spatial-aggregation'
				|| type == 'generalization-leg'
					|| type == 'cartographic-leg') {

			if (confirm("This connection will be detached. There is no undo. Are you sure?")){
				app.plumb.detach(param);
			}
		}

		// Generalization connections. Need to
		// detach all legs before detaching the
		// main connection
		else if(type == 'generalization-disjoint-partial'
			|| type == 'generalization-overlapping-partial'
				|| type == 'generalization-disjoint-total'
					|| type == 'generalization-overlapping-total'){

			if (confirm("This connection will be detached. There is no undo. Are you sure?")){
				app.plumb.detachAllConnections(param.getOverlays()[0].getElement());
				app.plumb.detach(param);
			}
		}

		// Connections with attributes to be edited. Opens the editor modal
		else {
			new app.omtg.ConnectionEditorView({connection : param});
		}
	});
});
<commit_msg>Cartographic and Generalization bug fixed<commit_after>jsPlumb.ready(function() {

	var defaultConnectorStyle = {
			strokeStyle:"black",
			lineWidth:2,
			outlineColor:"transparent",
			outlineWidth:4
	};

	var dashedConnectorStyle = {
			strokeStyle:"black",
			lineWidth:2,
			outlineColor:"transparent",
			outlineWidth:4,
			dashstyle:"4"
	};

	var connectorHoverStyle = {
			lineWidth:4,
			strokeStyle:"#1e8151",
			outlineWidth:2,
			outlineColor:"white"
	};

	var diamondOverlay = [ [ "Diamond", {
		length : 35,
		width : 18,
		location : 35,
		paintStyle : {
			strokeStyle : "black",
			fillStyle : "white"
		}
	} ] ];

	var triangle = function(color, position){
//		return [ "PlainArrow", {
//			length:25,
//			width: 25,
//			location: position,
//			direction:-1,
//			paintStyle:{
//				strokeStyle:"black",
//				fillStyle:color
//			},
//			id: "generalization-triangle",
//		}];

		return ["Custom", {
        	create:function(component) {
        		return $('<svg class="generalization-triangle" height="26" width="26"><polygon points="1,25 13,1 25,25" stroke="black" stroke-width="1" fill="'+ color +'" /></svg>');
        	},
        	location:position,
        	id: "generalization-triangle",

        }];
	};

	var circle = function(position){
		return ["Custom", {
        	create:function(component) {
        		return $('<svg width="16px" height="16px"><circle cx="8" cy="8" r="8" stroke="black" stroke-width="0" fill="black" /></svg>');
        	},
        	location:position,
        }];
	};

	var square = function(color, position){
		return ["Custom", {
        	create: function(component) {
        		return $('<svg class="cartographic-square" width="16px" height="16px"><rect width="15px" height="15px"  stroke="black" stroke-width="2" fill="'+ color +'" /></svg>');
        	},
        	location: position,
        	id: "cartographic-square",
        }];
	};

	// Plumbing default setup
	app.plumb = jsPlumb.getInstance({
		Anchor : "Continuous",
		ConnectionsDetachable : false,
		Connector : "Flowchart",
		Container : "canvas",
		DragOptions : {cursor : "pointer", zIndex : 2000},
		Endpoint : "Blank",
		HoverPaintStyle: connectorHoverStyle,
	});

	// Define all the connection types
	app.plumb.registerConnectionTypes({
		"association" : {
			paintStyle : defaultConnectorStyle,
			overlays : [[ "Label", { label:"", location:0.5, id:"description-label", cssClass: "description-label" } ],
			            [ "Label", { label:"", location:45, id:"cardinality-labelA", cssClass: "cardinality-label" } ],
			            [ "Label", { label:"", location:-45, id:"cardinality-labelB", cssClass: "cardinality-label" } ]],
			parameters: {
				"minA" : "",
				"maxA" : "",
				"minB" : "",
				"maxB" : "",
			},
		},
		"spatial-association" : {
			paintStyle : dashedConnectorStyle,
			overlays : [[ "Label", { label:"", location:0.5, id:"description-label", cssClass: "description-label" } ],
			            [ "Label", { label:"", location:45, id:"cardinality-labelA", cssClass: "cardinality-label" } ],
			            [ "Label", { label:"", location:-45, id:"cardinality-labelB", cssClass: "cardinality-label" } ]],
			parameters: {
				"minA" : "",
				"maxA" : "",
				"minB" : "",
				"maxB" : "",
			},
		},
		"aggregation" : {
			paintStyle : defaultConnectorStyle,
			overlays : diamondOverlay,
		},
		"spatial-aggregation" : {
			paintStyle : dashedConnectorStyle,
			overlays : diamondOverlay,
		},
		"generalization-disjoint-partial" : {
			anchors : [ "Bottom", "Top" ],
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [ triangle("white", 13) ],
			parameters:{
				"participation":"partial",
				"disjointness":"disjoint",
			},
		},
		"generalization-overlapping-partial" : {
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [ triangle("black", 13) ],
			parameters:{
				"participation":"partial",
				"disjointness":"overlapping",
			},
		},
		"generalization-disjoint-total" : {
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [circle(9), triangle("white", 30) ],
			parameters:{
				"participation":"total",
				"disjointness":"overlapping",
			},
		},
		"generalization-overlapping-total" : {
			connector: ["Flowchart", {stub: [50, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
			overlays : [circle(9), triangle("black", 30) ],
			parameters:{
				"participation":"total",
				"disjointness":"overlapping",
			},
		},
		"generalization-leg" : {
			connector: ["Flowchart", {stub: [30, 30], alwaysRespectStubs: true}],
			paintStyle : defaultConnectorStyle,
		},
		"arc-network" : {
			connector: "Straight",
			paintStyle : dashedConnectorStyle,
			overlays : [[ "Label", { label:"network", location:0.5, id:"description-label", cssClass: "arc-network-label" } ]],
		},
		"arc-network-sibling" : {
			connector: "Straight",
			paintStyle : dashedConnectorStyle,
		},
		"cartographic-generalization-disjoint" : {
			connector: ["Flowchart", {stub: [70, 50], alwaysRespectStubs: true}],
			paintStyle : dashedConnectorStyle,
			overlays : [square("white", 70), [ "Label", { label:"scale", location:0.5, id: "cartographic-label", cssClass: "cartographic-label" }]],
			parameters:{
				"disjointness":"disjoint"
			},
		},
		"cartographic-generalization-overlapping" : {
			connector: ["Flowchart", {stub: [70, 50], alwaysRespectStubs: true}],
			paintStyle : dashedConnectorStyle,
			overlays : [square("black", 70), [ "Label", { label:"scale", location:0.5, id: "cartographic-label", cssClass: "cartographic-label" }]],
			parameters:{
				"disjointness":"overlapping",
			},
		},
		"cartographic-leg" : {
			connector: ["Flowchart", {stub: [0, 50], alwaysRespectStubs: true}],
			paintStyle : dashedConnectorStyle,
		},
	});

	// This events checks which type of connection the user chose in the
	// toolbox, and set the type of the connection to the selected one.
	app.plumb.bind("connectionDrag", function(connection) {

		var tool = app.canvas.get('activeTool');
		if (tool && tool.get('model') == 'omtgRelation') {
			connection.setType(tool.get('name'));
			return;
		}

		// if connection comes from a cartographic square, set type as cartographic-leg
		if(connection.source.classList[0] == "cartographic-square"){
			connection.setType("cartographic-leg");
		}
		else if(connection.source.classList[0] == "generalization-triangle"){
			connection.setType("generalization-leg");
		}
	});

	// This events it is used to set some properties, like specific
	// anchors, to some connections. Here the second line of the
	// arc-network connection is also connected.
	app.plumb.bind("connection", function (info, originalEvent) {

		var type = info.connection.getType()[0];

		switch(type){
		//Adds the second line in network relationships
		case "arc-network":
			var sibling = app.plumb.connect({
				source:info.sourceId,
				target:info.targetId,
				type:"arc-network-sibling",
				parameters:{
					"sibling": info.connection
				}
			});

			info.connection.setParameter("sibling", sibling);
			break;

		case "generalization-disjoint-partial":
		case "generalization-disjoint-total":
		case "generalization-overlapping-partial":
		case "generalization-overlapping-total":
			// Set connection anchors, due to the drag
			// change of anchors, default in jsplumb, the
			// connection must be detached and re-atached
			// with the Bottom and Top anchors
			app.plumb.detach(info.connection);
			var newConn = app.plumb.connect({
				source : info.connection.sourceId,
				target : info.connection.targetId,
				anchors : [ "Bottom", "Top" ],
				type : type,
				fireEvent: false // avoids connect event loop
			});

			// Make generalization overlay a source of more connections
			app.newconn = newConn;
			app.plumb.makeSource(newConn.getOverlay("generalization-triangle").getElement(),{
				anchor: [ 0, 0.5, 0, 1 ],
//				parameters: {"sourceDiagramID" : info.connection.sourceId},
			});
			break;

		// Generalization leg type connection with top target anchor
		case "generalization-leg":
			info.connection.endpoints[1].setAnchor("Top");
			break;

		case "cartographic-generalization-disjoint":
		case "cartographic-generalization-overlapping":
			// Set connection anchors, due to the drag
			// change of anchors, default in jsplumb, the
			// connection must be detached and re-atached
			// with the Bottom and Top anchors
			app.plumb.detach(info.connection);
			var newConn = app.plumb.connect({
				source : info.connection.sourceId,
				target : info.connection.targetId,
				anchors : [ "Bottom", "Top" ],
				type : type,
				fireEvent: false  // avoids this event loop
			});

			// Make the middle square of the connection a source of connections
			app.plumb.makeSource(newConn.getOverlay("cartographic-square").getElement());
			break;

		// Cartographic leg type connection with top target anchor
		case "cartographic-leg":
			info.connection.endpoints[1].setAnchor("Top");
			break;
		}
	});

	// Event that checks for relationship restrictions. Before
	// dropping a connection to its target, the Designer checks if
	// this relationship is valid accordingly to OMT-G restrictions.
	app.plumb.bind("beforeDrop", function(info) {

		// Avoid self loop.
		// TODO: support network self loop
		if(info.sourceId == info.targetId)
			return false;

		// Get type of the connection and type of the diagrams
		var type = info.connection.getType()[0];
		var sourceType = app.canvas.get('diagrams').get(info.sourceId, 'type');
		var targetType = app.canvas.get('diagrams').get(info.targetId, 'type');

		switch(type){
		// Superclass and subclasses must have the same type
		case "generalization-disjoint-partial":
		case "generalization-overlapping-partial":
		case "generalization-disjoint-total":
		case "generalization-overlapping-total":
			return sourceType == targetType;

		// Aggregation must be between conventional classes
		case "aggregation":
			return (sourceType == "conventional") && (targetType == "conventional");

		// Superclass must be conventional and subclasses georeferenced
		// TODO: conceptual legs cannot connect conventional classes
		case "cartographic-generalization-disjoint":
		case "cartographic-generalization-overlapping":
			return (sourceType == "conventional") && (targetType != "conventional");

		case "cartographic-leg":
			return targetType != "conventional";

		// Both classes must be georeferenced
		case "spatial-association":
		case "spatial-aggregation":
			return (sourceType != "conventional") && (targetType != "conventional");

		// If source == target, they must bi bi-line or un-line.
		// if source or target is a node, the other side must be bi-line or un-line.
		case "arc-network":
			return (sourceType == targetType && (sourceType == "bi-line" || sourceType == "un-line")) ||
			(sourceType == "node" && (targetType == "bi-line" || targetType == "un-line")) ||
			(targetType == "node" && (sourceType == "bi-line" || sourceType == "un-line"));
		}

		return true;
	});

	// Event that opens modal for edit the connection or to delete it
	app.plumb.bind("dblclick", function(conn, originalEvent) {

		var param = conn;

		// Fix the bug of clicking an overlay
		if(conn instanceof jsPlumb.Overlays.Label)
			param = conn.component;

		// For arc-network when clicked in the sibling connection
		var type = param.getType()[0];
		if(type == 'arc-network-sibling')
			param = param.getParameter('sibling');

		// Connection types without attributes
		// to be edited or without legs. Only
		// opens a confirmation dialog for
		// deletion.
		if (type == 'aggregation'
			|| type == 'spatial-aggregation'
				|| type == 'generalization-leg'
					|| type == 'cartographic-leg') {

			if (confirm("This connection will be detached. There is no undo. Are you sure?")){
				app.plumb.detach(param);
			}
		}

		// Generalization connections. Need to
		// detach all legs before detaching the
		// main connection
		else if(type == 'generalization-disjoint-partial'
			|| type == 'generalization-overlapping-partial'
				|| type == 'generalization-disjoint-total'
					|| type == 'generalization-overlapping-total'){

			if (confirm("This connection will be detached. There is no undo. Are you sure?")){
				app.plumb.detachAllConnections(param.getOverlays()[0].getElement());
				app.plumb.detach(param);
			}
		}

		// Connections with attributes to be edited. Opens the editor modal
		else {
			new app.omtg.ConnectionEditorView({connection : param});
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

var exec = require('cordova/exec'),
  mixpanel = {
    people: {}
  },
  errors = {
    invalid: function(paramName, value) {
      return 'invalid ' + paramName + ': ' + value;
    },
  };

// MIXPANEL API

mixpanel.alias = mixpanel.createAlias = function(alias, originalId, onSuccess, onFail) {
  if (!alias) onFail(errors.invalid('alias', alias));
  else exec(onSuccess, onFail, 'Mixpanel', 'alias', [alias, originalId]);
};

mixpanel.distinctId = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'distinctId');
}

mixpanel.flush = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'flush', []);
};

mixpanel.identify = function(id, onSuccess, onFail) {
  if (!id) onFail(errors.invalid('id', id));
  else exec(onSuccess, onFail, 'Mixpanel', 'identify', [id]);
};

mixpanel.init = function(token, onSuccess, onFail) {
  if (!token) onFail(errors.invalid('token', token));
  else exec(onSuccess, onFail, 'Mixpanel', 'init', [token]);
};

mixpanel.register = function(superProperties, onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'register', [superProperties]);
};

mixpanel.reset = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'reset', []);
};

mixpanel.track = function(eventName, eventProperties, onSuccess, onFail) {
  if (!eventName) onFail(errors.invalid('event', eventName));
  else exec(onSuccess, onFail, 'Mixpanel', 'track', [eventName, eventProperties]);
};

// PEOPLE API

mixpanel.people.identify = function(distinctId, onSuccess, onFail) {
  if (!distinctId) onFail(errors.invalid('distinctId', distinctId));
  else exec(onSuccess, onFail, 'Mixpanel', 'people_identify', [distinctId]);
};

mixpanel.people.set = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) onFail(errors.invalid('properties', peopleProperties));
  else exec(onSuccess, onFail, 'Mixpanel', 'people_set', [peopleProperties]);
};

mixpanel.people.registerPushToken = function(pushToken, onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'people_registerPushToken', [pushToken]);
};

// Exports

module.exports = mixpanel;
<commit_msg>check more args in js instead in native code<commit_after>'use strict';

var exec = require('cordova/exec'),
  mixpanel = {
    people: {}
  },
  errors = {
    invalid: function(paramName, value) {
      return 'invalid ' + paramName + ': ' + value;
    }
  };

// MIXPANEL API

mixpanel.alias = mixpanel.createAlias = function(alias, originalId, onSuccess, onFail) {
  if (!alias || typeof alias !== 'string') {
    return onFail(errors.invalid('alias', alias));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'alias', [alias, originalId]);
};

mixpanel.distinctId = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'distinctId');
};

mixpanel.flush = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'flush', []);
};

mixpanel.identify = function(id, onSuccess, onFail) {
  if (!id || typeof id !== 'string') {
    return onFail(errors.invalid('id', id));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'identify', [id]);
};

mixpanel.init = function(token, onSuccess, onFail) {
  if (!token || typeof token != 'string') {
    return onFail(errors.invalid('token', token));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'init', [token]);
};

mixpanel.registerSuperProperties = function(superProperties, onSuccess, onFail) {
  if (!superProperties || typeof superProperties !== 'object') {
    return onFail(errors.invalid('superProperties', superProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'registerSuperProperties', [superProperties]);
};

mixpanel.reset = function(onSuccess, onFail) {
  exec(onSuccess, onFail, 'Mixpanel', 'reset', []);
};

mixpanel.track = function(eventName, eventProperties, onSuccess, onFail) {
  if (!eventName || typeof eventName != 'string') {
    return onFail(errors.invalid('event', eventName));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'track', [eventName, eventProperties]);
};

// PEOPLE API

mixpanel.people.identify = function(distinctId, onSuccess, onFail) {
  if (!distinctId) {
    return onFail(errors.invalid('distinctId', distinctId));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_identify', [distinctId]);
};

mixpanel.people.set = function(peopleProperties, onSuccess, onFail) {
  if (!peopleProperties || (typeof peopleProperties === 'object' && Object.keys(peopleProperties).length === 0)) {
    return onFail(errors.invalid('properties', peopleProperties));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_set', [peopleProperties]);
};

mixpanel.people.registerPushToken = function(pushToken, onSuccess, onFail) {
  if (!pushToken || typeof pushToken !== 'string') {
    return onFail(errors.invalid('pushToken', pushToken));
  }

  exec(onSuccess, onFail, 'Mixpanel', 'people_registerPushToken', [pushToken]);
};

// Exports

module.exports = mixpanel;
<|endoftext|>


<commit_before>var resource = require('resource');

var path = require('path'),
    fs = require('fs');

var query = require('./query'),
    layout = require('./layout'),
    render = require('./render');

var View = function (options) {

  var self = this;

  options = options || {};

  self.viewPath = options.path || process.cwd();

  if (options.path) {
    self.viewPath      = options.path;
    self.templatePath  = self.viewPath + '/';
    self.presenterPath = self.viewPath + '/';
  }

  if (options.name) {
    self.name = options.name;
  } else {
    self.name = "";
  }

  if (options.template) {
    self.template = options.template;
    //
    // Remark: If we have been passed in a template as a string, the querySelectorAll context needs to be updated
    //
    self.$ = query(self.template);
  }

  if (options.presenter) {
    self.presenter = options.presenter;
  }

  if (options.parent) {
    self.parent = options.parent;
  }

  if (typeof options === "string") {
    this.load(options);
  }

  return this;
};

//
// Loads a template file or directory by path
//
View.prototype.load = function (viewPath, cb) {
  var self = this;

  //
  // TODO: better currying of args
  //
  if(typeof cb !== 'function' && typeof viewPath === 'function') {
    cb = viewPath;
  }

  if(typeof viewPath === "string") {
    self.viewPath = viewPath;
  }

  self.templatePath  = self.viewPath + '/';
  self.presenterPath = self.viewPath + '/';

  if (typeof cb !== 'function') {
    throw new Error("callback is required");
  }

  return self._loadAsync(cb);
};

View.prototype._loadAsync = function (cb) {

  var self = this,
  viewPath = self.viewPath,
  callbacks = 0;

  var root = self.viewPath;

  fs.readdir(root, function(err, dir) {
    if (err) {
      return cb(err);
    }
    dir.forEach(function(p) {
      fs.stat(root + '/' + p, function(err, stat) {
        if (stat.isDirectory()){
          delegate('dir', p);
        } else {
          delegate('file', p);
        }
      });
    });
   });

  function delegate (type, _path) {
    var ext = self.detect(_path),
        subViewName;

    subViewName = _path;

    if (type === "file") {

      subViewName = _path.replace(ext, '');

      //
      // increase the callback count
      //
      callbacks++;

      // determine if file is template or presenter ( presenters end in .js and are node modules )
      if (ext === ".js") {
        callbacks--;
        // don't do anything
      } else {

        //
        // load the file as the current template
        //
        fs.readFile(root + '/' + _path, function(err, result) {
          if (err) {
            throw err;
          }
          result = result.toString();
          var presenter, template;
          //
          // determine if file is template or presenter
          //
          template = result;

          //
          // get presenter, if it exists
          //
          var presenterPath = root +  '/' + _path.replace(ext, '.js');

          //
          // Determine if presenter file exists first before attempting to require it
          //
          // TODO: replace with async stat
          var exists = false;
          try {
            var stat = fs.statSync(presenterPath);
            exists = true;
          } catch (err) {
            exists = false;
          }

          if (exists) {
            presenterPath = presenterPath.replace('.js', '');
            presenter = require(presenterPath);
          }

          self[subViewName] = new View({
            name: subViewName,
            template: template,
            presenter: presenter,
            parent: self
          });

          callbacks--;
          if(callbacks === 0) {
            cb(null, self);
          }

        });
      }
    }

    if(type === "dir") {
      //
      // create a new subview
      //
      self[subViewName] = new View({
        name: subViewName,
        path: root + '/' + _path,
        parent: self
      });
      //
      // increase callback count
      //
      callbacks ++;
      //
      // load view
      //
      self[subViewName].load(function() {
        //
        // decrease callback count
        //
        callbacks--;
        if(callbacks === 0){
          cb(null, self);
        }
      });
    }
  }
  return;

};

View.prototype.present = function(options, callback) {

  var self = this;

  // if this is not a layout, do perform layout
  if ((self.name !== "layout") &&
    (typeof options.layout === 'undefined' || options.layout)) {
    // load query
    self.$ = query(self.template);
    layout.call(self, self, options, function(err, result) {
      if (err)
        throw err;

      // update template and reload query
      self.$ = query(result);

      // if we have presenter, use it,
      // otherwise fallback to default presenter
      return (self.presenter || render).call(self, options, callback);
    });
  } else {
    // load query
    self.$ = query(self.template);

    // if we have presenter, use it,
    // otherwise fallback to default presenter
    return (self.presenter || render).call(self, options, function(err, result) {
      return callback(err, result);
    });
  }
};

//
// TODO: Detects view type based on current path
//
View.prototype.detect = function (p) {
  return path.extname(p);
};

View.prototype.breadcrumb = function () {
  if (typeof this.parent === "undefined") {
    return this.name;
  }
  return this.parent.breadcrumb() + '/' + this.name;
};

module['exports'] = View;
<commit_msg>[view] [fix] minor edit to properly handle error in view<commit_after>var resource = require('resource');

var path = require('path'),
    fs = require('fs');

var query = require('./query'),
    layout = require('./layout'),
    render = require('./render');

var View = function (options) {

  var self = this;

  options = options || {};

  self.viewPath = options.path || process.cwd();

  if (options.path) {
    self.viewPath      = options.path;
    self.templatePath  = self.viewPath + '/';
    self.presenterPath = self.viewPath + '/';
  }

  if (options.name) {
    self.name = options.name;
  } else {
    self.name = "";
  }

  if (options.template) {
    self.template = options.template;
    //
    // Remark: If we have been passed in a template as a string, the querySelectorAll context needs to be updated
    //
    self.$ = query(self.template);
  }

  if (options.presenter) {
    self.presenter = options.presenter;
  }

  if (options.parent) {
    self.parent = options.parent;
  }

  if (typeof options === "string") {
    this.load(options);
  }

  return this;
};

//
// Loads a template file or directory by path
//
View.prototype.load = function (viewPath, cb) {
  var self = this;

  //
  // TODO: better currying of args
  //
  if(typeof cb !== 'function' && typeof viewPath === 'function') {
    cb = viewPath;
  }

  if(typeof viewPath === "string") {
    self.viewPath = viewPath;
  }

  self.templatePath  = self.viewPath + '/';
  self.presenterPath = self.viewPath + '/';

  if (typeof cb !== 'function') {
    throw new Error("callback is required");
  }

  return self._loadAsync(cb);
};

View.prototype._loadAsync = function (cb) {

  var self = this,
  viewPath = self.viewPath,
  callbacks = 0;

  var root = self.viewPath;

  fs.readdir(root, function(err, dir) {
    if (err) {
      return cb(err);
    }
    dir.forEach(function(p) {
      fs.stat(root + '/' + p, function(err, stat) {
        if (stat.isDirectory()){
          delegate('dir', p);
        } else {
          delegate('file', p);
        }
      });
    });
   });

  function delegate (type, _path) {
    var ext = self.detect(_path),
        subViewName;

    subViewName = _path;

    if (type === "file") {

      subViewName = _path.replace(ext, '');

      //
      // increase the callback count
      //
      callbacks++;

      // determine if file is template or presenter ( presenters end in .js and are node modules )
      if (ext === ".js") {
        callbacks--;
        // don't do anything
      } else {

        //
        // load the file as the current template
        //
        fs.readFile(root + '/' + _path, function(err, result) {
          if (err) {
            throw err;
          }
          result = result.toString();
          var presenter, template;
          //
          // determine if file is template or presenter
          //
          template = result;

          //
          // get presenter, if it exists
          //
          var presenterPath = root +  '/' + _path.replace(ext, '.js');

          //
          // Determine if presenter file exists first before attempting to require it
          //
          // TODO: replace with async stat
          var exists = false;
          try {
            var stat = fs.statSync(presenterPath);
            exists = true;
          } catch (err) {
            exists = false;
          }

          if (exists) {
            presenterPath = presenterPath.replace('.js', '');
            presenter = require(presenterPath);
          }

          self[subViewName] = new View({
            name: subViewName,
            template: template,
            presenter: presenter,
            parent: self
          });

          callbacks--;
          if(callbacks === 0) {
            cb(null, self);
          }

        });
      }
    }

    if(type === "dir") {
      //
      // create a new subview
      //
      self[subViewName] = new View({
        name: subViewName,
        path: root + '/' + _path,
        parent: self
      });
      //
      // increase callback count
      //
      callbacks ++;
      //
      // load view
      //
      self[subViewName].load(function() {
        //
        // decrease callback count
        //
        callbacks--;
        if(callbacks === 0){
          cb(null, self);
        }
      });
    }
  }
  return;

};

View.prototype.present = function(options, callback) {

  var self = this;

  // if this is not a layout, do perform layout
  if ((self.name !== "layout") &&
    (typeof options.layout === 'undefined' || options.layout)) {
    // load query
    self.$ = query(self.template);
    layout.call(self, self, options, function(err, result) {
      if (err) { return callback(err); }

      // update template and reload query
      self.$ = query(result);

      // if we have presenter, use it,
      // otherwise fallback to default presenter
      return (self.presenter || render).call(self, options, callback);
    });
  } else {
    // load query
    self.$ = query(self.template);

    // if we have presenter, use it,
    // otherwise fallback to default presenter
    return (self.presenter || render).call(self, options, function(err, result) {
      return callback(err, result);
    });
  }
};

//
// TODO: Detects view type based on current path
//
View.prototype.detect = function (p) {
  return path.extname(p);
};

View.prototype.breadcrumb = function () {
  if (typeof this.parent === "undefined") {
    return this.name;
  }
  return this.parent.breadcrumb() + '/' + this.name;
};

module['exports'] = View;
<|endoftext|>


<commit_before>
$("#qbt_rp_icon").click(function () {
    if ($("#qbt_rp_icon").hasClass("icon-play")) {
        $.get(WEBDIR+'qbittorrent/command/resumeall');
        notify('Resume', 'all torrents', 'info');
        $('#qbt_rp_icon').removeClass("icon-play").addClass("icon-pause");
        get_torrents();
    } else {
        $.get(WEBDIR + 'qbittorrent/command/pauseall');
        notify('Pause', 'all torrents', 'info');
        $('#qbt_rp_icon').removeClass("icon-pause").addClass("icon-play");
        get_torrets();
    }
});

function get_torrents() {
    $.ajax({
        'url': WEBDIR + 'qbittorrent/fetch',
            'dataType': 'json',
            'success': function (response) {
            $('#torrents-queue').html("");
            $('#error_message').text("");
            var pausestatus = ["error", "pausedUP", "pausedDL", "checkingUP"];
            var numberofloop = 0;
            var times_in = 0;

            $.each(response, function (index, torrent) {
                tr = $('
');
                numberofloop += 1;

                if (jQuery.inArray(torrent.state, pausestatus) !== -1) {
                    times_in += 1;
                }

                var progressBar = $('
');
                progressBar.addClass('bar');
                progressBar.css('width', (torrent.progress * 100) + '%');
                progressBar.text(torrent.size);

                var progress = $('
');
                progress.addClass('progress');
                if (torrent.percentage_done >= 1) {
                    progress.addClass('progress-success');
                }
                progress.append(progressBar);

                // Button group
                buttons = $('
').addClass('btn-group');

                // Action button (pause or resume)
                actionButton = generateTorrentActionButton(torrent);
                buttons.append(actionButton);

                // Remove button
                removeButton = $('').
                addClass('btn btn-mini').
                html('').
                attr('data-hash', torrent.hash).
                attr('data-name', torrent.name).
                attr('title', 'Remove torrent');
                buttons.append(removeButton);

                tr.append(

                $('').addClass('qbt_name').html(torrent.name + '
 ' + torrent.dlspeed + ' ' + torrent.upspeed + ''),
                $('').text(torrent.num_seeds),
                $('').text(torrent.num_leechs),
                $('').addClass('qbt_ratio').text(torrent.ratio),
                $('').addClass('qbit_eta').text(torrent.eta),
                $('').addClass('qbt_state').text(torrent.state),
                $('').addClass('span3 qbit_progress').html(progress),
                $('').addClass('torrent-action').append(buttons));
                $('#torrents-queue').append(tr);
            });
            if (times_in === numberofloop) {
                $("#qbt_rp_icon").removeClass("icon-pause").addClass("icon-play");
            } else {
                $("#qbt_rp_icon").removeClass("icon-play").addClass("icon-pause");
            }
            $('.spinner').hide();

        }
    });
}

function get_speed() {
    $.ajax({
        'url': WEBDIR + 'qbittorrent/get_speed',
            'dataType': 'json',
            'success': function (response) {
            $('#qbittorrent_speed_down').text(response.qbittorrent_speed_down);
            $('#qbittorrent_speed_up').text(response.qbittorrent_speed_up);
            $('#qbittorrent_total_stats').text("Totals: Download: " + response.qbittorrent_total_dl + " Upload: " + response.qbittorrent_total_ul);
            }
        });
}

function generateTorrentActionButton(torrent) {
    button = $('').addClass('btn btn-mini qbt_rp');
    // Resume button if torrent is paused
    var status = torrent.state;
    var icon = cmd = title = "";

    if (status == "pausedUP" || status == "pausedDL" || status == "error" || status == "checkingUP") {
        icon = "icon-play";
        title = "Resume torrent";
        cmd = "resume";
    } else {
        icon = "icon-pause";
        title = "Pause torrent";
        cmd = "pause";
    }

    // Set icon, command and title to button
    button.html('');
    button.attr('title', title);
    button.attr('data-hash', torrent.hash);
    button.attr('data-name', torrent.name);
    button.attr('data-action', cmd);
    return button;
}

// delete torrent
$(document).on('click', '.qbt_removetorrent', function () {
    var action = $(this).attr('data-action');
    var name = $(this).attr('data-name');
    $.get(WEBDIR + 'qbittorrent/command/' + $(this).attr('data-action') + '/' + $(this).attr('data-hash') + '/' + $(this).attr('data-name') + '/', function(result) {
        notify(action, name, 'info');
    });
});

// resume/pause all torrents
$(document).on('click', '.qbt_rp', function () {
    if ($(this).children("i").hasClass("icon-play")) {
        ($(this).children("i").removeClass("icon-play").addClass("icon-pause"));
    } else {
        ($(this).children("i").removeClass("icon-pause").addClass("icon-play"));
    }
    var action = $(this).attr('data-action');
    var name = $(this).attr('data-name')
    $.get(WEBDIR + 'qbittorrent/command/' + $(this).attr('data-action') + '/' + $(this).attr('data-hash') + '/' + $(this).attr('data-name') + '/', function() {
        notify(action + ' torrent', name, 'info');
    });

});

//sets speed up and down
$(document).on('focusout', '.qbt_setspeed', function () {
    if ($(this).val() === undefined || ($(this).val().length === 0)) return;
    if ($(this).attr('data-action') === 'setGlobalDlLimit') {
        var title = 'Set download speed';
    } else {
        var title = 'Set upload speed';
    }
    speed = $(this).val();
    $.get(WEBDIR + 'qbittorrent/set_speedlimit/' + $(this).attr('data-action') + '/' + $(this).val() + '/', function() {
    notify(title, speed + ' KiB/s', 'info');
    });
});

//Fetches global upload and download limit and sets it as a placeholder
function get_global_limit() {
    $.ajax({
        'url': WEBDIR + 'qbittorrent/get_global_limit',
            'dataType': 'json',
            'success': function (response) {
            $('#qbittorrent_set_speeddown').attr("placeholder", response.dl_limit + ' KiB/s');
            $('#qbittorrent_set_speedup').attr("placeholder", response.ul_limit + ' KiB/s');
            }
        });
}

// Loads the moduleinfo
$(document).ready(function () {
    $('.spinner').show();
    get_torrents();
    get_speed();
    get_global_limit();
    setInterval(function () {
        get_torrents();
        get_speed();
        get_global_limit();
    }, 5000);

});

$("#send_torrent_qbt").click(function () {
    var d = {'cmd': 'download',
            'dlurl': $('#qbt_url').val()
        };

    $.get(WEBDIR + 'qbittorrent/command/', d, function(e) {
        //notify()
        $('#qbt_url').val('')

    });
});

<commit_msg>Fix typo<commit_after>
$("#qbt_rp_icon").click(function () {
    if ($("#qbt_rp_icon").hasClass("icon-play")) {
        $.get(WEBDIR+'qbittorrent/command/resumeall');
        notify('Resume', 'all torrents', 'info');
        $('#qbt_rp_icon').removeClass("icon-play").addClass("icon-pause");
        get_torrents();
    } else {
        $.get(WEBDIR + 'qbittorrent/command/pauseall');
        notify('Pause', 'all torrents', 'info');
        $('#qbt_rp_icon').removeClass("icon-pause").addClass("icon-play");
        get_torrents();
    }
});

function get_torrents() {
    $.ajax({
        'url': WEBDIR + 'qbittorrent/fetch',
            'dataType': 'json',
            'success': function (response) {
            $('#torrents-queue').html("");
            $('#error_message').text("");
            var pausestatus = ["error", "pausedUP", "pausedDL", "checkingUP"];
            var numberofloop = 0;
            var times_in = 0;

            $.each(response, function (index, torrent) {
                tr = $('
');
                numberofloop += 1;

                if (jQuery.inArray(torrent.state, pausestatus) !== -1) {
                    times_in += 1;
                }

                var progressBar = $('
');
                progressBar.addClass('bar');
                progressBar.css('width', (torrent.progress * 100) + '%');
                progressBar.text(torrent.size);

                var progress = $('
');
                progress.addClass('progress');
                if (torrent.percentage_done >= 1) {
                    progress.addClass('progress-success');
                }
                progress.append(progressBar);

                // Button group
                buttons = $('
').addClass('btn-group');

                // Action button (pause or resume)
                actionButton = generateTorrentActionButton(torrent);
                buttons.append(actionButton);

                // Remove button
                removeButton = $('').
                addClass('btn btn-mini').
                html('').
                attr('data-hash', torrent.hash).
                attr('data-name', torrent.name).
                attr('title', 'Remove torrent');
                buttons.append(removeButton);

                tr.append(

                $('').addClass('qbt_name').html(torrent.name + '
 ' + torrent.dlspeed + ' ' + torrent.upspeed + ''),
                $('').text(torrent.num_seeds),
                $('').text(torrent.num_leechs),
                $('').addClass('qbt_ratio').text(torrent.ratio),
                $('').addClass('qbit_eta').text(torrent.eta),
                $('').addClass('qbt_state').text(torrent.state),
                $('').addClass('span3 qbit_progress').html(progress),
                $('').addClass('torrent-action').append(buttons));
                $('#torrents-queue').append(tr);
            });
            if (times_in === numberofloop) {
                $("#qbt_rp_icon").removeClass("icon-pause").addClass("icon-play");
            } else {
                $("#qbt_rp_icon").removeClass("icon-play").addClass("icon-pause");
            }
            $('.spinner').hide();

        }
    });
}

function get_speed() {
    $.ajax({
        'url': WEBDIR + 'qbittorrent/get_speed',
            'dataType': 'json',
            'success': function (response) {
            $('#qbittorrent_speed_down').text(response.qbittorrent_speed_down);
            $('#qbittorrent_speed_up').text(response.qbittorrent_speed_up);
            $('#qbittorrent_total_stats').text("Totals: Download: " + response.qbittorrent_total_dl + " Upload: " + response.qbittorrent_total_ul);
            }
        });
}

function generateTorrentActionButton(torrent) {
    button = $('').addClass('btn btn-mini qbt_rp');
    // Resume button if torrent is paused
    var status = torrent.state;
    var icon = cmd = title = "";

    if (status == "pausedUP" || status == "pausedDL" || status == "error" || status == "checkingUP") {
        icon = "icon-play";
        title = "Resume torrent";
        cmd = "resume";
    } else {
        icon = "icon-pause";
        title = "Pause torrent";
        cmd = "pause";
    }

    // Set icon, command and title to button
    button.html('');
    button.attr('title', title);
    button.attr('data-hash', torrent.hash);
    button.attr('data-name', torrent.name);
    button.attr('data-action', cmd);
    return button;
}

// delete torrent
$(document).on('click', '.qbt_removetorrent', function () {
    var action = $(this).attr('data-action');
    var name = $(this).attr('data-name');
    $.get(WEBDIR + 'qbittorrent/command/' + $(this).attr('data-action') + '/' + $(this).attr('data-hash') + '/' + $(this).attr('data-name') + '/', function(result) {
        get_torrents();
        notify(action, name, 'info');
    });
});

// resume/pause all torrents
$(document).on('click', '.qbt_rp', function () {
    if ($(this).children("i").hasClass("icon-play")) {
        ($(this).children("i").removeClass("icon-play").addClass("icon-pause"));
    } else {
        ($(this).children("i").removeClass("icon-pause").addClass("icon-play"));
    }
    var action = $(this).attr('data-action');
    var name = $(this).attr('data-name')
    $.get(WEBDIR + 'qbittorrent/command/' + $(this).attr('data-action') + '/' + $(this).attr('data-hash') + '/' + $(this).attr('data-name') + '/', function() {
        get_torrents();
        notify(action + ' torrent', name, 'info');
    });

});

//sets speed up and down
$(document).on('focusout', '.qbt_setspeed', function () {
    if ($(this).val() === undefined || ($(this).val().length === 0)) return;
    if ($(this).attr('data-action') === 'setGlobalDlLimit') {
        var title = 'Set download speed';
    } else {
        var title = 'Set upload speed';
    }
    speed = $(this).val();
    $.get(WEBDIR + 'qbittorrent/set_speedlimit/' + $(this).attr('data-action') + '/' + $(this).val() + '/', function() {
        get_global_limit();
        get_speed();
        notify(title, speed + ' KiB/s', 'info');
    });
});

//Fetches global upload and download limit and sets it as a placeholder
function get_global_limit() {
    $.ajax({
        'url': WEBDIR + 'qbittorrent/get_global_limit',
            'dataType': 'json',
            'success': function (response) {
            $('#qbittorrent_set_speeddown').attr("placeholder", response.dl_limit + ' KiB/s');
            $('#qbittorrent_set_speedup').attr("placeholder", response.ul_limit + ' KiB/s');
            }
        });
}

// Loads the moduleinfo
$(document).ready(function () {
    $('.spinner').show();
    get_torrents();
    get_speed();
    get_global_limit();
    setInterval(function () {
        get_torrents();
        get_speed();
        get_global_limit();
    }, 4000);

});

$("#send_torrent_qbt").click(function () {
    var d = {'cmd': 'download',
            'dlurl': $('#qbt_url').val()
        };

    $.get(WEBDIR + 'qbittorrent/command/', d, function(e) {
        $('#qbt_url').val('')

    });
});

<|endoftext|>


<commit_before>;(function(define, require){
  'use strict';

  require.config({
    paths: {
      'underscore.string': '/nbextensions/ipbs/lib/underscore.string.min'
    },
    shim: {'underscore.string': {deps: ['underscore']}}
  });

  define(["underscore", "underscore.string"], function(_, _str){
    _.mixin(_str.exports());

    var trait_defaults = {
        prefix: "text-",
        field: "context",
        selection: "$el",
        type: "enum"
      },
      default_options = {
        skipRender: false
      },
      sizes = {
        xs: "extra_small",
        sm: "small",
        md: "medium",
        lg: "large"
      };

    var API = function(__super__, traits, options){
      options = _.defaults(options || {}, default_options);

      traits = _.map(traits, function(trait){
        trait = _.defaults(trait, trait_defaults);
        trait.method = trait.method || trait.field + "Changed";
        return trait;
      });

      var Classy;

      var methods = {
        initialize: function(){
          _.map(traits, function(trait){
            this.model.on(
              "change:" + trait.field,
              _.bind(this[trait.method], this));
            }, this
          );
          return Classy.__super__.initialize.apply(this, arguments);
        },

        render: function(){
          _.map(traits, function(trait){ this[trait.method](); }, this);

          return options.skipRender ?
            this :
            Classy.__super__.render.apply(this, arguments);
        }
      };

      _.map(traits, function(trait){
        methods[trait.method] = function(){
          var ctx = this.model.get(trait.field),
            sel = this[trait.selection],
            prev =  this.model.previous(trait.field);

          if(trait.type === "boolean"){
            ctx = ctx ? trait.value : null;
            prev = prev ? trait.value : null;
          }

          sel.removeClass(trait.prefix + prev);

          if(!_.isNull(ctx)){
            sel.addClass(trait.prefix + ctx);
          }

          return this;
        };
      });

      Classy = __super__.extend(methods);

      return Classy;
    };

    API.makeSized = function(clsPrefixTemplate, fieldTemplate, opts){
      opts = opts || {};

      return _.map(sizes, function(field, cls){
        return _.extend({}, opts, {
          prefix: _.template(clsPrefixTemplate)({name: cls}),
          field: _.template(fieldTemplate)({name: field})
        });
      });
    };

    return API;
  });
}).call(this, this.define, this.require);
<commit_msg>no, really removing udnerscore.string<commit_after>;(function(define, require){
  'use strict';

  define(["underscore"], function(_){
    var trait_defaults = {
        prefix: "text-",
        field: "context",
        selection: "$el",
        type: "enum"
      },
      default_options = {
        skipRender: false
      },
      sizes = {
        xs: "extra_small",
        sm: "small",
        md: "medium",
        lg: "large"
      };

    var API = function(__super__, traits, options){
      options = _.defaults(options || {}, default_options);

      traits = _.map(traits, function(trait){
        trait = _.defaults(trait, trait_defaults);
        trait.method = trait.method || trait.field + "Changed";
        return trait;
      });

      var Classy;

      var methods = {
        initialize: function(){
          _.map(traits, function(trait){
            this.model.on(
              "change:" + trait.field,
              _.bind(this[trait.method], this));
            }, this
          );
          return Classy.__super__.initialize.apply(this, arguments);
        },

        render: function(){
          _.map(traits, function(trait){ this[trait.method](); }, this);

          return options.skipRender ?
            this :
            Classy.__super__.render.apply(this, arguments);
        }
      };

      _.map(traits, function(trait){
        methods[trait.method] = function(){
          var ctx = this.model.get(trait.field),
            sel = this[trait.selection],
            prev =  this.model.previous(trait.field);

          if(trait.type === "boolean"){
            ctx = ctx ? trait.value : null;
            prev = prev ? trait.value : null;
          }

          sel.removeClass(trait.prefix + prev);

          if(!_.isNull(ctx)){
            sel.addClass(trait.prefix + ctx);
          }

          return this;
        };
      });

      Classy = __super__.extend(methods);

      return Classy;
    };

    API.makeSized = function(clsPrefixTemplate, fieldTemplate, opts){
      opts = opts || {};

      return _.map(sizes, function(field, cls){
        return _.extend({}, opts, {
          prefix: _.template(clsPrefixTemplate)({name: cls}),
          field: _.template(fieldTemplate)({name: field})
        });
      });
    };

    return API;
  });
}).call(this, this.define, this.require);
<|endoftext|>