<commit_before>var socket = io.connect('http://127.0.0.1:3000');
performance.now = performance.now || performance.webkitNow; // hack added by SD!

var localstream; //the stream of audio/video coming from this browser
var outgoing; // peer connection for data out
var incoming; // peer connection for data in
var debug = true; // true to log messages
var currentUser = null;

function logout() {
  navigator.id.logout();
}

if(navigator.id) {
  navigator.id.watch({
    onlogin: function() {
      //we don't handle login on this page
    },
    onlogout: function() {
      window.location = "/logout";
    }
  });
}

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

function start() {
  navigator.getUserMedia(
    { audio:true, video:true },
    function onStream(stream) {
      gotLocalStream(stream);
    },
    function failure(error) {
      alert('Error: To call you need to allow video and/or mic');
      trace('Failed to get stream: ' + error);
    }
  );
}

submitcontact.onsubmit = function(e) {
  alert('onsubmit');
  e.preventDefault();
  e.stopPropagation();
  var contactemail = document.getElementById('contactemail');
  contactemail.checkValidity();
  if(contactemail.validity.valid && contactemail.value !== "") {
    socket.emit('addContact', contactemail.value);
  }
};

function call(email) {
  alert('call');
  if(!localstream) {
    navigator.getUserMedia(
      { audio:true, video:true },
      function onStream(stream) {
        gotLocalStream(stream);
        call(email);
      },
      function failure(error) {
        alert('Error: To call you need to allow video and/or mic');
        trace('Failed to get stream: ' + error);
      }
    );
  }
  else {
    // temporary hacks to cope with API change
    if (!!localstream.videoTracks && !localstream.getVideoTracks) {
      localstream.getVideoTracks = function(){
        return this.videoTracks;
      };
    }
    if (!!localstream.audioTracks && !localstream.getAudioTracks) {
      localstream.getAudioTracks = function() {
        return this.audioTracks;
      };
    }

    outgoing = new RTCPeerConnection(null);
    outgoing.addStream(localstream);

    outgoing.onicecandidate = function(event) {
      if (event.candidate) {
        socket.emit('ice_in', email, event.candidate);
      }
    };

    if(debug) trace("Adding Local Stream to peer connection");
    setTimeout(function() {
      outgoing.createOffer(
        function (offer) {
          outgoing.setLocalDescription(new RTCSessionDescription(offer));
          if(debug) trace("Offer from outgoing \n" + offer.sdp);
          socket.emit('offer', email, offer);
        }, null, null);
    }, 1000);
  }
}

function gotRemoteStream(e) {
  if(debug) trace(e.stream);
  incomingvid.src = window.URL.createObjectURL(e.stream);
}

function gotLocalStream(stream) {
  outgoingvid.src = window.URL.createObjectURL(stream); // add preview
  localstream = stream;
}

function sendAnswerFromOffer(offer, email, stream) {
  alert('send answer from offer');

  incoming.setRemoteDescription(new RTCSessionDescription(offer), function() {
    incoming.createAnswer(function(ans) {
      incoming.setLocalDescription(new RTCSessionDescription(ans));
      if(debug) trace("Answer from incoming \n" + ans.sdp);
      outgoing = new RTCPeerConnection(null);
      outgoing.addStream(localstream);
      outgoing.onicecandidate = function(event) {
        if (event.candidate) {
          socket.emit('ice_in', email, event.candidate);
        }
      };
      setTimeout(function() {
        outgoing.createOffer(
          function (counteroffer) {
            outgoing.setLocalDescription(new RTCSessionDescription(counteroffer));
            if(debug) trace("Offer from outgoing \n" + counteroffer.sdp);
            socket.emit('answer', email, ans, counteroffer);
            // socket.emit('sendOfferDescription', JSON.stringify({ email: email, 'desc' : desc }));
          }, null, null);
      }, 1000);
    }, null, null);
  }, function(){
    if(debug) trace('offer FAILED set as remote description');
  });
}

socket.on('offer', function(email, offer) {
  alert('offer');
  if(confirm("Incoming call from " + email + "! Answer?")) {
    //prepare for stream
    incoming = new RTCPeerConnection(null);
    incoming.onicecandidate = function (event) {
      if (event.candidate) {
        socket.emit('ice_out', email, event.candidate);
      }
    };
    incoming.onaddstream = gotRemoteStream;

    if(!localstream) {
      navigator.getUserMedia(
        { audio:true, video:true },
        function onStream(stream) {
          gotLocalStream(stream);
          sendAnswerFromOffer(offer, email, stream);
        },
        function failure(error) {
          alert('Error: To call you need to allow video and/or mic');
          trace('Failed to get stream: ' + error);
        }
      );
    }
    else {
      sendAnswerFromOffer(offer, email, localstream);
    }
  }
  else {
    alert("Call denied");
  }
});

socket.on('allContacts', function(arr) {
  alert('all contacts');
  for(var i =  0; i < arr.length; i++) {
    document.getElementById('emails').innerHTML += "
" + arr[i] + "
";
  }
});

socket.on('contactAdded', function(email) {
  alert('contactAdded');
  document.getElementById('contactlist').innerHTML += "
" + email + "<button style='float:right;' onclick='call(\"" + email + "\");'>Call</button>
";
  document.getElementById('contactemail').value = "";
});

socket.on('answer', function(email, answer, counteroffer) {
  alert('answer');
  trace('Got answer: ' + answer.sdp);
  outgoing.setRemoteDescription(new RTCSessionDescription(answer),
    function() {},
    function() {
      if(debug) trace('answer FAILED set as remote description');
    }
  );

  if(counteroffer) {
    incoming = new RTCPeerConnection(null);

    incoming.onicecandidate = function (event) {
      if (event.candidate) {
        socket.emit('ice_out', email, event.candidate);
      }
    };

    // got remote stream
    incoming.onaddstream = gotRemoteStream;

    incoming.setRemoteDescription(new RTCSessionDescription(counteroffer), function() {
      incoming.createAnswer(function(ans) {
        incoming.setLocalDescription(new RTCSessionDescription(ans));
        if(debug) trace("Answer from incoming \n" + ans.sdp);
        //send back!
        socket.emit('answer', email, ans);
      }, null, null);
    }, function(){
      if(debug) trace('offer FAILED set as remote description');
    });
  }
});

socket.on('ice_in', function(email, cand) {
  alert('ice in');
  incoming.addIceCandidate(new RTCIceCandidate(cand));
  if(debug) trace("Local ICE candidate: \n" + cand.candidate);
});

socket.on('ice_out', function(email, cand) {
  alert('ice out');
  outgoing.addIceCandidate(new RTCIceCandidate(cand));
  if(debug) trace("Remote ICE candidate: \n" + cand.candidate);
});

start();
<commit_msg>Remove alerts<commit_after>var socket = io.connect('http://127.0.0.1:3000');
performance.now = performance.now || performance.webkitNow; // hack added by SD!

var localstream; //the stream of audio/video coming from this browser
var outgoing; // peer connection for data out
var incoming; // peer connection for data in
var debug = true; // true to log messages
var currentUser = null;

function logout() {
  navigator.id.logout();
}

if(navigator.id) {
  navigator.id.watch({
    onlogin: function() {
      //we don't handle login on this page
    },
    onlogout: function() {
      window.location = "/logout";
    }
  });
}

function trace(text) {
  // This function is used for logging.
  if (text[text.length - 1] == '\n') {
    text = text.substring(0, text.length - 1);
  }
  console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}

function start() {
  navigator.getUserMedia(
    { audio:true, video:true },
    function onStream(stream) {
      gotLocalStream(stream);
    },
    function failure(error) {
      alert('Error: To call you need to allow video and/or mic');
      trace('Failed to get stream: ' + error);
    }
  );
}

submitcontact.onsubmit = function(e) {
  e.preventDefault();
  e.stopPropagation();
  var contactemail = document.getElementById('contactemail');
  contactemail.checkValidity();
  if(contactemail.validity.valid && contactemail.value !== "") {
    socket.emit('addContact', contactemail.value);
  }
};

function call(email) {
  if(!localstream) {
    navigator.getUserMedia(
      { audio:true, video:true },
      function onStream(stream) {
        gotLocalStream(stream);
        call(email);
      },
      function failure(error) {
        alert('Error: To call you need to allow video and/or mic');
        trace('Failed to get stream: ' + error);
      }
    );
  }
  else {
    // temporary hacks to cope with API change
    if (!!localstream.videoTracks && !localstream.getVideoTracks) {
      localstream.getVideoTracks = function(){
        return this.videoTracks;
      };
    }
    if (!!localstream.audioTracks && !localstream.getAudioTracks) {
      localstream.getAudioTracks = function() {
        return this.audioTracks;
      };
    }

    outgoing = new RTCPeerConnection(null);
    outgoing.addStream(localstream);

    outgoing.onicecandidate = function(event) {
      if (event.candidate) {
        socket.emit('ice_in', email, event.candidate);
      }
    };

    if(debug) trace("Adding Local Stream to peer connection");
    setTimeout(function() {
      outgoing.createOffer(
        function (offer) {
          outgoing.setLocalDescription(new RTCSessionDescription(offer));
          if(debug) trace("Offer from outgoing \n" + offer.sdp);
          socket.emit('offer', email, offer);
        }, null, null);
    }, 1000);
  }
}

function gotRemoteStream(e) {
  if(debug) trace(e.stream);
  incomingvid.src = window.URL.createObjectURL(e.stream);
}

function gotLocalStream(stream) {
  outgoingvid.src = window.URL.createObjectURL(stream); // add preview
  localstream = stream;
}

function sendAnswerFromOffer(offer, email, stream) {
  incoming.setRemoteDescription(new RTCSessionDescription(offer), function() {
    incoming.createAnswer(function(ans) {
      incoming.setLocalDescription(new RTCSessionDescription(ans));
      if(debug) trace("Answer from incoming \n" + ans.sdp);
      outgoing = new RTCPeerConnection(null);
      outgoing.addStream(localstream);
      outgoing.onicecandidate = function(event) {
        if (event.candidate) {
          socket.emit('ice_in', email, event.candidate);
        }
      };
      setTimeout(function() {
        outgoing.createOffer(
          function (counteroffer) {
            outgoing.setLocalDescription(new RTCSessionDescription(counteroffer));
            if(debug) trace("Offer from outgoing \n" + counteroffer.sdp);
            socket.emit('answer', email, ans, counteroffer);
            // socket.emit('sendOfferDescription', JSON.stringify({ email: email, 'desc' : desc }));
          }, null, null);
      }, 1000);
    }, null, null);
  }, function(){
    if(debug) trace('offer FAILED set as remote description');
  });
}

socket.on('offer', function(email, offer) {
  if(confirm("Incoming call from " + email + "! Answer?")) {
    //prepare for stream
    incoming = new RTCPeerConnection(null);
    incoming.onicecandidate = function (event) {
      if (event.candidate) {
        socket.emit('ice_out', email, event.candidate);
      }
    };
    incoming.onaddstream = gotRemoteStream;

    if(!localstream) {
      navigator.getUserMedia(
        { audio:true, video:true },
        function onStream(stream) {
          gotLocalStream(stream);
          sendAnswerFromOffer(offer, email, stream);
        },
        function failure(error) {
          alert('Error: To call you need to allow video and/or mic');
          trace('Failed to get stream: ' + error);
        }
      );
    }
    else {
      sendAnswerFromOffer(offer, email, localstream);
    }
  }
  else {
    alert("Call denied");
  }
});

socket.on('allContacts', function(arr) {
  for(var i =  0; i < arr.length; i++) {
    document.getElementById('emails').innerHTML += "
" + arr[i] + "
";
  }
});

socket.on('contactAdded', function(email) {
  document.getElementById('contactlist').innerHTML += "
" + email + "<button style='float:right;' onclick='call(\"" + email + "\");'>Call</button>
";
  document.getElementById('contactemail').value = "";
});

socket.on('answer', function(email, answer, counteroffer) {
  trace('Got answer: ' + answer.sdp);
  outgoing.setRemoteDescription(new RTCSessionDescription(answer),
    function() {},
    function() {
      if(debug) trace('answer FAILED set as remote description');
    }
  );

  if(counteroffer) {
    incoming = new RTCPeerConnection(null);

    incoming.onicecandidate = function (event) {
      if (event.candidate) {
        socket.emit('ice_out', email, event.candidate);
      }
    };

    // got remote stream
    incoming.onaddstream = gotRemoteStream;

    incoming.setRemoteDescription(new RTCSessionDescription(counteroffer), function() {
      incoming.createAnswer(function(ans) {
        incoming.setLocalDescription(new RTCSessionDescription(ans));
        if(debug) trace("Answer from incoming \n" + ans.sdp);
        //send back!
        socket.emit('answer', email, ans);
      }, null, null);
    }, function(){
      if(debug) trace('offer FAILED set as remote description');
    });
  }
});

socket.on('ice_in', function(email, cand) {
  incoming.addIceCandidate(new RTCIceCandidate(cand));
  if(debug) trace("Local ICE candidate: \n" + cand.candidate);
});

socket.on('ice_out', function(email, cand) {
  outgoing.addIceCandidate(new RTCIceCandidate(cand));
  if(debug) trace("Remote ICE candidate: \n" + cand.candidate);
});

start();
<|endoftext|>


<commit_before>/* global define, xit, xdescribe, helper */

define(['webdb'], function (WebDB) {
    'use strict';

    describe("websql", function () {

        describe('database 1', function () {

            var DB,
                config = {
                    id: 'db1',
                    type: WebDB.TYPE_WEBSQL,
                    schema: {
                        test: {
                            key: {
                                keyPath: 'id',
                                autoIncrement: true
                            },
                            fields: {
                                name: {
                                    type: 'TEXT',
                                    default: ''
                                }
                            }
                        }
                    }
                },
                item = {
                    name: 'Kevin'
                };

            it('open', function () {

                runs(function () {
                    (new WebDB(config)).open().done(function (db) {
                        DB = db;
                    });
                });

                waitsFor(function () {
                    return !!DB;
                }, 'timeout for open database', 1000);

                runs(function () {
                    expect(DB).toBeDefined();
                });
            });

            it('insert item', function () {
                var record;

                runs(function () {
                    DB.create(item).done(function (r) {
                        record = r;
                    });
                });

                waitsFor(function () {
                    return !!record;
                }, 'timeout for create item', 1000);

                runs(function () {
                    expect(record.name).toEqual(item.name);
                });
            });
        });

        xdescribe('open', function () {

            it('create database 1', function () {
                var DB,
                    config = {
                        id: 'db1',
                        type: WebDB.TYPE_WEBSQL,
                        schema: {
                            test: {
                                key: {
                                    keyPath: 'id',
                                    autoIncrement: true
                                },
                                fields: {
                                    name: {
                                        type: 'TEXT',
                                        default: ''
                                    }
                                }
                            }
                        }
                    };

                runs(function () {
                    (new WebDB(config)).open().done(function (db) {
                        DB = db;
                    });
                });

                waitsFor(function () {
                    return !!DB;
                }, 'timeout for open database', 1000);

                runs(function () {
                    expect(DB).toBeDefined();
                });
            });

            xit('sql string generate 2', function () {
                var DB,
                    config = {
                        id: 'db2',
                        type: WebDB.TYPE_WEBSQL,
                        schema: {
                            test: {
                                key: {
                                    keyPath: 'id',
                                    autoIncrement: true
                                },
                                fields: {
                                    name: {
                                        type: 'TEXT',
                                        default: ''
                                    }
                                }
                            }
                        }
                    };

                runs(function () {
                    (new WebDB(config)).open().done(function (db) {
                        DB = db;
                    });
                });

                waitsFor(function () {
                    return !!DB;
                }, 'timeout for open database', 1000);

                runs(function () {
                    expect(DB).toBeDefined();
                });
            });

            xit('sql string generate 3', function () {
                var key = {
                    keyPath: 'id',
                    autoIncrement: true
                }, fields = {
                    id: {
                        type: 'TEXT',
                        autoIncrement: false
                    },
                    name: {
                        type: 'TEXT'
                    }
                }, str;
                str = helper.fieldStatementGenerator(key, fields);

                expect(str).toEqual('id INTEGER PRIMARY KEY, name TEXT');
            });

            xit('sql string generate 4', function () {
                var key = {
                    keyPath: 'id',
                    autoIncrement: true
                }, fields = {
                    id: {
                        autoIncrement: false
                    },
                    name: {
                        type: 'TEXT'
                    }
                }, str;
                str = helper.fieldStatementGenerator(key, fields);
                expect(str).toEqual('id INTEGER PRIMARY KEY, name TEXT');
            });
        });

        xdescribe('CRUD', function () {
            var DB,
                config = {
                    id: "webdb-test",
                    schema: {
                        test: {
                            key: {
                                keyPath: 'id',
                                autoIncrement: true
                            },
                            fields: {
                                name: {
                                    type: 'TEXT'
                                },
                                age: {
                                    type: 'INTEGER'
                                }
                            }
                        }
                    }
                },
                items = [{
                    name: "Kevin",
                    age: 20
                }, {
                    name: "John",
                    age: 25
                }, {
                    name: "Chen",
                    age: 30
                }];

            beforeEach(function () {
                var _config = config,
                    done = false,
                    webDB;

                _config.type = WebDB.TYPE_WEBSQL;
                webDB = new WebDB(_config);
                runs(function () {
                    webDB.open().done(function (db) {
                        DB = db;
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for open indexedDB', 1000);
            });

            afterEach(function () {
                var done = false;
                if (DB) DB.close();
                runs(function () {
                    // var req = indexedDB.deleteDatabase(config.id);
                    // req.onsuccess = function () {
                    //     done = true;
                    // };
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for delete database', 1000);
            });

            it("create", function () {
                var resultset = [],
                    len, d;

                len = items.length;

                runs(function () {
                    d = DB.create.apply(DB, items);
                    d.done(function (rs) {
                        resultset = rs;
                    });
                });

                waitsFor(function () {
                    return resultset.length === len;
                }, 'timeout for add items', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(len);
                });

            });

            it('get', function () {

                var record, done = false;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d;

                    d = DB.get(1);

                    d.done(function (r) {
                        record = r;
                    });
                });

                waitsFor(function () {
                    return !!record;
                }, 'timeout for get item', 1000);

                runs(function () {
                    expect(record.name).toEqual(items[0].name);
                });
            });

            it('get all', function () {

                var resultset, done = false;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d;

                    d = DB.all();

                    d.done(function (rs) {
                        resultset = rs;
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for get item', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(items.length);
                });
            });

            it('remove', function () {

                var resultset, done = false, removekey = 1, returnkey;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d, d2;

                    d = DB.remove(removekey);

                    d.done(function (k) {
                        returnkey = k;

                        d2 = DB.all();

                        d2.done(function (rs) {
                            resultset = rs;
                        });
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for remove item', 1000);

                runs(function () {
                    expect(returnkey).toEqual(removekey);
                    expect(resultset.length).toEqual(items.length - 1);
                });
            });

            it('clear', function () {

                var resultset, done = false;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d, d2;

                    d = DB.clear();

                    d.done(function () {

                        d2 = DB.all();

                        d2.done(function (rs) {
                            resultset = rs;
                        });
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for get item', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(0);
                });
            });
        });
    });
});
<commit_msg>add specs<commit_after>/* global define, xit, xdescribe, helper */

define(['webdb'], function (WebDB) {
    'use strict';

    describe("websql", function () {

        describe('database 1', function () {

            var DB,
                config = {
                    id: 'db1',
                    type: WebDB.TYPE_WEBSQL,
                    schema: {
                        test: {
                            key: {
                                keyPath: 'id',
                                autoIncrement: true
                            },
                            fields: {
                                name: {
                                    type: 'TEXT',
                                    default: ''
                                }
                            }
                        }
                    }
                },
                item = {
                    name: 'Kevin'
                };

            it('open', function () {

                runs(function () {
                    (new WebDB(config)).open().done(function (db) {
                        DB = db;
                    });
                });

                waitsFor(function () {
                    return !!DB;
                }, 'timeout for open database', 1000);

                runs(function () {
                    expect(DB).toBeDefined();
                });
            });

            it('insert', function () {
                var record;

                runs(function () {
                    DB.create(item).done(function (r) {
                        record = r;
                    });
                });

                waitsFor(function () {
                    return !!record;
                }, 'timeout for create item', 1000);

                runs(function () {
                    expect(record.name).toEqual(item.name);
                });
            });

            it('get', function () {
                var record, key = 1;

                runs(function () {
                    DB.get(key).done(function (r) {
                        record = r;
                    });
                });

                waitsFor(function () {
                    return !!record;
                }, 'timeout for create item', 1000);

                runs(function () {
                    expect(record.name).toEqual(item.name);
                });
            });

            it('all', function () {
                var resultset;

                runs(function () {
                    DB.all().done(function (rs) {
                        resultset = rs;
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for create item', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(1);
                });
            });

            it('remove', function () {
                var resultset, key = 1, removedkey;

                runs(function () {
                    DB.remove(key).done(function (k) {
                        removedkey = k;
                    });
                });

                waitsFor(function () {
                    return !!removedkey;
                }, 'timeout for remove item', 1000);

                runs(function () {
                    DB.all().done(function (rs) {
                        resultset = rs;
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for create item', 1000);

                runs(function () {
                    expect(removedkey).toBe(key);
                    expect(resultset.length).toBe(0);
                });
            });
        });

        xdescribe('open', function () {

            it('create database 1', function () {
                var DB,
                    config = {
                        id: 'db1',
                        type: WebDB.TYPE_WEBSQL,
                        schema: {
                            test: {
                                key: {
                                    keyPath: 'id',
                                    autoIncrement: true
                                },
                                fields: {
                                    name: {
                                        type: 'TEXT',
                                        default: ''
                                    }
                                }
                            }
                        }
                    };

                runs(function () {
                    (new WebDB(config)).open().done(function (db) {
                        DB = db;
                    });
                });

                waitsFor(function () {
                    return !!DB;
                }, 'timeout for open database', 1000);

                runs(function () {
                    expect(DB).toBeDefined();
                });
            });

            xit('sql string generate 2', function () {
                var DB,
                    config = {
                        id: 'db2',
                        type: WebDB.TYPE_WEBSQL,
                        schema: {
                            test: {
                                key: {
                                    keyPath: 'id',
                                    autoIncrement: true
                                },
                                fields: {
                                    name: {
                                        type: 'TEXT',
                                        default: ''
                                    }
                                }
                            }
                        }
                    };

                runs(function () {
                    (new WebDB(config)).open().done(function (db) {
                        DB = db;
                    });
                });

                waitsFor(function () {
                    return !!DB;
                }, 'timeout for open database', 1000);

                runs(function () {
                    expect(DB).toBeDefined();
                });
            });

            xit('sql string generate 3', function () {
                var key = {
                    keyPath: 'id',
                    autoIncrement: true
                }, fields = {
                    id: {
                        type: 'TEXT',
                        autoIncrement: false
                    },
                    name: {
                        type: 'TEXT'
                    }
                }, str;
                str = helper.fieldStatementGenerator(key, fields);

                expect(str).toEqual('id INTEGER PRIMARY KEY, name TEXT');
            });

            xit('sql string generate 4', function () {
                var key = {
                    keyPath: 'id',
                    autoIncrement: true
                }, fields = {
                    id: {
                        autoIncrement: false
                    },
                    name: {
                        type: 'TEXT'
                    }
                }, str;
                str = helper.fieldStatementGenerator(key, fields);
                expect(str).toEqual('id INTEGER PRIMARY KEY, name TEXT');
            });
        });

        xdescribe('CRUD', function () {
            var DB,
                config = {
                    id: "webdb-test",
                    schema: {
                        test: {
                            key: {
                                keyPath: 'id',
                                autoIncrement: true
                            },
                            fields: {
                                name: {
                                    type: 'TEXT'
                                },
                                age: {
                                    type: 'INTEGER'
                                }
                            }
                        }
                    }
                },
                items = [{
                    name: "Kevin",
                    age: 20
                }, {
                    name: "John",
                    age: 25
                }, {
                    name: "Chen",
                    age: 30
                }];

            beforeEach(function () {
                var _config = config,
                    done = false,
                    webDB;

                _config.type = WebDB.TYPE_WEBSQL;
                webDB = new WebDB(_config);
                runs(function () {
                    webDB.open().done(function (db) {
                        DB = db;
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for open indexedDB', 1000);
            });

            afterEach(function () {
                var done = false;
                if (DB) DB.close();
                runs(function () {
                    // var req = indexedDB.deleteDatabase(config.id);
                    // req.onsuccess = function () {
                    //     done = true;
                    // };
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for delete database', 1000);
            });

            it("create", function () {
                var resultset = [],
                    len, d;

                len = items.length;

                runs(function () {
                    d = DB.create.apply(DB, items);
                    d.done(function (rs) {
                        resultset = rs;
                    });
                });

                waitsFor(function () {
                    return resultset.length === len;
                }, 'timeout for add items', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(len);
                });

            });

            it('get', function () {

                var record, done = false;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d;

                    d = DB.get(1);

                    d.done(function (r) {
                        record = r;
                    });
                });

                waitsFor(function () {
                    return !!record;
                }, 'timeout for get item', 1000);

                runs(function () {
                    expect(record.name).toEqual(items[0].name);
                });
            });

            it('get all', function () {

                var resultset, done = false;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d;

                    d = DB.all();

                    d.done(function (rs) {
                        resultset = rs;
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for get item', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(items.length);
                });
            });

            it('remove', function () {

                var resultset, done = false, removekey = 1, returnkey;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d, d2;

                    d = DB.remove(removekey);

                    d.done(function (k) {
                        returnkey = k;

                        d2 = DB.all();

                        d2.done(function (rs) {
                            resultset = rs;
                        });
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for remove item', 1000);

                runs(function () {
                    expect(returnkey).toEqual(removekey);
                    expect(resultset.length).toEqual(items.length - 1);
                });
            });

            it('clear', function () {

                var resultset, done = false;

                runs(function () {
                    var d;

                    d = DB.create.apply(DB, items);
                    d.done(function () {
                        done = true;
                    });
                });

                waitsFor(function () {
                    return done;
                }, 'timeout for create items', 1000);

                runs(function () {
                    var d, d2;

                    d = DB.clear();

                    d.done(function () {

                        d2 = DB.all();

                        d2.done(function (rs) {
                            resultset = rs;
                        });
                    });
                });

                waitsFor(function () {
                    return !!resultset;
                }, 'timeout for get item', 1000);

                runs(function () {
                    expect(resultset.length).toEqual(0);
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>// requirejs.config({
//       paths: {
//         'jquery': 'lib/jquery-1.8.3.min',
//         'bootstrap': 'lib/bootstrap.min',
//         'validate': 'vendor/jquery.validate',
//         'gmap' : 'vendor/gmap3.min',
//         'upload' : 'vendor/AjaxUpload.2.0.min'
//       }
//     });

//require(['jquery','upload','bootstrap', 'validate','gmap'], function ($) {
//funciones de usuarios
$(document).ready(function(){

var limpiar_modal =function(){
$('.control-group').removeClass('success');
  $('.control-group').removeClass('error');
  $('label').remove(":contains('OK!')");
  $('.error').remove();
};
$('#restaurante').validate({
      rules: {
        va_nombre: {
            required: true,
            minlength : 8
        },
        va_razon_social: {
              required: true ,
              minlength : 10
        },
        va_web :{
                   url:true},
        va_ruc:{
                required : true,
                rucReal:true
            },
        va_imagen : { required : true},
        va_modalidad :{
          required: true,
          minlength: 1
        },
        Ta_tipo_comida_in_id:{
                required : true
              }
      },
      messages:{
            va_nombre: {
                required:"Por favor ingresar el nombre del restaurante",
                minlength : "Minimo 8 caracteres"
            },
            va_razon_social:{
                required:"Por favor ingresar la razon social",
                minlength : "Minimo 10 caractertes"
            },
            va_web:{
                url:"Por favor ingresa una Url valida"
            },
            va_ruc: {
                required : "Por favor ingrese un Ruc",
                rucReal:" Ingresa un Ruc valido "
            },
            va_modalidad : {
               required: "Por favor seleccionar una modalida",
               minlength : "Seleccionar al menos 1"
            },
            va_imagen : {
              required : "Por favor ingresar una imagen"
            },
            Ta_tipo_comida_in_id :{
              required : "Por favor ingresar un tipo de plato"
            }
        },
      highlight: function(element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
      },
      success: function(element) {
        element
        .text('OK!').addClass('valid')
        .closest('.control-group').removeClass('error').addClass('success');
      }
    });
var validar=function(elemento){
$(elemento).validate({
	    rules: {
	      va_nombre: {
	          required: true
	      },
	      va_apellidos: {
	   	        required: true
	      },
	      Ta_rol_in_id :{
	      required:true},
	      va_email: {
	        required: true,
	        email: true
	      },
	      va_contrasenia:{
                required : true,
                minlength:6
            },
        va_contrasenia2:{
                required : true,
                equalTo: "#va_contrasenia",
                minlength:6
            }
	    },
	    messages:{
            va_nombre: {
                required:"Por favor ingresar el nombre"
            },
            va_apellidos:{
                required:"Por favor ingresar el apellido"
            },
            va_email:{
                required:"Por favor ingresa un Email Valido"
            },
            va_contrasenia: {
                required : "Ingrese la clave",
                minlength:"Ingresa un password de 6 caracteres a mas"
            },
            va_contrasenia2: {
                required : "Repita la clave",
                minlength:"Ingresa un password de 6 caracteres a mas",
                equalTo : "Ingrese el mismo valor de Clave"
            },
            Ta_rol_in_id :{
            	required : "Por favor ingresar un rol"
            }
        },
			highlight: function(element) {
				$(element).closest('.control-group').removeClass('success').addClass('error');
			},
			success: function(element) {
				element
				.text('OK!').addClass('valid')
				.closest('.control-group').removeClass('error').addClass('success');
			}
	  });

}
validar('#usuario');

//  //llenado de combo
//  $.getJSON('/usuario/index/jsonestado',function(data){
// 		$.each(data,function(i,val){
// 			$('#Ta_rol_in_id').append("<option value=" + val.in_id + " >" + val.va_nombre_rol + " </option>" );
// 		})
// });
//  $.getJSON('/restaurante/index/jsoncomida',function(data){
//     $.each(data,function(i,val){
//       $('#Ta_tipo_comida_in_id').append("<option value=" + val.in_id + " >" + val.va_nombre_tipo + " </option>" );
//     })
// });

// $.getJSON('/restaurante/index/medio',function(data){
//     $.each(data,function(i,val){
//           $('#cmodal').append("<input type='checkbox' name='va_modalidad[]' id="+ val.in_id+" value="+ val.in_id+"> " + val.va_nombre + "
" );
//           $('#comodal').append("<input type='checkbox' name='va_modalidad[]' id="+ val.in_id+" value="+ val.in_id+"> " + val.va_nombre + "
" );
//     });
// });
// $.getJSON('/local/index/jsonservicios',function(data){
//     $.each(data,function(i,val){
//           $('#servicio_local').append("<input type='checkbox' name='servicio_local[]' id="+ val.in_id+" value="+val.in_id +"> " + val.va_nombre + "
" );
//     });
// });

  $('#direccion_loc').keyup(function () {
     var value = $(this).val();
    $('#address').val("");
     var d = $("#distrito option:selected").text();
     var p = $("#provincia option:selected").text();
     var pa = $("#pais option:selected").text();
     $("#address").val(value + ", " + d  + " , " + p + " , " + pa);
   }).keyup();

//llenado de combos
$("#pais").change(function(evento){
   var pais=parseInt($(this).val());
$.getJSON('/local/index/jsondepartamento',function(data){
    if(pais==1){
       $.each(data,function(i,val){
          $('#departamento').append( "<option value=" + val.in_iddep + " >" + val.ch_departamento + " </option>");
    });
    }
});
});

  $("#departamento").change(function(evento){
   var dep=parseInt($(this).val());
   var url="/local/index/jsonprovincia?iddepa=" + dep;
 console.log(dep);
      $.getJSON(url,function(data){
         $("#provincia").empty();
          $("#distrito").empty();
          $("#provincia").append("<option value=''>Seleccione</option>");
            $.each(data,function(i,val){
                $('#provincia').append( "<option value=" + val.in_idprov + " >" + val.ch_provincia + " </option>");
                      });
     });
});

  $("#provincia").change(function(evento){

   var dep=parseInt($('#departamento').val());
    var pro=parseInt($(this).val());
   var url="/local/index/jsondistrito?iddepa=" + dep + "&iddpro=" + pro
  console.log(pro);
      $.getJSON(url,function(data){
         $("#distrito").empty();
        $("#distrito").append("<option value=''>Seleccione</option>");
    $.each(data,function(i,val){

                $('#distrito').append( "<option value=" + val.in_iddis + " >" + val.ch_distrito + " </option>");

          });
     });
});

//mapa

var map;

function load_map() {
    var myLatlng = new google.maps.LatLng(-12.055345316962327, -77.04518530000001);
    var myOptions = {
        zoom: 4,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map($("#map_canvas").get(0), myOptions);
}

$('#search').on('click', function() {
  load_map();
  $('#map_canvas').css("display","block");
    var address = $('#address').val();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address}, geocodeResult);
});
var infoWindow = null;

function openInfoWindow(marker) {
    var markerLatLng = marker.getPosition();
   $('#de_latitud').html("");
    $('#de_longitud').html("");
    var l= markerLatLng.lat();
    var lo = markerLatLng.lng();
   $('#de_latitud').val(l);
    $('#de_longitud').val(lo);

}

function geocodeResult(results, status) {
    // Verificamos el estatus
    if (status == 'OK') {
        // Si hay resultados encontrados, centramos y repintamos el mapa
        // esto para eliminar cualquier pin antes puesto
        var mapOptions = {
            center: results[0].geometry.location,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map($("#map_canvas").get(0), mapOptions);
        // fitBounds acercará el mapa con el zoom adecuado de acuerdo a lo buscado
        map.fitBounds(results[0].geometry.viewport);
        $('#de_latitud').val(results[0].geometry.location.lat());
      $('#de_longitud').val(results[0].geometry.location.lng());
        // Dibujamos un marcador con la ubicación del primer resultado obtenido
        var markerOptions = { position: results[0].geometry.location ,draggable: true}
        var marker = new google.maps.Marker(markerOptions);
        google.maps.event.addListener(marker, 'dragend', function(){ openInfoWindow(marker); });
        marker.setMap(map);
    } else {
        // En caso de no haber resultados o que haya ocurrido un error
        // lanzamos un mensaje con el error
        alert("Geocoding no tuvo éxito debido a: " + status);
    }
}

  //carga imagen
// $('#para').click(function(){
//       var btn_firma = $('#addImage'), interval;
//       new AjaxUpload('#addImage', {
//         action: 'includes/uploadFile.php',onSubmit : function(file , ext){
//           if (! (ext && /^(jpg|png)$/.test(ext))){
//             alert('Sólo se permiten Imagenes .jpg o .png');
//             return false;
//           } else {
//             $('#loaderAjax').show();
//             btn_firma.text('Espere por favor');
//             this.disable();
//           }
//         },
//         onComplete: function(file, response){

//           btn_firma.text('Cambiar Imagen');
//           respuesta = $.parseJSON(response);
//           if(respuesta.respuesta == 'done'){
//             $('#fotografia').removeAttr('scr');
//             $('#fotografia').attr('src','img/' + respuesta.fileName);
//             $('#loaderAjax').show();
//           }
//           else{
//             alert(respuesta.mensaje);
//           }

//           $('#loaderAjax').hide();
//           this.enable();
//         }
//     });
// });

//

$(".eli").on("click",function(){
	var id = $(this).attr('data-id');
	var nom =$(this).attr('name');
  $('#eli-user').modal('show');
  console.log(id);
	$('#verusuario').attr({'data-id':id});
	$('#verusuario').html("Estas seguro de eliminar al usuario " + nom + " ?");
});

$('.check_rest').mousedown(function() {
    var id = $(this).attr('id');
    console.log(id);
    console.log()
    var est;
        if (!$(this).is(':checked')) {
          if (confirm("Desea Activar al Restaurante ?") ){
            var est="activo";
            var request = $.ajax({
            url: "restaurante/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
            $(this).prop("checked", "checked");
            $("#" + id).addClass("success");
            $("#la" + id).removeClass().addClass("label label-success");
            $("#la" + id).html("");
            $("#la" + id).html("activo");
                 };
        }else{
          var est="desactivo";
            var request = $.ajax({
            url: "restaurante/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
          $("#" + id).removeClass("success");
          $("#la" + id).removeClass().addClass("label label-important");
          $("#la" + id).html("");
            $("#la" + id).html("desactivo");
              }
    });

  $('.check').mousedown(function() {
  	var id = $(this).attr('id');
    console.log(id);
    console.log()
    var est;
        if (!$(this).is(':checked')) {
        	if (confirm("Desea Activar al usuario ?") ){
            var est="activo";
            var request = $.ajax({
            url: "/usuario/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
            $(this).prop("checked", "checked");
            $("#" + id).addClass("success");
            $("#la" + id).removeClass().addClass("label label-success");
            $("#la" + id).html("");
            $("#la" + id).html("activo");
                 };
        }else{
          var est="desactivo";
            var request = $.ajax({
            url: "/usuario/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
        	$("#" + id).removeClass("success");
        	$("#la" + id).removeClass().addClass("label label-important");
          $("#la" + id).html("");
            $("#la" + id).html("desactivo");
              }
    });

  $("#delete").on("click",function(){
	var user=$("#verusuario").attr("data-id");
	$("#" + user).closest('tr').remove();
	$('#eli-user').modal('hide');
	console.log(user);
  var request = $.ajax({
  url: "/usuario/index/eliminarusu?id="+user,
  type: "POST",
  data: {id: user}
  });
});
});
<commit_msg>front<commit_after>// requirejs.config({
//       paths: {
//         'jquery': 'lib/jquery-1.8.3.min',
//         'bootstrap': 'lib/bootstrap.min',
//         'validate': 'vendor/jquery.validate',
//         'gmap' : 'vendor/gmap3.min',
//         'upload' : 'vendor/AjaxUpload.2.0.min'
//       }
//     });

//require(['jquery','upload','bootstrap', 'validate','gmap'], function ($) {
//funciones de usuarios
$(document).ready(function(){

var limpiar_modal =function(){
$('.control-group').removeClass('success');
  $('.control-group').removeClass('error');
  $('label').remove(":contains('OK!')");
  $('.error').remove();
};
$('#restaurante').validate({
      rules: {
        va_nombre: {
            required: true,
            minlength : 8
        },
        va_razon_social: {
              required: true ,
              minlength : 10
        },
        va_web :{
                   url:true},
        va_ruc:{
                required : true,
                rucReal:true
            },
        va_imagen : { required : true},
        "va_modalidad[]" :{
          required: true,
          minlength: 1
        },
        Ta_tipo_comida_in_id:{
                required : true
              }
      },
      messages:{
            va_nombre: {
                required:"Por favor ingresar el nombre del restaurante",
                minlength : "Minimo 8 caracteres"
            },
            va_razon_social:{
                required:"Por favor ingresar la razon social",
                minlength : "Minimo 10 caractertes"
            },
            va_web:{
                url:"Por favor ingresa una Url valida"
            },
            va_ruc: {
                required : "Por favor ingrese un Ruc",
                rucReal:" Ingresa un Ruc valido "
            },
            "va_modalidad[]" : {
               required: "Por favor seleccionar una modalida",
               minlength : "Seleccionar al menos 1"
            },
            va_imagen : {
              required : "Por favor ingresar una imagen"
            },
            Ta_tipo_comida_in_id :{
              required : "Por favor ingresar un tipo de plato"
            }
        },
      highlight: function(element) {
        $(element).closest('.control-group').removeClass('success').addClass('error');
      },
      success: function(element) {
        element
        .text('OK!').addClass('valid')
        .closest('.control-group').removeClass('error').addClass('success');
      }
    });
var validar=function(elemento){
$(elemento).validate({
	    rules: {
	      va_nombre: {
	          required: true
	      },
	      va_apellidos: {
	   	        required: true
	      },
	      Ta_rol_in_id :{
	      required:true},
	      va_email: {
	        required: true,
	        email: true
	      },
	      va_contrasenia:{
                required : true,
                minlength:6
            },
        va_contrasenia2:{
                required : true,
                equalTo: "#va_contrasenia",
                minlength:6
            }
	    },
	    messages:{
            va_nombre: {
                required:"Por favor ingresar el nombre"
            },
            va_apellidos:{
                required:"Por favor ingresar el apellido"
            },
            va_email:{
                required:"Por favor ingresa un Email Valido"
            },
            va_contrasenia: {
                required : "Ingrese la clave",
                minlength:"Ingresa un password de 6 caracteres a mas"
            },
            va_contrasenia2: {
                required : "Repita la clave",
                minlength:"Ingresa un password de 6 caracteres a mas",
                equalTo : "Ingrese el mismo valor de Clave"
            },
            Ta_rol_in_id :{
            	required : "Por favor ingresar un rol"
            }
        },
			highlight: function(element) {
				$(element).closest('.control-group').removeClass('success').addClass('error');
			},
			success: function(element) {
				element
				.text('OK!').addClass('valid')
				.closest('.control-group').removeClass('error').addClass('success');
			}
	  });

}
validar('#usuario');

//  //llenado de combo
//  $.getJSON('/usuario/index/jsonestado',function(data){
// 		$.each(data,function(i,val){
// 			$('#Ta_rol_in_id').append("<option value=" + val.in_id + " >" + val.va_nombre_rol + " </option>" );
// 		})
// });
//  $.getJSON('/restaurante/index/jsoncomida',function(data){
//     $.each(data,function(i,val){
//       $('#Ta_tipo_comida_in_id').append("<option value=" + val.in_id + " >" + val.va_nombre_tipo + " </option>" );
//     })
// });

// $.getJSON('/restaurante/index/medio',function(data){
//     $.each(data,function(i,val){
//           $('#cmodal').append("<input type='checkbox' name='va_modalidad[]' id="+ val.in_id+" value="+ val.in_id+"> " + val.va_nombre + "
" );
//           $('#comodal').append("<input type='checkbox' name='va_modalidad[]' id="+ val.in_id+" value="+ val.in_id+"> " + val.va_nombre + "
" );
//     });
// });
// $.getJSON('/local/index/jsonservicios',function(data){
//     $.each(data,function(i,val){
//           $('#servicio_local').append("<input type='checkbox' name='servicio_local[]' id="+ val.in_id+" value="+val.in_id +"> " + val.va_nombre + "
" );
//     });
// });

  $('#direccion_loc').keyup(function () {
     var value = $(this).val();
    $('#address').val("");
     var d = $("#distrito option:selected").text();
     var p = $("#provincia option:selected").text();
     var pa = $("#pais option:selected").text();
     $("#address").val(value + ", " + d  + " , " + p + " , " + pa);
   }).keyup();

//llenado de combos
$("#pais").change(function(evento){
   var pais=parseInt($(this).val());
$.getJSON('/local/index/jsondepartamento',function(data){
    if(pais==1){
       $.each(data,function(i,val){
          $('#departamento').append( "<option value=" + val.in_iddep + " >" + val.ch_departamento + " </option>");
    });
    }
});
});

  $("#departamento").change(function(evento){
   var dep=parseInt($(this).val());
   var url="/local/index/jsonprovincia?iddepa=" + dep;
 console.log(dep);
      $.getJSON(url,function(data){
         $("#provincia").empty();
          $("#distrito").empty();
          $("#provincia").append("<option value=''>Seleccione</option>");
            $.each(data,function(i,val){
                $('#provincia').append( "<option value=" + val.in_idprov + " >" + val.ch_provincia + " </option>");
                      });
     });
});

  $("#provincia").change(function(evento){

   var dep=parseInt($('#departamento').val());
    var pro=parseInt($(this).val());
   var url="/local/index/jsondistrito?iddepa=" + dep + "&iddpro=" + pro
  console.log(pro);
      $.getJSON(url,function(data){
         $("#distrito").empty();
        $("#distrito").append("<option value=''>Seleccione</option>");
    $.each(data,function(i,val){

                $('#distrito').append( "<option value=" + val.in_iddis + " >" + val.ch_distrito + " </option>");

          });
     });
});

//mapa

var map;

function load_map() {
    var myLatlng = new google.maps.LatLng(-12.055345316962327, -77.04518530000001);
    var myOptions = {
        zoom: 4,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map($("#map_canvas").get(0), myOptions);
}

$('#search').on('click', function() {
  load_map();
  $('#map_canvas').css("display","block");
    var address = $('#address').val();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address}, geocodeResult);
});
var infoWindow = null;

function openInfoWindow(marker) {
    var markerLatLng = marker.getPosition();
   $('#de_latitud').html("");
    $('#de_longitud').html("");
    var l= markerLatLng.lat();
    var lo = markerLatLng.lng();
   $('#de_latitud').val(l);
    $('#de_longitud').val(lo);

}

function geocodeResult(results, status) {
    // Verificamos el estatus
    if (status == 'OK') {
        // Si hay resultados encontrados, centramos y repintamos el mapa
        // esto para eliminar cualquier pin antes puesto
        var mapOptions = {
            center: results[0].geometry.location,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map($("#map_canvas").get(0), mapOptions);
        // fitBounds acercará el mapa con el zoom adecuado de acuerdo a lo buscado
        map.fitBounds(results[0].geometry.viewport);
        $('#de_latitud').val(results[0].geometry.location.lat());
      $('#de_longitud').val(results[0].geometry.location.lng());
        // Dibujamos un marcador con la ubicación del primer resultado obtenido
        var markerOptions = { position: results[0].geometry.location ,draggable: true}
        var marker = new google.maps.Marker(markerOptions);
        google.maps.event.addListener(marker, 'dragend', function(){ openInfoWindow(marker); });
        marker.setMap(map);
    } else {
        // En caso de no haber resultados o que haya ocurrido un error
        // lanzamos un mensaje con el error
        alert("Geocoding no tuvo éxito debido a: " + status);
    }
}

  //carga imagen
// $('#para').click(function(){
//       var btn_firma = $('#addImage'), interval;
//       new AjaxUpload('#addImage', {
//         action: 'includes/uploadFile.php',onSubmit : function(file , ext){
//           if (! (ext && /^(jpg|png)$/.test(ext))){
//             alert('Sólo se permiten Imagenes .jpg o .png');
//             return false;
//           } else {
//             $('#loaderAjax').show();
//             btn_firma.text('Espere por favor');
//             this.disable();
//           }
//         },
//         onComplete: function(file, response){

//           btn_firma.text('Cambiar Imagen');
//           respuesta = $.parseJSON(response);
//           if(respuesta.respuesta == 'done'){
//             $('#fotografia').removeAttr('scr');
//             $('#fotografia').attr('src','img/' + respuesta.fileName);
//             $('#loaderAjax').show();
//           }
//           else{
//             alert(respuesta.mensaje);
//           }

//           $('#loaderAjax').hide();
//           this.enable();
//         }
//     });
// });

//

$(".eli").on("click",function(){
	var id = $(this).attr('data-id');
	var nom =$(this).attr('name');
  $('#eli-user').modal('show');
  console.log(id);
	$('#verusuario').attr({'data-id':id});
	$('#verusuario').html("Estas seguro de eliminar al usuario " + nom + " ?");
});

$('.check_rest').mousedown(function() {
    var id = $(this).attr('id');
    console.log(id);
    console.log()
    var est;
        if (!$(this).is(':checked')) {
          if (confirm("Desea Activar al Restaurante ?") ){
            var est="activo";
            var request = $.ajax({
            url: "restaurante/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
            $(this).prop("checked", "checked");
            $("#" + id).addClass("success");
            $("#la" + id).removeClass().addClass("label label-success");
            $("#la" + id).html("");
            $("#la" + id).html("activo");
                 };
        }else{
          var est="desactivo";
            var request = $.ajax({
            url: "restaurante/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
          $("#" + id).removeClass("success");
          $("#la" + id).removeClass().addClass("label label-important");
          $("#la" + id).html("");
            $("#la" + id).html("desactivo");
              }
    });

  $('.check').mousedown(function() {
  	var id = $(this).attr('id');
    console.log(id);
    console.log()
    var est;
        if (!$(this).is(':checked')) {
        	if (confirm("Desea Activar al usuario ?") ){
            var est="activo";
            var request = $.ajax({
            url: "/usuario/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
            $(this).prop("checked", "checked");
            $("#" + id).addClass("success");
            $("#la" + id).removeClass().addClass("label label-success");
            $("#la" + id).html("");
            $("#la" + id).html("activo");
                 };
        }else{
          var est="desactivo";
            var request = $.ajax({
            url: "/usuario/index/cambiaestado?id="+id + "&estado=" + est,
            type: "get",
            data: {id: id , estado:est}
                   });
        	$("#" + id).removeClass("success");
        	$("#la" + id).removeClass().addClass("label label-important");
          $("#la" + id).html("");
            $("#la" + id).html("desactivo");
              }
    });

  $("#delete").on("click",function(){
	var user=$("#verusuario").attr("data-id");
	$("#" + user).closest('tr').remove();
	$('#eli-user').modal('hide');
	console.log(user);
  var request = $.ajax({
  url: "/usuario/index/eliminarusu?id="+user,
  type: "POST",
  data: {id: user}
  });
});
});
<|endoftext|>


<commit_before>require(
    [
        'jquery',
        'Portlet/Form'
    ],
    function ($, PortletForm) {
        'use strict';

        describe('Portlet Form', function () {

            var $DefaultForm = null,
                portletForm  = null;

            beforeEach(function (done) {
                reloadFixtures(function () {
                    $DefaultForm = $('#DefaultForm');
                    portletForm          = new PortletForm($DefaultForm);
                    done();
                });
            });

            describe('Buttons', function () {
                it('should get all buttons from a portlet', function () {
                    expect(portletForm.getButtonList()).to.have.length(2);
                });

                it('should disable all buttons from a portlet', function () {
                    portletForm.disableButton();

                    expect(portletForm.getElement().find('[name="email"]').is(':enabled')).to.be.true;
                    expect(portletForm.getElement().find('[name="password"]').is(':enabled')).to.be.true;
                    expect(portletForm.getButtonList().filter(':submit').is(':disabled')).to.be.true;
                    expect(portletForm.getButtonList().filter('button').is(':disabled')).to.be.true;
                });

                it('should enable all buttons from a portlet', function () {
                    portletForm.enableButton();

                    expect(portletForm.getButtonList().filter(':submit').is(':enabled')).to.be.true;
                    expect(portletForm.getButtonList().filter('button').is(':enabled')).to.be.true;
                });
            });

            describe('request handling', function () {
                it('should have form buttons disabled as soon as something is requested', function (done) {
                    portletForm.addEventListener('load.start', function () {
                        expect(this.getElement().find('[name="email"]').is(':enabled')).to.be.true;
                        expect(this.getElement().find('[name="password"]').is(':enabled')).to.be.true;
                        expect(this.getButtonList().filter(':submit').is(':disabled')).to.be.true;
                        expect(this.getButtonList().filter('button').is(':disabled')).to.be.true;

                        done();
                    });

                    portletForm.load();
                });
            });

            describe('Request actions', function () {

                it('should submit a form', function (done) {
                    var emailValue    = 'foobar@foobar.com',
                        passwordValue = '123321';

                    portletForm.getElement().find('[name="email"]').val(emailValue);
                    portletForm.getElement().find('[name="password"]').val(passwordValue);

                    portletForm.addEventListener('submit.start', function () {
                        var httpRequest = this.httpRequest;

                        expect(httpRequest.dataType).to.eql('html');
                        expect(httpRequest.method).to.eql('POST');
                        expect(httpRequest.url).to.eql('/foo/bar');
                        expect(httpRequest.data.split('&')[0]).to.have.string(encodeURIComponent(emailValue));
                        expect(httpRequest.data.split('&')[1]).to.have.string(encodeURIComponent(passwordValue));

                        done();
                    });

                    portletForm.submit();
                });

                describe('update a form', function () {
                    var $comboBox = null;

                    beforeEach(function () {
                        $comboBox = $('#comboBox');
                        $comboBox.find('option')[1].setAttribute('selected', true);
                    });

                    it('should with a action without params', function (done) {

                        portletForm.addEventListener('update.start', function () {
                            var httpRequest = this.httpRequest;

                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.method).to.eql('POST');
                            expect(httpRequest.url).to.eql('/foo/bar?updateField=1');
                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.data.split('&')[3]).to.have.string('value2');

                            done();
                        });

                        portletForm.update();
                    });

                    it('should with a action with params', function (done) {

                        portletForm.getElement().find('form').attr('action', '/foo/bar?foo=1&bar=2')

                        portletForm.addEventListener('update.start', function () {
                            var httpRequest = this.httpRequest;

                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.method).to.eql('POST');
                            expect(httpRequest.url).to.eql('/foo/bar?foo=1&bar=2&updateField=1');
                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.data.split('&')[3]).to.have.string('value2');

                            done();
                        });

                        portletForm.update();
                    });
                });

            });

        });
    }
);
<commit_msg>fix spec name<commit_after>require(
    [
        'jquery',
        'Portlet/Form'
    ],
    function ($, PortletForm) {
        'use strict';

        describe('Portlet Form', function () {

            var $DefaultForm = null,
                portletForm  = null;

            beforeEach(function (done) {
                reloadFixtures(function () {
                    $DefaultForm = $('#DefaultForm');
                    portletForm          = new PortletForm($DefaultForm);
                    done();
                });
            });

            describe('Buttons', function () {
                it('should get all buttons from a portlet', function () {
                    expect(portletForm.getButtonList()).to.have.length(2);
                });

                it('should disable all buttons from a portlet', function () {
                    portletForm.disableButton();

                    expect(portletForm.getElement().find('[name="email"]').is(':enabled')).to.be.true;
                    expect(portletForm.getElement().find('[name="password"]').is(':enabled')).to.be.true;
                    expect(portletForm.getButtonList().filter(':submit').is(':disabled')).to.be.true;
                    expect(portletForm.getButtonList().filter('button').is(':disabled')).to.be.true;
                });

                it('should enable all buttons from a portlet', function () {
                    portletForm.enableButton();

                    expect(portletForm.getButtonList().filter(':submit').is(':enabled')).to.be.true;
                    expect(portletForm.getButtonList().filter('button').is(':enabled')).to.be.true;
                });
            });

            describe('request handling', function () {
                it('should have form buttons disabled as soon as something is requested', function (done) {
                    portletForm.addEventListener('load.start', function () {
                        expect(this.getElement().find('[name="email"]').is(':enabled')).to.be.true;
                        expect(this.getElement().find('[name="password"]').is(':enabled')).to.be.true;
                        expect(this.getButtonList().filter(':submit').is(':disabled')).to.be.true;
                        expect(this.getButtonList().filter('button').is(':disabled')).to.be.true;

                        done();
                    });

                    portletForm.load();
                });
            });

            describe('Request actions', function () {

                it('should submit a form', function (done) {
                    var emailValue    = 'foobar@foobar.com',
                        passwordValue = '123321';

                    portletForm.getElement().find('[name="email"]').val(emailValue);
                    portletForm.getElement().find('[name="password"]').val(passwordValue);

                    portletForm.addEventListener('submit.start', function () {
                        var httpRequest = this.httpRequest;

                        expect(httpRequest.dataType).to.eql('html');
                        expect(httpRequest.method).to.eql('POST');
                        expect(httpRequest.url).to.eql('/foo/bar');
                        expect(httpRequest.data.split('&')[0]).to.have.string(encodeURIComponent(emailValue));
                        expect(httpRequest.data.split('&')[1]).to.have.string(encodeURIComponent(passwordValue));

                        done();
                    });

                    portletForm.submit();
                });

                describe('update a form', function () {
                    var $comboBox = null;

                    beforeEach(function () {
                        $comboBox = $('#comboBox');
                        $comboBox.find('option')[1].setAttribute('selected', true);
                    });

                    it('should update with a action without params', function (done) {

                        portletForm.addEventListener('update.start', function () {
                            var httpRequest = this.httpRequest;

                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.method).to.eql('POST');
                            expect(httpRequest.url).to.eql('/foo/bar?updateField=1');
                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.data.split('&')[3]).to.have.string('value2');

                            done();
                        });

                        portletForm.update();
                    });

                    it('should update with a action with params', function (done) {

                        portletForm.getElement().find('form').attr('action', '/foo/bar?foo=1&bar=2')

                        portletForm.addEventListener('update.start', function () {
                            var httpRequest = this.httpRequest;

                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.method).to.eql('POST');
                            expect(httpRequest.url).to.eql('/foo/bar?foo=1&bar=2&updateField=1');
                            expect(httpRequest.dataType).to.eql('html');
                            expect(httpRequest.data.split('&')[3]).to.have.string('value2');

                            done();
                        });

                        portletForm.update();
                    });
                });

            });

        });
    }
);
<|endoftext|>


<commit_before>document.addEventListener("touchstart", function() {}, true);

Messenger.options = {
  extraClasses: 'messenger-on-top',
  parentLocations: ['.main'],
  theme: 'block'
};
var duration = 10000000000000;

$(document).on('tap', '#button', function(e) {
  var $this = $(this);
  $this.addClass('active');

    $this.toggleClass('record');
    if ($this.hasClass('record')) {
      $('#label').text('Stop');
      socket.emit('start', 'go');
      if(config.remote){
        setTimeout(function(){
          $this.removeClass('active');
          $this.toggleClass('record');
          $('#label').text('Record');
          loading();
          setTimeout(function(){
            $('#button').removeClass('wait');
            $('#label').text('Record');
          }, config.clickInterval);
        }, 250);
      }
    } else {
      $('#label').text('Record');
      socket.emit('stop', 'go');
    }

});

socket = io(':' + config.server.port)
  .on('connect', function() {
    console.log('connected');
    Messenger().post({
      message: 'Connected',
      type: 'success',
      id: 'info',
      hideAfter: duration
    });
    init();
  })
  .on('disconnect', function() {
    console.log('We\'ve been disconnected');
    Messenger().post({
      message: 'Disconnected',
      type: 'error',
      id: 'info',
      hideAfter: duration
    });
    freez();
  })
  .on('error', function() {
    console.log('error while connecting');
  })
  .on('reconnect', function(nbtry) {
    Messenger().post({
      message: 'Successfull reconnection.',
      type: 'info',
      id: 'info',
      hideAfter: duration
    });
    init();
    console.log('Successfull reconnect after ' + nbtry + ' trying.');
  })
  .on('reconnecting', function(nbtry) {
    console.log('Trying to reconnect.');
    Messenger().post({
      message: 'Attempting to reconnect...Reconnect',
      type: 'warning',
      id: 'info',
      hideAfter: duration
    });
  })
  .on('time', function(data) {
    console.log(data);
    var percent = 100 - (data.time / data.duration) * 100;
    $('.bar').css({
      width: percent + '%'
    });
    $('.pack span').text(moment.utc(data.time).format("HH:mm:ss"));
  })
  .on('stop', function(data) {
    console.log('finished: ', data);
    $('#label').text('Record').addClass('wait');
    $('#button').removeClass('record').addClass('wait');
  })
  .on('error', function(data) {
    console.log(data);
    $('message').addClass('error').text(data.msg);
  })
  .on('success', function(data) {
    $('message').addClass('success').text(data.msg);
    setTimeout(clearMessage, 3000);
  });

var clearMessage = function() {
  $('message').empty().removeClass('error success');
  $('.wait').removeClass('wait');
}

var init = function() {
  $('.bar').css({
    width: 0 + '%'
  });
  $('.pack span').text('00:00:00');
  $('.wait').removeClass('wait');
  if(config.remote){
    $('.pack').hide();
  }
}

var freez = function() {
  $('.bar').css({
    width: 0 + '%'
  });
  $('.pack span').text('00:00:00');
  $('#label').text('Record').addClass('wait');
  $('#button').removeClass('record').addClass('wait');
}

var loading = function(){
  $('#label').text('Loading').addClass('wait');
  $('#button').addClass('wait');
}<commit_msg>fix loading position<commit_after>document.addEventListener("touchstart", function() {}, true);

Messenger.options = {
  extraClasses: 'messenger-on-top',
  parentLocations: ['.main'],
  theme: 'block'
};
var duration = 10000000000000;

$(document).on('tap', '#button', function(e) {
  var $this = $(this);
  $this.addClass('active');

    $this.toggleClass('record');
    if ($this.hasClass('record')) {
      $('#label').text('Stop');
      socket.emit('start', 'go');
      if(config.remote){
        loading();
        setTimeout(function(){
          $this.removeClass('active');
          $this.toggleClass('record');
          $('#label').text('Record');
          setTimeout(function(){
            $('#button').removeClass('wait');
            $('#label').text('Record');
          }, config.clickInterval);
        }, 250);
      }
    } else {
      $('#label').text('Record');
      socket.emit('stop', 'go');
    }

});

socket = io(':' + config.server.port)
  .on('connect', function() {
    console.log('connected');
    Messenger().post({
      message: 'Connected',
      type: 'success',
      id: 'info',
      hideAfter: duration
    });
    init();
  })
  .on('disconnect', function() {
    console.log('We\'ve been disconnected');
    Messenger().post({
      message: 'Disconnected',
      type: 'error',
      id: 'info',
      hideAfter: duration
    });
    freez();
  })
  .on('error', function() {
    console.log('error while connecting');
  })
  .on('reconnect', function(nbtry) {
    Messenger().post({
      message: 'Successfull reconnection.',
      type: 'info',
      id: 'info',
      hideAfter: duration
    });
    init();
    console.log('Successfull reconnect after ' + nbtry + ' trying.');
  })
  .on('reconnecting', function(nbtry) {
    console.log('Trying to reconnect.');
    Messenger().post({
      message: 'Attempting to reconnect...Reconnect',
      type: 'warning',
      id: 'info',
      hideAfter: duration
    });
  })
  .on('time', function(data) {
    console.log(data);
    var percent = 100 - (data.time / data.duration) * 100;
    $('.bar').css({
      width: percent + '%'
    });
    $('.pack span').text(moment.utc(data.time).format("HH:mm:ss"));
  })
  .on('stop', function(data) {
    console.log('finished: ', data);
    $('#label').text('Record').addClass('wait');
    $('#button').removeClass('record').addClass('wait');
  })
  .on('error', function(data) {
    console.log(data);
    $('message').addClass('error').text(data.msg);
  })
  .on('success', function(data) {
    $('message').addClass('success').text(data.msg);
    setTimeout(clearMessage, 3000);
  });

var clearMessage = function() {
  $('message').empty().removeClass('error success');
  $('.wait').removeClass('wait');
}

var init = function() {
  $('.bar').css({
    width: 0 + '%'
  });
  $('.pack span').text('00:00:00');
  $('.wait').removeClass('wait');
  if(config.remote){
    $('.pack').hide();
  }
}

var freez = function() {
  $('.bar').css({
    width: 0 + '%'
  });
  $('.pack span').text('00:00:00');
  $('#label').text('Record').addClass('wait');
  $('#button').removeClass('record').addClass('wait');
}

var loading = function(){
  $('#label').text('Loading').addClass('wait');
  $('#button').addClass('wait');
}<|endoftext|>


<commit_before>  $(document).keydown(function (e) {
      var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

      switch (keyCode) {
          case arrow.left:
              $('.previous').trigger('click');
          break;
          case arrow.right:
              $('.next').trigger('click');
          break;
          case arrow.down:
              $('.topOfMain .more').trigger('click');
          break;
          case arrow.up:
              $('.topOfMain .more-back').trigger('click');
          break;
          default: return; // allow other keys to be handled
      }
      e.preventDefault();
      // prevent default action (eg. page moving up/down)
      // but consider accessibility (eg. user may want to use keys to choose a radio button)
  });
// Menu

(function() {
  showDashboardNav();

  $(".flyout-btn").click(function() {
    console.log('click 1');
    $(".flyout-btn").toggleClass("btn-rotate");
    $(".nav-overlay").toggleClass("open hide");
    // $(".flyout").find("a").removeClass();
    $('.nav-icon').toggleClass('open');

    $li = $('.topOfMain');
    sendGAEvent('menu-button-click', username + "#" + $li.attr('cardId'), $li.attr('cardIndex'));

    return $(".flyout").removeClass("flyout-init fade").toggleClass("expand");
  });

  $('.removed-from-deck').delay(1000).remove();

  $(".nav-overlay .navigation-content").find(".navigation-item").click(function (e) {
    console.log('click 6');
    e.preventDefault();                   // prevent default anchor behavior
    var goTo = this.getAttribute("href"); // store anchor href

    if (goTo.substr(0, 1) === '/')
      window.location.href = goTo;
    else
      window.open(goTo);
  });

}).call(this);

function showDashboardNav() {
  var lastPrevUserDate = new Date('2015-10-14T20:50:40.640Z');
  if (registeredOn && registeredOn < lastPrevUserDate) { // registeredOn is declared in the html page
      $('.dashboard-nav').removeClass('hide');
  }
}

function clickPulse(x, y, $pulseElem) {

    var clickY = y - $pulseElem.offset().top;
    var clickX = x - $pulseElem.offset().left;
    var setX = parseInt(clickX);
    var setY = parseInt(clickY);

    $pulseElem.find("svg.click-circle").remove();
    $pulseElem.append('<svg class="click-circle"><circle cx="'+setX+'" cy="'+setY+'" r="'+100+'"></circle></svg>');

    var c = $pulseElem.find("circle");
    c.animate(
        {
          "r" : $pulseElem.outerWidth()
        }, 200, function() { $pulseElem.find("svg.click-circle").remove(); }
    );
}

function sendGAEvent(eventAction, eventLabel, eventValue) {
    var gaObj = {};
    gaObj.eventCategory = 'card-stack';
    gaObj.eventAction = eventAction;
    gaObj.eventLabel = eventLabel;
    gaObj.eventValue = eventValue;

    console.log('gaObj', gaObj);

    ga('send', 'event', gaObj);
}

window.logInfoClick = function(elem) {
    var $elem = $(elem);
    var cardLi = $elem.parentsUntil('ul', 'li')[0];
    sendGAEvent('infoLink_click', cardLi.getAttribute('cardId'), username);
};

<commit_msg>changed the event in button click to the composite 1self event<commit_after>  $(document).keydown(function (e) {
      var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

      switch (keyCode) {
          case arrow.left:
              $('.previous').trigger('click');
          break;
          case arrow.right:
              $('.next').trigger('click');
          break;
          case arrow.down:
              $('.topOfMain .more').trigger('click');
          break;
          case arrow.up:
              $('.topOfMain .more-back').trigger('click');
          break;
          default: return; // allow other keys to be handled
      }
      e.preventDefault();
      // prevent default action (eg. page moving up/down)
      // but consider accessibility (eg. user may want to use keys to choose a radio button)
  });
// Menu

(function() {
  showDashboardNav();

  var getCardData = function(cardElem){
      var cardData = cardElem.find('.cardData');
      cardData = decodeURIComponent(cardData.val());
      cardData = JSON.parse(cardData);
      return cardData;
  };

  var getEventLabel = function(cardData, index){
      var result = cardData.type + '/';
      result += cardData.cardDate + '/';
      if(cardData.objectTags){
          result += cardData.objectTags + '/' + cardData.actionTags + '/';
      }
      result += (index - globalCardsArray.length);

      return result;
  };

  $(".flyout-btn").click(function() {
    console.log('click 1');
    $(".flyout-btn").toggleClass("btn-rotate");
    $(".nav-overlay").toggleClass("open hide");
    // $(".flyout").find("a").removeClass();
    $('.nav-icon').toggleClass('open');

    $li = $('.topOfMain');
    var menuEvent = {
      eventCategory: 'navigation',
      eventAction: 'menu-button-click',
      eventLabel: getEventLabel(getCardData($li), $li.attr('cardIndex') )
    };
    analytics.send('event', menuEvent);

    return $(".flyout").removeClass("flyout-init fade").toggleClass("expand");
  });

  $('.removed-from-deck').delay(1000).remove();

  $(".nav-overlay .navigation-content").find(".navigation-item").click(function (e) {
    console.log('click 6');
    e.preventDefault();                   // prevent default anchor behavior
    var goTo = this.getAttribute("href"); // store anchor href

    if (goTo.substr(0, 1) === '/')
      window.location.href = goTo;
    else
      window.open(goTo);
  });

}).call(this);

function showDashboardNav() {
  var lastPrevUserDate = new Date('2015-10-14T20:50:40.640Z');
  if (registeredOn && registeredOn < lastPrevUserDate) { // registeredOn is declared in the html page
      $('.dashboard-nav').removeClass('hide');
  }
}

function clickPulse(x, y, $pulseElem) {

    var clickY = y - $pulseElem.offset().top;
    var clickX = x - $pulseElem.offset().left;
    var setX = parseInt(clickX);
    var setY = parseInt(clickY);

    $pulseElem.find("svg.click-circle").remove();
    $pulseElem.append('<svg class="click-circle"><circle cx="'+setX+'" cy="'+setY+'" r="'+100+'"></circle></svg>');

    var c = $pulseElem.find("circle");
    c.animate(
        {
          "r" : $pulseElem.outerWidth()
        }, 200, function() { $pulseElem.find("svg.click-circle").remove(); }
    );
}

function sendGAEvent(eventAction, eventLabel, eventValue) {
    var gaObj = {};
    gaObj.eventCategory = 'card-stack';
    gaObj.eventAction = eventAction;
    gaObj.eventLabel = eventLabel;
    gaObj.eventValue = eventValue;

    console.log('gaObj', gaObj);

    ga('send', 'event', gaObj);
}

window.logInfoClick = function(elem) {
    var $elem = $(elem);
    var cardLi = $elem.parentsUntil('ul', 'li')[0];
    sendGAEvent('infoLink_click', cardLi.getAttribute('cardId'), username);
};

<|endoftext|>


<commit_before>var ledInfo = [];
var rootURL;
var arrDims = {};

function init(){
    var colorpicker = $('#cp7').colorpicker({
    	format: "hex",
        color: '#ff0000',
        container: true,
        inline: true
    });

    d3.json('config.js', function(err, config){
		if (err ||  !config.rootURL ){ //TODO test removing config.js and fing with the contents
    		console.log(err, config);
    	}
    	rootURL = config.rootURL;

		//get LED info
	    $.ajax({url: rootURL + "/getLEDArrDimensions"}).fail(function(errorInfo) {
 			changeStatus('alert', errorInfo.status, errorInfo.statusText);
 		}).then( function(arrDimsOut) {
			changeStatus();
			arrDims = arrDimsOut;
			var ledInfo = d3.range(arrDims.width * arrDims.height).map(function(d){
				var xy = getXY(d);
				xy.addr = d;
				return xy;
		    });

			var circleData = {r : 10, spacing: 5};

			var svg = d3.select("#ledArray").append("svg");
			var ledGrp = svg.append("g").attr("transform", "scale(1,-1) translate(" + circleData.r + ",-" + (((circleData.r*2)+circleData.spacing)*arrDims.height) + ")");

			ledGrp.selectAll("circle").data(ledInfo).enter().append("circle")
			.attr({
				cx: function(d){return d.x * (((circleData.r*2)+circleData.spacing))+circleData.spacing;},
      			cy: function(d){return d.y * (((circleData.r*2)+circleData.spacing))+circleData.spacing;},
		       	r: circleData.r,
		       	"stroke-width": 1,
      			"stroke": "#000",
		       	"fill": "#000000",
		       	"id": function(d){return "led_" + d.addr;}
			}).on("click", function(clkLED){
				//todo setLED and set led image on success
				var led = d3.select("#led_"+clkLED.addr);
				var color = {};

				if (led.attr("fill") == "#000000"){
					color.hex = $('#cp7').colorpicker().data().color;
	       		}
	       		else {
					color.hex = "#000000";
	       		}

	       		color.r = parseInt(color.hex.substring(1,3), 16);
	       		color.g = parseInt(color.hex.substring(3,5), 16);
	       		color.b = parseInt(color.hex.substring(5,7), 16);

				$.ajax({
					method: 'POST',
					url: rootURL + "/setPixel",
					data: {
						pixX:clkLED.x,
						pixY:clkLED.y,
						pixR:color.r,
						pixG:color.g,
						pixB:color.b
					}
				}).fail(function(errorInfo) {
		 			changeStatus('alert', errorInfo.status, errorInfo.statusText);
		 		}).then(function(d,err){
		 			changeStatus();
					led.attr("fill", color.hex);
				});
	       });

	       refreshFromDevice();

	       setInterval(function(){
	       	refreshFromDevice();
	       }, 1000);
	    });
    });
}

function getXY(addr){
	var yNum = Math.floor(addr/arrDims.width);
	var xNum;
	if (yNum%2 ==0){ //even row
		xNum = addr - (yNum * arrDims.width);
	}
	else { //odd row
		xNum = ((yNum+1)*arrDims.width)-(addr+1); //can this be simplified?
	}

	return {x: xNum, y: yNum };
}

function refreshFromDevice(){
	$.ajax({ url: rootURL + "/getLEDPixels"}).fail(function(errorInfo) {
		changeStatus('alert', errorInfo.status, errorInfo.statusText);
	}).then(function(particleLEDInfo, err) {
		changeStatus();
    	for (var i = 0; i < particleLEDInfo.leds.length; i++) {
    		var led = d3.select("#led_"+ i);
			var fillR = particleLEDInfo.leds[i].r.toString(16);
    		var fillG = particleLEDInfo.leds[i].g.toString(16);
    		var fillB = particleLEDInfo.leds[i].b.toString(16);

    		fillR = fillR.length == 1 ? "0" + fillR : fillR;
    		fillG = fillG.length == 1 ? "0" + fillG : fillG;
    		fillB = fillB.length == 1 ? "0" + fillB : fillB;

    		led.attr("fill", "#" + fillR + fillG + fillB);
    	}
    });
}

function changeStatus(kind, statusCode, statusMessage){
	var container = $('.status-container');
	if (kind === undefined){
		container.empty();
	}
	else{
		var alertText = statusCode + ": " + statusMessage;
		container.append("
" + alertText + "
");
	}

}<commit_msg>Add processing grey color post click. Don't keep appending new error messages on forever<commit_after>var ledInfo = [];
var rootURL;
var arrDims = {};

function init(){
    var colorpicker = $('#cp7').colorpicker({
    	format: "hex",
        color: '#ff0000',
        container: true,
        inline: true
    });

    d3.json('config.js', function(err, config){
		if (err ||  !config.rootURL ){ //TODO test removing config.js and fing with the contents
    		console.log(err, config);
    	}
    	rootURL = config.rootURL;

		//get LED info
	    $.ajax({url: rootURL + "/getLEDArrDimensions"}).fail(function(errorInfo) {
 			changeStatus('alert', errorInfo.status, errorInfo.statusText);
 		}).then( function(arrDimsOut) {
			changeStatus();
			arrDims = arrDimsOut;
			var ledInfo = d3.range(arrDims.width * arrDims.height).map(function(d){
				var xy = getXY(d);
				xy.addr = d;
				return xy;
		    });

			var circleData = {r : 10, spacing: 5};

			var svg = d3.select("#ledArray").append("svg");
			var ledGrp = svg.append("g").attr("transform", "scale(1,-1) translate(" + circleData.r + ",-" + (((circleData.r*2)+circleData.spacing)*arrDims.height) + ")");

			ledGrp.selectAll("circle").data(ledInfo).enter().append("circle")
			.attr({
				cx: function(d){return d.x * (((circleData.r*2)+circleData.spacing))+circleData.spacing;},
      			cy: function(d){return d.y * (((circleData.r*2)+circleData.spacing))+circleData.spacing;},
		       	r: circleData.r,
		       	"stroke-width": 1,
      			"stroke": "#000",
		       	"fill": "#000000",
		       	"id": function(d){return "led_" + d.addr;}
			}).on("click", function(clkLED){
				//todo setLED and set led image on success
				var led = d3.select("#led_"+clkLED.addr);
				var color = {};

				if (led.attr("fill") == "#000000"){
					color.hex = $('#cp7').colorpicker().data().color;
	       		}
	       		else {
					color.hex = "#000000";
	       		}

	       		color.r = parseInt(color.hex.substring(1,3), 16);
	       		color.g = parseInt(color.hex.substring(3,5), 16);
	       		color.b = parseInt(color.hex.substring(5,7), 16);

				led.attr("fill", "#666666");

				$.ajax({
					method: 'POST',
					url: rootURL + "/setPixel",
					data: {
						pixX:clkLED.x,
						pixY:clkLED.y,
						pixR:color.r,
						pixG:color.g,
						pixB:color.b
					}
				}).fail(function(errorInfo) {
		 			changeStatus('alert', errorInfo.status, errorInfo.statusText);
		 		}).then(function(d,err){
		 			changeStatus();
					led.attr("fill", color.hex);
				});
	       });

	       refreshFromDevice();

	       setInterval(function(){
	       	refreshFromDevice();
	       }, 1000);
	    });
    });
}

function getXY(addr){
	var yNum = Math.floor(addr/arrDims.width);
	var xNum;
	if (yNum%2 ==0){ //even row
		xNum = addr - (yNum * arrDims.width);
	}
	else { //odd row
		xNum = ((yNum+1)*arrDims.width)-(addr+1); //can this be simplified?
	}

	return {x: xNum, y: yNum };
}

function refreshFromDevice(){
	$.ajax({ url: rootURL + "/getLEDPixels"}).fail(function(errorInfo) {
		changeStatus('alert', errorInfo.status, errorInfo.statusText);
	}).then(function(particleLEDInfo, err) {
		changeStatus();
    	for (var i = 0; i < particleLEDInfo.leds.length; i++) {
    		var led = d3.select("#led_"+ i);
			var fillR = particleLEDInfo.leds[i].r.toString(16);
    		var fillG = particleLEDInfo.leds[i].g.toString(16);
    		var fillB = particleLEDInfo.leds[i].b.toString(16);

    		fillR = fillR.length == 1 ? "0" + fillR : fillR;
    		fillG = fillG.length == 1 ? "0" + fillG : fillG;
    		fillB = fillB.length == 1 ? "0" + fillB : fillB;

    		led.attr("fill", "#" + fillR + fillG + fillB);
    	}
    });
}

function changeStatus(kind, statusCode, statusMessage){
	var container = $('.status-container');

	container.empty();

	if (kind !== undefined) {
		var alertText = statusCode + ": " + statusMessage;
		container.append("
" + alertText + "
");
	}
}<|endoftext|>