<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test the cluster helper functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var cluster = require("org/arangodb/cluster");
var jsunity = require("jsunity");

var compareStringIds = function (l, r) {
  if (l.length != r.length) {
    return l.length - r.length < 0 ? -1 : 1;
  }

  // length is equal
  for (i = 0; i < l.length; ++i) {
    if (l[i] != r[i]) {
      return l[i] < r[i] ? -1 : 1;
    }
  }

  return 0;
};

// -----------------------------------------------------------------------------
// --SECTION--                                                           cluster
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: cluster enabled
////////////////////////////////////////////////////////////////////////////////

function ClusterEnabledSuite () {
  var agency = ArangoAgency;
  var ss = ArangoServerState;
  var ci = ArangoClusterInfo;
  var oldPrefix = agency.prefix(true);
  var oldId = ss.id();
  var oldRole = ss.role();

  var cleanDirectories = function () {
    [ "Target", "Plan", "Current" ].forEach(function (d) {
      try {
        agency.remove(d, true);
      }
      catch (err) {
        // dir may not exist. this is not a problem
      }
    });
  };

  var initValues = function () {
    [ "Target",
      "Plan",
      "Current",
      "Target/DBServers",
      "Target/Coordinators",
      "Target/Collections",
      "Plan/DBServers",
      "Plan/Coordinators",
      "Plan/Collections",
      "Current/ServersRegistered",
      "Current/DBServers",
      "Current/Coordinators",
      "Current/Collections",
      "Current/ShardsCopied"
    ].forEach(function (d) {
      try {
        agency.createDirectory(d);
      }
      catch (err) {
      }
    });
  };

  return {
    setUp : function () {
      assertTrue(agency.setPrefix("UnitTestsAgency"));
      assertEqual("UnitTestsAgency", agency.prefix(true));

      cleanDirectories();
      initValues();
    },

    tearDown : function () {
      cleanDirectories();

      assertTrue(agency.setPrefix(oldPrefix));
      ss.setId(oldId);
      assertEqual(oldPrefix, agency.prefix(true));
      ss.setRole(oldRole);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test id
////////////////////////////////////////////////////////////////////////////////

    testId : function () {
      ss.setId("myself");
      assertEqual("myself", ss.id());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test address
////////////////////////////////////////////////////////////////////////////////

    testAddress : function () {
      assertTrue(agency.set("Target/MapIDToEndpoint/myself", "tcp://127.0.0.1:8529"));
      assertTrue(agency.set("Plan/Coordinators/myself", "none"));
      assertTrue(agency.set("Plan/DBServers/myself", "other"));
      ss.setId("myself");
      ss.flush();

      assertEqual("tcp://127.0.0.1:8529", ss.address());

      assertTrue(agency.set("Target/MapIDToEndpoint/myself", "tcp://127.0.0.1:8530"));
      ss.flush();

      assertEqual("tcp://127.0.0.1:8530", ss.address());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCluster
////////////////////////////////////////////////////////////////////////////////

    testIsCluster : function () {
      assertTrue(cluster.isCluster());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinator
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorTrue : function () {
      assertTrue(agency.set("Plan/Coordinators/myself", "none"));
      ss.setId("myself");
      ss.flush();

      assertTrue(cluster.isCoordinator());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinator
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorFalse : function () {
      assertTrue(agency.set("Plan/Coordinators/DBServers/myself", "other"));
      ss.setId("myself");
      ss.flush();

      assertFalse(cluster.isCoordinator());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test role
////////////////////////////////////////////////////////////////////////////////

    testRoleCoordinator : function () {
      assertTrue(agency.set("Plan/Coordinators/myself", "none"));
      ss.setId("myself");
      ss.flush();

      assertTrue(cluster.role() !== undefined);
      assertTrue(cluster.role() === "COORDINATOR");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test role
////////////////////////////////////////////////////////////////////////////////

    testRoleDBServer : function () {
      assertTrue(agency.set("Plan/DBServers/myself", "other"));
      ss.setId("myself");
      ss.flush();

      assertTrue(cluster.role() !== undefined);
      assertTrue(cluster.role() === "PRIMARY");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test status
////////////////////////////////////////////////////////////////////////////////

    testStatus : function () {
      assertTrue(cluster.status() !== undefined);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinatorRequest
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorRequest : function () {
      assertFalse(cluster.isCoordinatorRequest(null));
      assertFalse(cluster.isCoordinatorRequest(undefined));
      assertFalse(cluster.isCoordinatorRequest({ }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { } }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { test: "" } }));
      assertTrue(cluster.isCoordinatorRequest({ headers: { "x-arango-coordinator": "abc" } }));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test doesDatabaseExist
////////////////////////////////////////////////////////////////////////////////

    testDoesDatabaseExist : function () {
      var database = {
        name: "test"
      };

      assertTrue(agency.set("Plan/Databases/" + database.name, database));
      assertTrue(agency.set("Current/DBServers/Foo", "Bar"));
      assertTrue(agency.set("Current/DBServers/Barz", "Bat"));
      assertTrue(agency.set("Current/Databases/test/Foo", database));
      assertTrue(agency.set("Current/Databases/test/Barz", database));

      assertTrue(ci.doesDatabaseExist("test"));

      assertFalse(ci.doesDatabaseExist("UnitTestsAgencyNonExisting"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test doesDatabaseExist
////////////////////////////////////////////////////////////////////////////////

    testDoesDatabaseExistNotReady : function () {
      var database = {
        name: "test"
      };

      assertTrue(agency.set("Plan/Databases/" + database.name, database));
      assertTrue(agency.set("Current/DBServers/Foo", "Bar"));
      assertTrue(agency.set("Current/DBServers/Barz", "Bat"));
      assertTrue(agency.set("Current/Databases/test/Foo", database));

      assertFalse(ci.doesDatabaseExist("test"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getCollectionInfo
////////////////////////////////////////////////////////////////////////////////

    testGetCollectionInfo : function () {
      var collection = {
        id: "123",
        name: "mycollection",
        type: 2,
        status: 3, // LOADED
        shardKeys: [ "_key" ],
        shards: { "s1" : "myself", "s2" : "other" }
      };
      assertTrue(agency.set("Current/Collections/test/" + collection.id, collection));

      var data = ci.getCollectionInfo("test", collection.id);

      assertEqual(collection.id, data.id);
      assertEqual(collection.name, data.name);
      assertEqual(collection.type, data.type);
      assertEqual(collection.status, data.status);
      assertEqual(collection.shardKeys, data.shardKeys);
      assertEqual(collection.shards, data.shards);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getCollectionInfo
////////////////////////////////////////////////////////////////////////////////

    testGetCollectionInfo2 : function () {
      var collection = {
        id: "12345868390663",
        name: "mycollection_test",
        type: 3,
        status: 2, // LOADED
        shardKeys: [ "_key", "a", "bc" ],
        shards: { "s1" : "myself", "s2" : "other", "s3" : "foo", "s4" : "bar" }
      };

      assertTrue(agency.set("Current/Collections/test/" + collection.id, collection));

      var data = ci.getCollectionInfo("test", collection.id);

      assertEqual(collection.id, data.id);
      assertEqual(collection.name, data.name);
      assertEqual(collection.type, data.type);
      assertEqual(collection.status, data.status);
      assertEqual(collection.shardKeys, data.shardKeys);
      assertEqual(collection.shards, data.shards);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getResponsibleServer
////////////////////////////////////////////////////////////////////////////////

    testGetResponsibleServer : function () {
      var collection = {
        id: "12345868390663",
        name: "mycollection_test",
        type: 3,
        status: 2, // LOADED
        shardKeys: [ "_key", "a", "bc" ],
        shards: { "s1" : "myself" }
      };

      assertTrue(agency.set("Current/Collections/test/" + collection.id, collection));
      ci.flush();

      assertEqual("myself", ci.getResponsibleServer("s1"));
      assertEqual("", ci.getResponsibleServer("s9999"));

      collection.shards = { s1: "other", s2: "myself" };
      assertTrue(agency.set("Current/Collections/test/" + collection.id, collection));
      ci.flush();

      assertEqual("other", ci.getResponsibleServer("s1"));
      assertEqual("myself", ci.getResponsibleServer("s2"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getServerEndpoint
////////////////////////////////////////////////////////////////////////////////

    testGetServerEndpoint : function () {
      assertTrue(agency.set("Current/ServersRegistered/myself", "tcp://127.0.0.1:8529"));
      ci.flush();

      assertEqual("tcp://127.0.0.1:8529", ci.getServerEndpoint("myself"));

      assertTrue(agency.set("Current/ServersRegistered/myself", "tcp://127.0.0.1:8530"));
      ci.flush();

      assertEqual("tcp://127.0.0.1:8530", ci.getServerEndpoint("myself"));

      assertTrue(agency.remove("Current/ServersRegistered/myself"));
      assertTrue(agency.set("Current/ServersRegistered/other", "tcp://127.0.0.1:8529"));
      ci.flush();

      assertEqual("", ci.getServerEndpoint("myself"));
      assertEqual("tcp://127.0.0.1:8529", ci.getServerEndpoint("other"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test uniqid
////////////////////////////////////////////////////////////////////////////////

    testUniqid : function () {
      var last = "0";

      for (var i = 0; i < 1005; ++i) {
        var id = ci.uniqid();
        assertEqual(-1, compareStringIds(last, id));
        last = id;
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test uniqid
////////////////////////////////////////////////////////////////////////////////

    testUniqidRange : function () {
      var last = "0";

      for (var i = 0; i < 100; ++i) {
        var id = ci.uniqid(10);
        assertEqual(-1, compareStringIds(last, id));
        last = id;
      }
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: cluster disabled
////////////////////////////////////////////////////////////////////////////////

function ClusterDisabledSuite () {
  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCluster
////////////////////////////////////////////////////////////////////////////////

    testIsCluster : function () {
      assertFalse(cluster.isCluster());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test role
////////////////////////////////////////////////////////////////////////////////

    testRole : function () {
      assertTrue(cluster.role() === undefined);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test status
////////////////////////////////////////////////////////////////////////////////

    testStatus : function () {
      assertTrue(cluster.status() === undefined);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinatorRequest
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorRequest : function () {
      assertFalse(cluster.isCoordinatorRequest(null));
      assertFalse(cluster.isCoordinatorRequest(undefined));
      assertFalse(cluster.isCoordinatorRequest({ }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { } }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { test: "" } }));
      assertTrue(cluster.isCoordinatorRequest({ headers: { "x-arango-coordinator": "abc" } }));
    }
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

if (cluster.isCluster()) {
  jsunity.run(ClusterEnabledSuite);
}
else {
  jsunity.run(ClusterDisabledSuite);
}

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<commit_msg>Fix tests on cluster.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test the cluster helper functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var cluster = require("org/arangodb/cluster");
var jsunity = require("jsunity");
var _ = require("underscore");

var compareStringIds = function (l, r) {
  if (l.length != r.length) {
    return l.length - r.length < 0 ? -1 : 1;
  }

  // length is equal
  for (i = 0; i < l.length; ++i) {
    if (l[i] != r[i]) {
      return l[i] < r[i] ? -1 : 1;
    }
  }

  return 0;
};

// -----------------------------------------------------------------------------
// --SECTION--                                                           cluster
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: cluster enabled
////////////////////////////////////////////////////////////////////////////////

function ClusterEnabledSuite () {
  var agency = ArangoAgency;
  var ss = ArangoServerState;
  var ci = ArangoClusterInfo;
  var oldPrefix = agency.prefix(true);
  var oldId = ss.id();
  var oldRole = ss.role();

  var cleanDirectories = function () {
    [ "Target", "Plan", "Current" ].forEach(function (d) {
      try {
        agency.remove(d, true);
      }
      catch (err) {
        // dir may not exist. this is not a problem
      }
    });
  };

  var initValues = function () {
    [ "Target",
      "Plan",
      "Current",
      "Target/DBServers",
      "Target/Coordinators",
      "Target/Collections",
      "Plan/DBServers",
      "Plan/Coordinators",
      "Plan/Collections",
      "Current/ServersRegistered",
      "Current/DBServers",
      "Current/Coordinators",
      "Current/Collections",
      "Current/ShardsCopied"
    ].forEach(function (d) {
      try {
        agency.createDirectory(d);
      }
      catch (err) {
      }
    });
  };

  return {
    setUp : function () {
      assertTrue(agency.setPrefix("UnitTestsAgency"));
      assertEqual("UnitTestsAgency", agency.prefix(true));

      cleanDirectories();
      initValues();
    },

    tearDown : function () {
      cleanDirectories();

      assertTrue(agency.setPrefix(oldPrefix));
      ss.setId(oldId);
      assertEqual(oldPrefix, agency.prefix(true));
      ss.setRole(oldRole);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test id
////////////////////////////////////////////////////////////////////////////////

    testId : function () {
      ss.setId("myself");
      assertEqual("myself", ss.id());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test address
////////////////////////////////////////////////////////////////////////////////

    testAddress : function () {
      assertTrue(agency.set("Target/MapIDToEndpoint/myself", "tcp://127.0.0.1:8529"));
      assertTrue(agency.set("Plan/Coordinators/myself", "none"));
      assertTrue(agency.set("Plan/DBServers/myself", "other"));
      ss.setId("myself");
      ss.flush();

      assertEqual("tcp://127.0.0.1:8529", ss.address());

      assertTrue(agency.set("Target/MapIDToEndpoint/myself", "tcp://127.0.0.1:8530"));
      ss.flush();

      assertEqual("tcp://127.0.0.1:8530", ss.address());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCluster
////////////////////////////////////////////////////////////////////////////////

    testIsCluster : function () {
      assertTrue(cluster.isCluster());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinator
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorTrue : function () {
      assertTrue(agency.set("Plan/Coordinators/myself", "none"));
      ss.setId("myself");
      ss.flush();

      assertTrue(cluster.isCoordinator());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinator
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorFalse : function () {
      assertTrue(agency.set("Plan/Coordinators/DBServers/myself", "other"));
      ss.setId("myself");
      ss.flush();

      assertFalse(cluster.isCoordinator());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test role
////////////////////////////////////////////////////////////////////////////////

    testRoleCoordinator : function () {
      assertTrue(agency.set("Plan/Coordinators/myself", "none"));
      ss.setId("myself");
      ss.flush();

      assertTrue(cluster.role() !== undefined);
      assertTrue(cluster.role() === "COORDINATOR");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test role
////////////////////////////////////////////////////////////////////////////////

    testRoleDBServer : function () {
      assertTrue(agency.set("Plan/DBServers/myself", "other"));
      ss.setId("myself");
      ss.flush();

      assertTrue(cluster.role() !== undefined);
      assertTrue(cluster.role() === "PRIMARY");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test status
////////////////////////////////////////////////////////////////////////////////

    testStatus : function () {
      assertTrue(cluster.status() !== undefined);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinatorRequest
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorRequest : function () {
      assertFalse(cluster.isCoordinatorRequest(null));
      assertFalse(cluster.isCoordinatorRequest(undefined));
      assertFalse(cluster.isCoordinatorRequest({ }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { } }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { test: "" } }));
      assertTrue(cluster.isCoordinatorRequest({ headers: { "x-arango-coordinator": "abc" } }));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test doesDatabaseExist
////////////////////////////////////////////////////////////////////////////////

    testDoesDatabaseExist : function () {
      var database = {
        name: "test"
      };

      assertTrue(agency.set("Plan/Databases/" + database.name, database));
      assertTrue(agency.set("Current/DBServers/Foo", "Bar"));
      assertTrue(agency.set("Current/DBServers/Barz", "Bat"));
      assertTrue(agency.set("Current/Databases/test/Foo", database));
      assertTrue(agency.set("Current/Databases/test/Barz", database));

      assertTrue(ci.doesDatabaseExist("test"));

      assertFalse(ci.doesDatabaseExist("UnitTestsAgencyNonExisting"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test doesDatabaseExist
////////////////////////////////////////////////////////////////////////////////

    testDoesDatabaseExistNotReady : function () {
      var database = {
        name: "test"
      };

      assertTrue(agency.set("Plan/Databases/" + database.name, database));
      assertTrue(agency.set("Current/DBServers/Foo", "Bar"));
      assertTrue(agency.set("Current/DBServers/Barz", "Bat"));
      assertTrue(agency.set("Current/Databases/test/Foo", database));

      assertFalse(ci.doesDatabaseExist("test"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getCollectionInfo
////////////////////////////////////////////////////////////////////////////////

    testGetCollectionInfo : function () {
      var collection = {
        id: "123",
        name: "mycollection",
        type: 2,
        status: 3, // LOADED
        shardKeys: [ "_key" ],
        shards: { "s1" : "myself", "s2" : "other" }
      };
      assertTrue(agency.set("Plan/Collections/test/" + collection.id, collection));

      var data = ci.getCollectionInfo("test", collection.id);

      assertEqual(collection.id, data.id);
      assertEqual(collection.name, data.name);
      assertEqual(collection.type, data.type);
      assertEqual(collection.status, data.status);
      assertEqual(collection.shardKeys, data.shardKeys);
      assertEqual(collection.shards, data.shards);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getCollectionInfo
////////////////////////////////////////////////////////////////////////////////

    testGetCollectionInfo2 : function () {
      var collection = {
        id: "12345868390663",
        name: "mycollection_test",
        type: 3,
        status: 2, // LOADED
        shardKeys: [ "_key", "a", "bc" ],
        shards: { "s1" : "myself", "s2" : "other", "s3" : "foo", "s4" : "bar" }
      };

      assertTrue(agency.set("Plan/Collections/test/" + collection.id, collection));

      ci.flush();

      var data = ci.getCollectionInfo("test", collection.id);

      assertEqual(collection.id, data.id);
      assertEqual(collection.name, data.name);
      assertEqual(collection.type, data.type);
      assertEqual(collection.status, data.status);
      assertEqual(collection.shardKeys, data.shardKeys);
      assertEqual(collection.shards, data.shards);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getResponsibleServer
////////////////////////////////////////////////////////////////////////////////

    testGetResponsibleServer : function () {
      var collection = {
        id: "12345868390663",
        name: "mycollection_test",
        type: 3,
        status: 2, // LOADED
        shardKeys: [ "_key", "a", "bc" ],
        shards: { "s1" : "myself" },
        error: false,
        errorNum: 0,
        DBServer: "myself"
      };

      assertTrue(agency.set("Current/Collections/test/" + collection.id +
                            "/s1", collection));
      ci.flush();

      assertEqual("myself", ci.getResponsibleServer("s1"));
      assertEqual("", ci.getResponsibleServer("s9999"));

      collection.shards = { s1: "other", s2: "myself" };
      collection.DBServer = "myself";
      assertTrue(agency.set("Current/Collections/test/" + collection.id +
                            "/s2", collection));
      collection.DBServer = "other";
      assertTrue(agency.set("Current/Collections/test/" + collection.id +
                            "/s1", collection));
      ci.flush();

      assertEqual("other", ci.getResponsibleServer("s1"));
      assertEqual("myself", ci.getResponsibleServer("s2"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test getServerEndpoint
////////////////////////////////////////////////////////////////////////////////

    testGetServerEndpoint : function () {
      assertTrue(agency.set("Current/ServersRegistered/myself", {endpoint:"tcp://127.0.0.1:8529"}));
      ci.flush();

      assertEqual("tcp://127.0.0.1:8529", ci.getServerEndpoint("myself"));

      assertTrue(agency.set("Current/ServersRegistered/myself", {endpoint:"tcp://127.0.0.1:8530"}));
      ci.flush();

      assertEqual("tcp://127.0.0.1:8530", ci.getServerEndpoint("myself"));

      assertTrue(agency.remove("Current/ServersRegistered/myself"));
      assertTrue(agency.set("Current/ServersRegistered/other", {endpoint:"tcp://127.0.0.1:8529"}));
      ci.flush();

      assertEqual("", ci.getServerEndpoint("myself"));
      assertEqual("tcp://127.0.0.1:8529", ci.getServerEndpoint("other"));
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test uniqid
////////////////////////////////////////////////////////////////////////////////

    testUniqid : function () {
      var last = "0";

      for (var i = 0; i < 1005; ++i) {
        var id = ci.uniqid();
        assertEqual(-1, compareStringIds(last, id));
        last = id;
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test uniqid
////////////////////////////////////////////////////////////////////////////////

    testUniqidRange : function () {
      var last = "0";

      for (var i = 0; i < 100; ++i) {
        var id = ci.uniqid(10);
        assertEqual(-1, compareStringIds(last, id));
        last = id;
      }
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: cluster disabled
////////////////////////////////////////////////////////////////////////////////

function ClusterDisabledSuite () {
  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCluster
////////////////////////////////////////////////////////////////////////////////

    testIsCluster : function () {
      assertFalse(cluster.isCluster());
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test role
////////////////////////////////////////////////////////////////////////////////

    testRole : function () {
      assertTrue(cluster.role() === undefined);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test status
////////////////////////////////////////////////////////////////////////////////

    testStatus : function () {
      assertTrue(cluster.status() === undefined);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test isCoordinatorRequest
////////////////////////////////////////////////////////////////////////////////

    testIsCoordinatorRequest : function () {
      assertFalse(cluster.isCoordinatorRequest(null));
      assertFalse(cluster.isCoordinatorRequest(undefined));
      assertFalse(cluster.isCoordinatorRequest({ }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { } }));
      assertFalse(cluster.isCoordinatorRequest({ headers: { test: "" } }));
      assertTrue(cluster.isCoordinatorRequest({ headers: { "x-arango-coordinator": "abc" } }));
    }
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

if (cluster.isCluster()) {
  jsunity.run(ClusterEnabledSuite);
}
else {
  jsunity.run(ClusterDisabledSuite);
}

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<|endoftext|>


<commit_before>var QuestionPage = (function QuestionPage() {
  var publicAPI = {
    getQuestion: getQuestion
  };

  var $questionBox;
  var $questionBody;
  var $answer;
  var $answerTemplate;
  var $answerList;
  var $selectedAnswer;
  var $submitButton;
  var $homeButton;
  var questions;
  var currentQuestion;
  var questionText;

  return publicAPI;

  function getQuestion() {
    $homeButtonBox = $('#home-button-box');
    $homeButton = $('#just-the-home-button');
    $questionBody = $('#question-body');
    $answer = $('#answer');
    $answerList = $('#answer-list');
    $selectedAnswer = $('#selected-answer');
    $submitButton = $('#submit-answer');
    $questionAnswers = $("#question-box").show();
    $answerTemplate = $answer.clone();

    $homeButtonBox.show();
    $answer.remove();

    $homeButton.click(App.showHomePage);

    $answerList.click(function (element) {
      $selectedAnswer
        .text('Your Answer: ' +
          element.toElement.textContent
            .charAt(0)
            .toUpperCase()
        );

      $submitButton.prop('disabled', false);
    });

    $submitButton.click(function (element) {
      answerQuestion($selectedAnswer.text().slice(-1));
    });

    ServerAPI.getQuestion(user, function questionRetrieved(err, unanswered) {
      if (err) {
        console.error('error retrieving question', err);
      } else {
        if (unanswered.hasOwnProperty('question_text')) {

          //case where 'unanswered' is just a single question object
          questions = [unanswered];
        } else {

          //case where we get multiple questions in an array
          questions = unanswered;
        }

        buildQuestion();
      }
    });
  } //end function getQuestion

  function buildQuestion () {
    $submitButton.prop('disabled', true);
    $selectedAnswer.text('Your Answer: ');
    $answerList.empty();

    if (questions.length) {
      currentQuestion = questions.shift();
      questionText = currentQuestion.question_text.split('^');
      $questionBody.text(questionText[0]);

      for (var i = 1; i < questionText.length; i++) {
        $answerList
          .append(
            $answerTemplate
            .clone()
            .text(questionText[i])
          );
      }

    } else {

      //there are no questions left
      $questionBody.text('You\'ve answered every question in the system! Please come back later');
    }
  }

  function answerQuestion(answer) {
    var data = {
      identity: user,
      questionId: currentQuestion.id,
      user_answer: answer.toLowerCase()
    };

    ServerAPI.submitAnswer(data, function answerSubmitted(err, success) {
      if (err) {
        console.error('error answering question', err);
      } else {
        buildQuestion();
      }
    });
  }

})();
<commit_msg>fixing error<commit_after>var QuestionPage = (function QuestionPage() {
  var publicAPI = {
    getQuestion: getQuestion
  };

  var $questionBox;
  var $questionBody;
  var $answer;
  var $answerTemplate;
  var $answerList;
  var $selectedAnswer;
  var $submitButton;
  var $homeButton;
  var questions;
  var currentQuestion;
  var questionText;

  return publicAPI;

  function getQuestion() {
    $homeButtonBox = $('#home-button-box');
    $homeButton = $('#just-the-home-button');
    $questionBody = $('#question-body');
    $answer = $('#answer');
    $answerList = $('#answer-list');
    $selectedAnswer = $('#selected-answer');
    $submitButton = $('#submit-answer');
    $questionAnswers = $("#question-box").show();
    $answerTemplate = $answer.clone();

    $homeButtonBox.show();
    $answer.remove();

    $homeButton.click(App.showHomePage);

    $answerList.click(function (element) {
      $selectedAnswer
        .text('Your Answer: ' +
          element.toElement.textContent
            .charAt(0)
            .toUpperCase()
        );

      $submitButton.prop('disabled', false);
    });

    $submitButton.click(function (element) {
      answerQuestion($selectedAnswer.text().slice(-1));
    });

    ServerAPI.getQuestion(user, function questionRetrieved(err, unanswered) {
      if (err) {
        console.error('error retrieving question', err);
      } else {
        if (unanswered.hasOwnProperty('question_text')) {

          //case where 'unanswered' is just a single question object
          questions = [];
          questions.push(unanswered);
        } else {

          //case where we get multiple questions in an array
          questions = unanswered;
        }

        buildQuestion();
      }
    });
  } //end function getQuestion

  function buildQuestion () {
    $submitButton.prop('disabled', true);
    $selectedAnswer.text('Your Answer: ');
    $answerList.empty();

    if (questions.length) {
      currentQuestion = questions.shift();
      questionText = currentQuestion.question_text.split('^');
      $questionBody.text(questionText[0]);

      for (var i = 1; i < questionText.length; i++) {
        $answerList
          .append(
            $answerTemplate
            .clone()
            .text(questionText[i])
          );
      }

    } else {

      //there are no questions left
      $questionBody.text('You\'ve answered every question in the system! Please come back later');
    }
  }

  function answerQuestion(answer) {
    var data = {
      identity: user,
      questionId: currentQuestion.id,
      user_answer: answer.toLowerCase()
    };

    ServerAPI.submitAnswer(data, function answerSubmitted(err, success) {
      if (err) {
        console.error('error answering question', err);
      } else {
        buildQuestion();
      }
    });
  }

})();
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  getInitialState: function() {
    return {
      barPressure: '300',
      minutes: 0,
    };
  },

  render: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];
    var selectionString = pressure.bar + ' bar which gives ' + pressure.minutes + ' minutes.';
    return (
      <View>
        <Text></Text>
        <Text>Enter your tank BA</Text>
        <PickerIOS
          selectedValue={this.state.barPressure}
          onValueChange={(barPressure) => this.setState({barPressure, minutes: 0})}>
          {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
            <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
            )
          )}
        </PickerIOS>
        <Text>You selected: {selectionString}</Text>
      </View>
    );
  },
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);
<commit_msg>updated text regarding cylinder pressure<commit_after>'use strict';

var React = require('react-native');
var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  getInitialState: function() {
    return {
      barPressure: '300',
      minutes: 0,
    };
  },

  render: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];
    var selectionString = pressure.bar + ' bar which gives ' + pressure.minutes + ' minutes.';
    return (
      <View>
        <Text></Text>
        <Text>Enter Cylinder Pressure: </Text>
        <PickerIOS
          selectedValue={this.state.barPressure}
          onValueChange={(barPressure) => this.setState({barPressure, minutes: 0})}>
          {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
            <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
            )
          )}
        </PickerIOS>
        <Text>You selected: {selectionString}</Text>
      </View>
    );
  },
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);
<|endoftext|>


<commit_before>!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.Class=e()}(this,function(){"use strict";var n="constructor",i="extend";function t(){}return t[i]=function(t){var e=Object.create(this.prototype);function o(){e[n].apply(this,arguments)}return t.call(e,this.prototype),o.prototype=e,o[i]=this[i],o},t});<commit_msg>Rebuilt<commit_after>!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.Class=e()}(this,function(){"use strict";var n="extend";function t(){}return t[n]=function(t){var e=Object.create(this.prototype);function o(){e.constructor.apply(this,arguments)}return t.call(e,this.prototype),o.prototype=e,o[n]=this[n],o},t});<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');
const argv = require('minimist')(process.argv.slice(2)); // eslint-disable-line import/no-extraneous-dependencies
const ruleBoilerplateGenerator = require('./boilerplate/rule');
const testBoilerplateGenerator = require('./boilerplate/test');
const docBoilerplateGenerator = require('./boilerplate/doc');
const exec = require('child_process').exec;

const ruleName = argv._[0];
const author = argv.author || '$AUTHOR';
const description = argv.description || '$DESCRIPTION';

const rulePath = path.resolve(`src/rules/${ruleName}.js`);
const testPath = path.resolve(`__tests__/src/rules/${ruleName}-test.js`);
const docsPath = path.resolve(`docs/rules/${ruleName}.md`);

const jscodeshiftJSON = require('jscodeshift/package.json');
const jscodeshiftMain = jscodeshiftJSON.main;
const jscodeshiftPath = require.resolve('jscodeshift');
const jscodeshiftRoot = jscodeshiftPath.slice(
  0,
  jscodeshiftPath.indexOf(jscodeshiftMain)
);

// Validate
if (!ruleName) {
  throw new Error('Rule name is required');
} else if (fs.existsSync(rulePath)) {
  throw new Error('Rule already exists!');
}

// Generate file boilerplate
const ruleBoilerplate = ruleBoilerplateGenerator(author, description);
const testBoilerplate = testBoilerplateGenerator(ruleName, author, description);
const docBoilerplate = docBoilerplateGenerator(ruleName);

// Create new files
fs.writeFileSync(rulePath, ruleBoilerplate);
fs.writeFileSync(testPath, testBoilerplate);
fs.writeFileSync(docsPath, docBoilerplate);

// Add the rule to the index
exec([
  path.join(
    jscodeshiftRoot,
    jscodeshiftJSON.bin.jscodeshift
  ),
  './src/index.js',
  '-t ./scripts/addRuleToIndex.js',
  '--extensions js',
  '--parser flow',
  `--ruleName=${ruleName}`,
  `--rulePath=${rulePath}`,
  ].join(' '),
  (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`);
      return;
    }
  }
);
<commit_msg>Add env statement to create-rule script<commit_after>#!/usr/bin/env node --harmony
const path = require('path');
const fs = require('fs');
const argv = require('minimist')(process.argv.slice(2)); // eslint-disable-line import/no-extraneous-dependencies
const ruleBoilerplateGenerator = require('./boilerplate/rule');
const testBoilerplateGenerator = require('./boilerplate/test');
const docBoilerplateGenerator = require('./boilerplate/doc');
const exec = require('child_process').exec;

const ruleName = argv._[0];
const author = argv.author || '$AUTHOR';
const description = argv.description || '$DESCRIPTION';

const rulePath = path.resolve(`src/rules/${ruleName}.js`);
const testPath = path.resolve(`__tests__/src/rules/${ruleName}-test.js`);
const docsPath = path.resolve(`docs/rules/${ruleName}.md`);

const jscodeshiftJSON = require('jscodeshift/package.json');
const jscodeshiftMain = jscodeshiftJSON.main;
const jscodeshiftPath = require.resolve('jscodeshift');
const jscodeshiftRoot = jscodeshiftPath.slice(
  0,
  jscodeshiftPath.indexOf(jscodeshiftMain)
);

// Validate
if (!ruleName) {
  throw new Error('Rule name is required');
} else if (fs.existsSync(rulePath)) {
  throw new Error('Rule already exists!');
}

// Generate file boilerplate
const ruleBoilerplate = ruleBoilerplateGenerator(author, description);
const testBoilerplate = testBoilerplateGenerator(ruleName, author, description);
const docBoilerplate = docBoilerplateGenerator(ruleName);

// Create new files
fs.writeFileSync(rulePath, ruleBoilerplate);
fs.writeFileSync(testPath, testBoilerplate);
fs.writeFileSync(docsPath, docBoilerplate);

// Add the rule to the index
exec([
  path.join(
    jscodeshiftRoot,
    jscodeshiftJSON.bin.jscodeshift
  ),
  './src/index.js',
  '-t ./scripts/addRuleToIndex.js',
  '--extensions js',
  '--parser flow',
  `--ruleName=${ruleName}`,
  `--rulePath=${rulePath}`,
  ].join(' '),
  (error, stdout, stderr) => {
    if (error) {
      console.error(`exec error: ${error}`);
      return;
    }
  }
);
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './react-src/app.js',
    devtool: 'source-map',
    output: {
        path: path.join(__dirname, 'www/js'),
        filename: 'react-app.js'
    },

    module: {
        rules: [{
            test: /.js?$/,

            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env', 'react'],
                    plugins: ["transform-class-properties"]
                }
            }
        }]
    },
    plugins: [

    ],
    target: 'electron-main'

};<commit_msg>Single to double quotes.<commit_after>var path = require("path");

module.exports = {
    entry: "./react-src/App.js",
    devtool: "source-map",
    output: {
        path: path.join(__dirname, "www/js"),
        filename: "react-app.js"
    },

    module: {
        rules: [{
            test: /.js?$/,

            exclude: /node_modules/,
            use: {
                loader: "babel-loader",
                options: {
                    presets: ["env", "react"],
                    plugins: ["transform-class-properties"]
                }
            }
        }]
    },
    plugins: [

    ],
    target: "electron-main"

};<|endoftext|>


<commit_before>/**
@license jQuery Toggles v2.0.4
Copyright 2013 Simon Tabor - MIT License
https://github.com/simontabor/jquery-toggles / http://simontabor.com/labs/toggles
*/
$.fn['toggles'] = function(options) {
  options = options || {};

  // extend default opts with the users options
  var opts = $.extend({
    'drag': true, // can the toggle be dragged
    'click': true, // can it be clicked to toggle
    'text': {
      'on': 'ON', // text for the ON position
      'off': 'OFF' // and off
    },
    'on': false, // is the toggle ON on init
    'animate': 250, // animation time
    'transition': 'ease-in-out', // animation transition,
    'checkbox': null, // the checkbox to toggle (for use in forms)
    'clicker': null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
    'width': 50, // width used if not set in css
    'height': 20, // height if not set in css
    'type': 'compact' // defaults to a compact toggle, other option is 'select' where both options are shown at once
  },options);

  var selectType = (opts['type'] == 'select');

  // ensure these are jquery elements
  opts['checkbox'] = $(opts['checkbox']); // doesnt matter for checkbox

  if (opts['clicker']) opts['clicker'] = $(opts['clicker']); // leave as null if not set

  // use native transitions if possible
  var transition = 'margin-left '+opts['animate']+'ms '+opts['transition'];
  var transitions = {
    '-webkit-transition': transition,
    '-moz-transition': transition,
    'transition': transition
  };

  // for resetting transitions to none
  var notransitions = {
    '-webkit-transition': '',
    '-moz-transition': '',
    'transition': ''
  };

  // this is the actual toggle function which does the toggling
  var doToggle = function(slide, width, height, state) {
    var active = slide.toggleClass('active').hasClass('active');

    if (state === active) return;

    var inner = slide.find('.toggle-inner').css(transitions);

    slide.find('.toggle-off').toggleClass('active');
    slide.find('.toggle-on').toggleClass('active');

    // toggle the checkbox, if there is one
    opts['checkbox'].prop('checked',active);

    if (selectType) return;

    var margin = active ? 0 : -width + height;

    // move the toggle!
    inner.css('margin-left',margin);

    // ensure the toggle is left in the correct state after animation
    setTimeout(function() {
      inner.css(notransitions);
      inner.css('margin-left',margin);
    },opts['animate']);

  };

  // start setting up the toggle(s)
  return this.each(function() {
    var toggle = $(this);

    var height = toggle.height();
    var width = toggle.width();

    // if the element doesnt have an explicit height/width in css, set them
    if (!height || !width) {
      toggle.height(height = opts.height);
      toggle.width(width = opts.width);
    }

    var div = '
'); // wrapper inside toggle
    var inner = $(div+'inner">'); // inside slide, this bit moves
    var on = $(div+'on">'); // the on div
    var off = $(div+'off">'); // off div
    var blob = $(div+'blob">'); // the grip toggle blob

    var halfheight = height/2;
    var onoffwidth = width - halfheight;

    // set up the CSS for the individual elements
    on
      .css({
        height: height,
        width: onoffwidth,
        textAlign: 'center',
        textIndent: selectType ? '' : -halfheight,
        lineHeight: height+'px'
      })
      .html(opts['text']['on']);

    off
      .css({
        height: height,
        width: onoffwidth,
        marginLeft: selectType ? '' : -halfheight,
        textAlign: 'center',
        textIndent: selectType ? '' : halfheight,
        lineHeight: height+'px'
      })
      .html(opts['text']['off'])
      .addClass('active');

    blob.css({
      height: height,
      width: height,
      marginLeft: -halfheight
    });

    inner.css({
      width: width * 2 - height,
      marginLeft: selectType ? 0 : -width + height
    });

    if (selectType) {
      slide.addClass('toggle-select');
      toggle.css('width', onoffwidth*2);
      blob.hide();
    }

    // construct the toggle
    toggle.html(slide.html(inner.append(on,blob,off)));

    // when toggle is fired, toggle the toggle
    slide.on('toggle', function(e,active) {

      // stop bubbling
      if (e) e.stopPropagation();

      doToggle(slide,width,height);
      toggle.trigger('toggle',!active);
    });

    // setup events for toggling on or off
    toggle.on('toggleOn', function() {
      doToggle(slide, width, height, false);
    });
    toggle.on('toggleOff', function() {
      doToggle(slide, width, height, true);
    });

    if (opts['on']) {

      // toggle immediately to turn the toggle on
      doToggle(slide,width,height);
    }

    // if click is enabled and toggle isn't within the clicker element (stops double binding)
    if (opts['click'] && (!opts['clicker'] || !opts['clicker'].has(toggle).length)) {

      // bind the click, ensuring its not the blob being clicked on
      toggle.on('click',function(e) {
        if (e.target !=  blob[0] || !opts['drag']) {
          slide.trigger('toggle', slide.hasClass('active'));
        }
      });
    }

    // setup the clicker element
    if (opts['clicker']) {
      opts['clicker'].on('click',function(e) {
        if (e.target !=  blob[0] || !opts['drag']) {
          slide.trigger('toggle', slide.hasClass('active'));
        }
      });
    }

    // we're done with all the non dragging stuff
    if (!opts['drag'] || selectType) return;

    // time to begin the dragging parts/blob clicks
    var diff;
    var slideLimit = (width - height) / 4;

    // fired on mouseup and mouseleave events
    var upLeave = function(e) {
      toggle.off('mousemove');
      slide.off('mouseleave');
      blob.off('mouseup');

      var active = slide.hasClass('active');

      if (!diff && opts.click && e.type !== 'mouseleave') {

        // theres no diff so nothing has moved. only toggle if its a mouseup
        slide.trigger('toggle', active);
        return;
      }

      if (active) {

        // if the movement enough to toggle?
        if (diff < -slideLimit) {
          slide.trigger('toggle',active);
        } else {

          // go back
          inner.animate({
            marginLeft: 0
          },opts.animate/2);
        }
      } else {

        // inactive
        if (diff > slideLimit) {
          slide.trigger('toggle',active);
        } else {

          // go back again
          inner.animate({
            marginLeft: -width + height
          },opts.animate/2);
        }
      }

    };

    var wh = -width + height;

    blob.on('mousedown', function(e) {

      // reset diff
      diff = 0;

      blob.off('mouseup');
      slide.off('mouseleave');
      var cursor = e.pageX;

      toggle.on('mousemove', blob, function(e) {
        diff = e.pageX - cursor;
        var marginLeft;
        if (slide.hasClass('active')) {

          marginLeft = diff;

          // keep it within the limits
          if (diff > 0) marginLeft = 0;
          if (diff < wh) marginLeft = wh;
        } else {

          marginLeft = diff + wh;

          if (diff < 0) marginLeft = wh;
          if (diff > -wh) marginLeft = 0;

        }

        inner.css('margin-left',marginLeft);
      });

      blob.on('mouseup', upLeave);
      slide.on('mouseleave', upLeave);
    });

  });

};
<commit_msg>Add touch events for devices that support it.<commit_after>/**
@license jQuery Toggles v2.0.4
Copyright 2013 Simon Tabor - MIT License
https://github.com/simontabor/jquery-toggles / http://simontabor.com/labs/toggles
*/
$.fn['toggles'] = function(options) {
  options = options || {};

  // extend default opts with the users options
  var opts = $.extend({
    'drag': true, // can the toggle be dragged
    'click': true, // can it be clicked to toggle
    'text': {
      'on': 'ON', // text for the ON position
      'off': 'OFF' // and off
    },
    'on': false, // is the toggle ON on init
    'animate': 250, // animation time
    'transition': 'ease-in-out', // animation transition,
    'checkbox': null, // the checkbox to toggle (for use in forms)
    'clicker': null, // element that can be clicked on to toggle. removes binding from the toggle itself (use nesting)
    'width': 50, // width used if not set in css
    'height': 20, // height if not set in css
    'type': 'compact' // defaults to a compact toggle, other option is 'select' where both options are shown at once
  },options);

  var selectType = (opts['type'] == 'select');

  // ensure these are jquery elements
  opts['checkbox'] = $(opts['checkbox']); // doesnt matter for checkbox

  if (opts['clicker']) opts['clicker'] = $(opts['clicker']); // leave as null if not set

  // use native transitions if possible
  var transition = 'margin-left '+opts['animate']+'ms '+opts['transition'];
  var transitions = {
    '-webkit-transition': transition,
    '-moz-transition': transition,
    'transition': transition
  };

  // for resetting transitions to none
  var notransitions = {
    '-webkit-transition': '',
    '-moz-transition': '',
    'transition': ''
  };

  // this is the actual toggle function which does the toggling
  var doToggle = function(slide, width, height, state) {
    var active = slide.toggleClass('active').hasClass('active');

    if (state === active) return;

    var inner = slide.find('.toggle-inner').css(transitions);

    slide.find('.toggle-off').toggleClass('active');
    slide.find('.toggle-on').toggleClass('active');

    // toggle the checkbox, if there is one
    opts['checkbox'].prop('checked',active);

    if (selectType) return;

    var margin = active ? 0 : -width + height;

    // move the toggle!
    inner.css('margin-left',margin);

    // ensure the toggle is left in the correct state after animation
    setTimeout(function() {
      inner.css(notransitions);
      inner.css('margin-left',margin);
    },opts['animate']);

  };

  // start setting up the toggle(s)
  return this.each(function() {
    var toggle = $(this);

    var height = toggle.height();
    var width = toggle.width();

    // if the element doesnt have an explicit height/width in css, set them
    if (!height || !width) {
      toggle.height(height = opts.height);
      toggle.width(width = opts.width);
    }

    var div = '
'); // wrapper inside toggle
    var inner = $(div+'inner">'); // inside slide, this bit moves
    var on = $(div+'on">'); // the on div
    var off = $(div+'off">'); // off div
    var blob = $(div+'blob">'); // the grip toggle blob

    var halfheight = height/2;
    var onoffwidth = width - halfheight;

    // set up the CSS for the individual elements
    on
      .css({
        height: height,
        width: onoffwidth,
        textAlign: 'center',
        textIndent: selectType ? '' : -halfheight,
        lineHeight: height+'px'
      })
      .html(opts['text']['on']);

    off
      .css({
        height: height,
        width: onoffwidth,
        marginLeft: selectType ? '' : -halfheight,
        textAlign: 'center',
        textIndent: selectType ? '' : halfheight,
        lineHeight: height+'px'
      })
      .html(opts['text']['off'])
      .addClass('active');

    blob.css({
      height: height,
      width: height,
      marginLeft: -halfheight
    });

    inner.css({
      width: width * 2 - height,
      marginLeft: selectType ? 0 : -width + height
    });

    if (selectType) {
      slide.addClass('toggle-select');
      toggle.css('width', onoffwidth*2);
      blob.hide();
    }

    // construct the toggle
    toggle.html(slide.html(inner.append(on,blob,off)));

    // when toggle is fired, toggle the toggle
    slide.on('toggle', function(e,active) {

      // stop bubbling
      if (e) e.stopPropagation();

      doToggle(slide,width,height);
      toggle.trigger('toggle',!active);
    });

    // setup events for toggling on or off
    toggle.on('toggleOn', function() {
      doToggle(slide, width, height, false);
    });
    toggle.on('toggleOff', function() {
      doToggle(slide, width, height, true);
    });

    if (opts['on']) {

      // toggle immediately to turn the toggle on
      doToggle(slide,width,height);
    }

    // if click is enabled and toggle isn't within the clicker element (stops double binding)
    if (opts['click'] && (!opts['clicker'] || !opts['clicker'].has(toggle).length)) {

      // bind the click, ensuring its not the blob being clicked on
      toggle.on('click',function(e) {
        if (e.target !=  blob[0] || !opts['drag']) {
          slide.trigger('toggle', slide.hasClass('active'));
        }
      });
    }

    // setup the clicker element
    if (opts['clicker']) {
      opts['clicker'].on('click',function(e) {
        if (e.target !=  blob[0] || !opts['drag']) {
          slide.trigger('toggle', slide.hasClass('active'));
        }
      });
    }

    // we're done with all the non dragging stuff
    if (!opts['drag'] || selectType) return;

    // time to begin the dragging parts/blob clicks
    var diff;
    var slideLimit = (width - height) / 4;

    // fired on mouseup and mouseleave events
    var upLeave = function(e) {
      toggle.off('mousemove');
      slide.off('mouseleave');
      blob.off('mouseup touchend');

      var active = slide.hasClass('active');

      if (!diff && opts.click && e.type !== 'mouseleave') {

        // theres no diff so nothing has moved. only toggle if its a mouseup
        slide.trigger('toggle', active);
        return;
      }

      if (active) {

        // if the movement enough to toggle?
        if (diff < -slideLimit) {
          slide.trigger('toggle',active);
        } else {

          // go back
          inner.animate({
            marginLeft: 0
          },opts.animate/2);
        }
      } else {

        // inactive
        if (diff > slideLimit) {
          slide.trigger('toggle',active);
        } else {

          // go back again
          inner.animate({
            marginLeft: -width + height
          },opts.animate/2);
        }
      }

    };

    var wh = -width + height;

    blob.on('mousedown touchstart', function(e) {

      // reset diff
      diff = 0;

      blob.off('mouseup touchend');
      slide.off('mouseleave');
      var cursor = e.pageX;

      toggle.on('mousemove touchmove', blob, function(e) {
        diff = e.pageX - cursor;
        var marginLeft;
        if (slide.hasClass('active')) {

          marginLeft = diff;

          // keep it within the limits
          if (diff > 0) marginLeft = 0;
          if (diff < wh) marginLeft = wh;
        } else {

          marginLeft = diff + wh;

          if (diff < 0) marginLeft = wh;
          if (diff > -wh) marginLeft = 0;

        }

        inner.css('margin-left',marginLeft);
      });

      blob.on('mouseup touchend', upLeave);
      slide.on('mouseleave', upLeave);
    });

  });

};
<|endoftext|>


<commit_before>var define = define || function() {
};

define(function() {
   return TP_Server;
});

function TP_Server() {
   var self = this;

   // private vars
   var protocol = {
      request : {},
      response : {},
      struct : {},
      message : {},
      consts : {},
      reverseMap : {}
   };
   var requestCounter = 0;
   var requestHandlers = [];
   var messageHandlers = [];
   var openHandlers = [];
   var closeHandlers = [];
   var socket;
   var simulator = null;

   // public interface
   self.commsLog = false;
   self.register = register;
   self.registerConst = registerConst;
   self.addMessageHandler = addMessageHandler;
   self.send = send;
   self.sendRequest = sendRequest;
   self.connect = connect;
   self.disconnect = disconnect;
   self.nameOf = nameOf;
   self.consts = protocol.consts;
   self.connected = false;
   self.setSimulator = function(s) {
      simulator = s;
   };

   for (var i = 0; i < arguments.length; i++) {
      new arguments[i](self);
   }

   function register(type, contractName, structName, contractId, structId) {
      var map = protocol[type];
      var val = {
         contractId : contractId,
         structId : structId
      };
      map[contractName + "." + structName] = val;
      if (map[structName]) {
         map[structName] = 0;
      } else {
         map[structName] = val;
      }
      protocol.reverseMap["" + contractId + "." + structId] = contractName + "." + structName;
   }

   function registerConst(contractName, structName, constName, constValue) {
      var map = protocol["consts"];
      var o;
      if (structName != null && structName != "null") {
         o = map[contractName + "." + structName] || {};
         map[contractName + "." + structName] = o;
      } else {
         o = map[contractName] || {};
         map[contractName] = o;
      }
      o[constName] = constValue;
   }

   function consts(name) {
      return protocol["consts"][name];
   }

   function nameOf(arg1, arg2) {
      // call with either a single arg = object with _contractId and _structId
      // or with explicit contractId, structId
      var key;
      if (typeof arg2 !== 'undefined') {
         key = "" + arg1 + "." + arg2;
      } else {
         key = "" + arg1._contractId + "." + arg1._structId;
      }
      return protocol.reverseMap[key];
   }

   function addMessageHandler(message, handler) {
      var val = protocol.message[message];
      if (!val) {
         console.log("unknown message: " + message);
         return;
      }
      if (val === 0) {
         console.log("ambiguous message: " + message);
         return;
      }
      messageHandlers[val.contractId + "." + val.structId] = handler;
   }

   function send(request, args, toId) {
      var val = protocol.request[request];
      if (!val) {
         console.log("unknown request: " + request);
         return;
      }
      if (val === 0) {
         console.log("ambiguous request: " + request);
         return;
      }
      return sendRequest(val.contractId, val.structId, args, toId);
   }

   function sendRequest(contractId, structId, args, toId) {
      toId = typeof toId !== 'undefined' ? toId : 0;
      var requestId = requestCounter++;
      args._requestId = requestId;
      args._contractId = contractId;
      args._structId = structId;
      args._toId = toId;
      if (self.commsLog)
         logRequest(args);

      if (simulator != null) {
         var resp = simulator.request(request, args, toId);
         var i;
         for (i = 0; i < resp.messages.length; i++) {
            var mess = resp.messages[i];
            handleMessage(mess);
         }
         return {
            handle : function(func) {
               requestHandlers[requestId] = func;
               handleResponse(resp.response);
            }
         }
      }

      if (socket && socket.readyState == WebSocket.OPEN) {
         socket.send(JSON.stringify(args, null, 3))
      }

      return {
         handle : function(func) {
            requestHandlers[requestId] = func;
         }
      }
   }

   function connect(server, port) {
      port = typeof port !== 'undefined' ? port : 9903;
      if (!window.WebSocket) {
         window.WebSocket = window.MozWebSocket;
      }
      if (!window.WebSocket) {
         return null;
      }
      if (simulator != null) {
         return {
            listen : function(onOpen, onClose) {
               onOpen();
            }
         }
      }
      socket = new WebSocket("ws://" + server + ":" + port + "/sockets");
      socket.onopen = onSocketOpen;
      socket.onmessage = onSocketMessage;
      socket.onclose = onSocketClose;
      socket.onerror = onSocketError;
      return {
         listen : function(onOpen, onClose) {
            openHandlers = [];
            closeHandlers = [];
            openHandlers.push(onOpen);
            closeHandlers.push(onClose);
         }
      }
   }

   function disconnect() {
      if (self.commsLog)
         console.log("Disconnecting...");
      socket.close();
   }

   function logResponse(result) {
      var str = "";
      if (result.isError()) {
         str = "ERROR " + result.errorCode;
      } else if (result._contractId == 1 && result._structId == 2) {
         str = "SUCCESS";
      } else {
         str = JSON.stringify(result);
      }
      console.log("[%d] <- %s%s", result._requestId, nameOf(result), JSON.stringify(result, dropUnderscored));
   }

   function logRequest(result) {
      console.log("[%d] => %s%s", result._requestId, nameOf(result), JSON.stringify(result, dropUnderscored));
   }

   function logMessage(result) {
      console.log("[M:%d] <- %s%s", result._topicId, nameOf(result), JSON.stringify(result, dropUnderscored));
   }

   function dropUnderscored(key, value) {
      if (typeof key == 'string' || key instanceof String) {
         if (key.indexOf("_") == 0)
            return undefined;
      }
      return value;
   }

   function handleResponse(result) {
      result.isError = function() {
         return result._contractId == 1 && result._structId == 1;
      };
      if (self.commsLog)
         logResponse(result);
      var func = requestHandlers[result._requestId];
      if (func) {
         func(result);
      }
   }

   function handleMessage(result) {
      if (self.commsLog)
         logMessage(result);
      var func = messageHandlers[result._contractId + "." + result._structId];
      if (func) {
         func(result);
      }
   }

   function sendKeepAliveCheck(millis) {
      if (self.connected && self.keepAlive == null) {
         self.keepAlive = setTimeout(function() {
            self.keepAlive = null;
            if (self.connected) {
               var d = new Date();
               if (d.getTime() - lastHeardFrom > 20000) {
                  disconnect();
               } else if (d.getTime() - lastHeardFrom > 5000) {
                  // TODO: mark as bad connection
                  send("KeepAlive", {});
               }
            }
         }, millis);
      }
   }

   // --- socket methods

   function onSocketOpen(event) {
      self.connected = true;
      if (self.commsLog)
         console.log("[socket] open")
      var i, array = openHandlers;
      for (i = 0; i < array.length; i++)
         array[i]();

      self.keepAlive = setInterval(function() {
         send("KeepAlive", {});
         var now = Date.now();
         if (now - lastHeardFrom > 20000) {
            disconnect();
         } else if (now - lastHeardFrom > 6000) {
            // TODO: mark as bad connection
         }
      }, 5000);

   }

   function onSocketClose(event) {
      self.connected = false;
      if (self.keepAlive != null) {
         clearInterval(self.keepAlive);
         self.keepAlive = null;
      }
      if (self.commsLog)
         console.log("[socket] closed")
      var i, array = closeHandlers;
      for (i = 0; i < array.length; i++)
         array[i]();
   }

   function onSocketMessage(event) {
      var result = null;
      if (event.data.indexOf("{") == 0) {
         result = JSON.parse(event.data);
      } else {
         // TODO figure out how to communicate errors
         result = parseInt(event.data);
      }
      if (result._requestId != null) {
         handleResponse(result);
      } else if (result._topicId != null) {
         handleMessage(result);
      }
      lastHeardFrom = Date.now();
   }

   function onSocketError(event) {
      if (self.commsLog)
         console.log("[socket] error");
   }

}
<commit_msg>KeepAlive fixes<commit_after>var define = define || function() {
};

define(function() {
   return TP_Server;
});

function TP_Server() {
   var self = this;

   // private vars
   var protocol = {
      request : {},
      response : {},
      struct : {},
      message : {},
      consts : {},
      reverseMap : {}
   };
   var requestCounter = 0;
   var requestHandlers = [];
   var messageHandlers = [];
   var openHandlers = [];
   var closeHandlers = [];
   var socket;
   var simulator = null;
   var lastHeardFrom = 0;

   // public interface
   self.commsLog = false;
   self.register = register;
   self.registerConst = registerConst;
   self.addMessageHandler = addMessageHandler;
   self.send = send;
   self.sendRequest = sendRequest;
   self.connect = connect;
   self.disconnect = disconnect;
   self.nameOf = nameOf;
   self.consts = protocol.consts;
   self.connected = false;
   self.setSimulator = function(s) {
      simulator = s;
   };

   for (var i = 0; i < arguments.length; i++) {
      new arguments[i](self);
   }

   function register(type, contractName, structName, contractId, structId) {
      var map = protocol[type];
      var val = {
         contractId : contractId,
         structId : structId
      };
      map[contractName + "." + structName] = val;
      if (map[structName]) {
         map[structName] = 0;
      } else {
         map[structName] = val;
      }
      protocol.reverseMap["" + contractId + "." + structId] = contractName + "." + structName;
   }

   function registerConst(contractName, structName, constName, constValue) {
      var map = protocol["consts"];
      var o;
      if (structName != null && structName != "null") {
         o = map[contractName + "." + structName] || {};
         map[contractName + "." + structName] = o;
      } else {
         o = map[contractName] || {};
         map[contractName] = o;
      }
      o[constName] = constValue;
   }

   function consts(name) {
      return protocol["consts"][name];
   }

   function nameOf(arg1, arg2) {
      // call with either a single arg = object with _contractId and _structId
      // or with explicit contractId, structId
      var key;
      if (typeof arg2 !== 'undefined') {
         key = "" + arg1 + "." + arg2;
      } else {
         key = "" + arg1._contractId + "." + arg1._structId;
      }
      return protocol.reverseMap[key];
   }

   function addMessageHandler(message, handler) {
      var val = protocol.message[message];
      if (!val) {
         console.log("unknown message: " + message);
         return;
      }
      if (val === 0) {
         console.log("ambiguous message: " + message);
         return;
      }
      messageHandlers[val.contractId + "." + val.structId] = handler;
   }

   function send(request, args, toId) {
      var val = protocol.request[request];
      if (!val) {
         console.log("unknown request: " + request);
         return;
      }
      if (val === 0) {
         console.log("ambiguous request: " + request);
         return;
      }
      return sendRequest(val.contractId, val.structId, args, toId);
   }

   function sendRequest(contractId, structId, args, toId) {
      toId = typeof toId !== 'undefined' ? toId : 0;
      var requestId = requestCounter++;
      args._requestId = requestId;
      args._contractId = contractId;
      args._structId = structId;
      args._toId = toId;
      if (self.commsLog)
         logRequest(args);

      if (simulator != null) {
         var resp = simulator.request(request, args, toId);
         var i;
         for (i = 0; i < resp.messages.length; i++) {
            var mess = resp.messages[i];
            handleMessage(mess);
         }
         return {
            handle : function(func) {
               requestHandlers[requestId] = func;
               handleResponse(resp.response);
            }
         }
      }

      if (socket && socket.readyState == WebSocket.OPEN) {
         socket.send(JSON.stringify(args, null, 3))
      }

      return {
         handle : function(func) {
            requestHandlers[requestId] = func;
         }
      }
   }

   function connect(server, port) {
      port = typeof port !== 'undefined' ? port : 9903;
      if (!window.WebSocket) {
         window.WebSocket = window.MozWebSocket;
      }
      if (!window.WebSocket) {
         return null;
      }
      if (simulator != null) {
         return {
            listen : function(onOpen, onClose) {
               onOpen();
            }
         }
      }
      socket = new WebSocket("ws://" + server + ":" + port + "/sockets");
      socket.onopen = onSocketOpen;
      socket.onmessage = onSocketMessage;
      socket.onclose = onSocketClose;
      socket.onerror = onSocketError;
      return {
         listen : function(onOpen, onClose) {
            openHandlers = [];
            closeHandlers = [];
            openHandlers.push(onOpen);
            closeHandlers.push(onClose);
         }
      }
   }

   function disconnect() {
      if (self.commsLog)
         console.log("Disconnecting...");
      socket.close();
   }

   function logResponse(result) {
      var str = "";
      if (result.isError()) {
         str = "ERROR " + result.errorCode;
      } else if (result._contractId == 1 && result._structId == 2) {
         str = "SUCCESS";
      } else {
         str = JSON.stringify(result);
      }
      console.log("[%d] <- %s%s", result._requestId, nameOf(result), JSON.stringify(result, dropUnderscored));
   }

   function logRequest(result) {
      console.log("[%d] => %s%s", result._requestId, nameOf(result), JSON.stringify(result, dropUnderscored));
   }

   function logMessage(result) {
      console.log("[M:%d] <- %s%s", result._topicId, nameOf(result), JSON.stringify(result, dropUnderscored));
   }

   function dropUnderscored(key, value) {
      if (typeof key == 'string' || key instanceof String) {
         if (key.indexOf("_") == 0)
            return undefined;
      }
      return value;
   }

   function handleResponse(result) {
      result.isError = function() {
         return result._contractId == 1 && result._structId == 1;
      };
      if (self.commsLog)
         logResponse(result);
      var func = requestHandlers[result._requestId];
      if (func) {
         func(result);
      }
   }

   function handleMessage(result) {
      if (self.commsLog)
         logMessage(result);
      var func = messageHandlers[result._contractId + "." + result._structId];
      if (func) {
         func(result);
      }
   }

   // --- socket methods

   function onSocketOpen(event) {
      self.connected = true;
      if (self.commsLog)
         console.log("[socket] open")
      var i, array = openHandlers;
      for (i = 0; i < array.length; i++)
         array[i]();

      self.keepAlive = setInterval(function() {
         send("KeepAlive", {}, 1/*Core.DIRECT*/);
         var elapsed = Date.now() - lastHeardFrom;
         if (elapsed > 6000) {
            console.log("We haven't heard from the server in " + elapsed + " ms")
            // TODO: mark as bad connection
         }
         if (elapsed > 20000) {
            disconnect();
         }
      }, 5000);

   }

   function onSocketClose(event) {
      self.connected = false;
      if (self.keepAlive != null) {
         clearInterval(self.keepAlive);
         self.keepAlive = null;
      }
      if (self.commsLog)
         console.log("[socket] closed")
      var i, array = closeHandlers;
      for (i = 0; i < array.length; i++)
         array[i]();
   }

   function onSocketMessage(event) {
      var result = null;
      if (event.data.indexOf("{") == 0) {
         result = JSON.parse(event.data);
      } else {
         // TODO figure out how to communicate errors
         result = parseInt(event.data);
      }
      if (result._requestId != null) {
         handleResponse(result);
      } else if (result._topicId != null) {
         handleMessage(result);
      }
      lastHeardFrom = Date.now();
   }

   function onSocketError(event) {
      if (self.commsLog)
         console.log("[socket] error");
   }

}
<|endoftext|>


<commit_before>// FIXME avoid global
var marker;

var bounds ;

//console.log('map field loaded');

/*
The following variables are set up by a LiteralField in the LatLongField field, as they names of these fields can of course vary
- latFieldName: latittude field name
- lonFieldName: longitutude field name
- zoomFieldName:  zoom field name
*/

   function gmloaded() {
    //console.log('google maps call back');
     initLivequery();
     //initMap();
   }

   // initialise the map

   function initMap() {
    //console.log('init map');

     var myOptions = {
       zoom: 16,
       disableDefaultUI: false,
       mapTypeId: google.maps.MapTypeId.ROADMAP,
       disableDoubleClickZoom: false,
       draggable: true,
       keyboardShortcuts: false,
       scrollwheel: true
     };

     (function($) {
      var gm = $('#GoogleMap');
      //console.log(gm);
      var latFieldName = gm.attr('data-latfieldname');
      //console.log("LAT FIELD NAME:"+latFieldName);

      var latField = $('input[name='+gm.attr('data-latfieldname')+']'); //$('input[name="$LatFieldName"]');
      var lonField = $('input[name='+gm.attr('data-lonfieldname')+']'); // $('input[name="$LonFieldName"]');
      var zoomField = $('input[name='+gm.attr('data-zoomfieldname')+']'); // $('input[name="$ZoomFieldName"]');
      var guidePointsAttr = gm.attr('data-GuidePoints');
      //console.log(guidePointsAttr);

      var guidePoints = new Array();
      if (typeof guidePointsAttr != "undefined") {
        guidePoints = JSON.parse(guidePointsAttr);
      }

      //console.log('T1');

      //console.log("latitude field");
      //console.log(latField);
      //console.log("VAL:"+latField.val());
      //console.log('longitude field');
      //console.log(lonField);
      //console.log("VAL:"+lonField.val());

       myOptions.center = new google.maps.LatLng(latField.val(), lonField.val());

       if (zoomField.length) {
          myOptions['zoom'] = parseInt(zoomField.val());
          //console.log("ZOOM="+myOptions['zoom']);
          //console.log(zoomField);
       }

       map = new google.maps.Map(document.getElementById("GoogleMap"), myOptions);
       bounds = new google.maps.LatLngBounds ();

       if (guidePoints.length) {
        //console.log("GP T1");
        //console.log("GP T2");
        //console.log(guidePoints);
        var sumlat = 0;
        var sumlon = 0;
        for (var i = guidePoints.length - 1; i >= 0; i--) {
          //console.log(i);
          //console.log(guidePoints[i]);
          var lat = guidePoints[i].latitude;
          var lon = guidePoints[i].longitude;
          addGuideMarker(lat,lon);
          var latlng = new google.maps.LatLng(lat, lon);
          sumlat = sumlat + parseFloat(lat);
          sumlon = sumlon + parseFloat(lon);

          // extend bounds
          bounds.extend (latlng);
        };

       /*
        var markerPos = marker.getPosition();
        //console.log("MARKER POS");
        //console.log(markerPos.lat());
    */

        if ((latField.val() == 0) && (lonField.val() == 0)) {
          var nPoints = guidePoints.length;
          //console.log("N Points:"+nPoints);
          //console.log('sum lat = '+sumlat);
          var newMarkerPos = new google.maps.LatLng(sumlat/nPoints, sumlon/nPoints);
          /*
          marker.setPosition(newMarkerPos);
          //console.log("New positino: ");
          //console.log(newMarkerPos);
          bounds.extend(newMarkerPos);
          */
        }

        map.fitBounds(bounds);
      }

       if (latField.val() && lonField.val()) {
         marker = null;

         setMarker(myOptions.center, true);
       }

       google.maps.event.addListener(map, "rightclick", function(event) {
         var lat = event.latLng.lat();
         var lng = event.latLng.lng();
         latField.val(lat);
         lonField.val(lng);
         // populate yor box/field with lat, lng
         //console.log('set marker');
         setMarker(event.latLng, false);
       });

       google.maps.event.addListener(map, "zoom_changed", function(e) {
         if (zoomField.length) {
           zoomField.val(map.getZoom());
         }
       });

      google.maps.event.trigger(map, 'resize');

      map.setZoom( map.getZoom() );

     // see http://stackoverflow.com/questions/10197128/google-maps-api-v3-not-rendering-competely-on-tabbed-page-using-twitters-bootst
     //google.maps.event.trigger(map, 'resize');

     $( document ).bind( "pageshow", function( event, data ){
        google.maps.event.trigger(map, 'resize');
      });

     // When the location tab is clicked, resize the map
     $('.ui-tabs-anchor').click(function() {
        google.maps.event.trigger(map, 'resize');
        var gm = $('#GoogleMap');
        //console.log(gm);
        var useMapBounds = gm.attr('data-usemapbounds');
        //console.log("Use map bounds?: " + useMapBounds);
        if (useMapBounds) {
          //console.log("FITTING MAP TO BOUNDS ON TAB CLICK");
            map.fitBounds(bounds);
        } else {
            //console.log("FITTING MAP TO CENTRE OF MARKER");
            //console.log(marker.getPosition().lat()+','+marker.getPosition().lng());

            map.setCenter(marker.getPosition());
        }
     });

     })(jQuery);

    // map.setZoom(map.getZoom());

   }

   // utility functions

   function addGuideMarker(lat,lon) {
    //console.log("LAT:"+lat);
    //console.log("LON:"+lon);
    var latlng = new google.maps.LatLng(lat, lon);
    var pinColor = "CCCCCC";
    var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));
    var guideMarker = new google.maps.Marker({
      position: latlng,
      title: "Marker",
      icon: pinImage,
      shadow: pinShadow
    });
    guideMarker.setMap(map);

   }

   function setMarker(location, recenter) {
     if (marker != null) {
       marker.setPosition(location);
     } else {
       marker = new google.maps.Marker({
         position: location,
         title: "Position",
         draggable: true
       });
       marker.setMap(map);
       google.maps.event.addListener(marker, 'dragend', setCoordByMarker);
     }

     if (recenter) {
       map.setCenter(location)
     }
   }

   function setCoordByMarker(event) {
     (function($) {

      //console.log("Set coord by drag");

      var latField = $('input[name="$LatFieldName"]');
      var lonField = $('input[name="$LonFieldName"]');
      var zoomField = $('input[name="$ZoomFieldName"]');

      var lat = event.latLng.lat();
      var lng = event.latLng.lng();
      latField.val(lat);
      lonField.val(lng);

       //console.log("LATFIELD");
       //console.log(latField.val());
       //console.log("SHOULD BE "+event.latLng.lng());

       if (zoomField.length) {
         zoomField.val(map.getZoom());
       }

       map.setCenter(event.latLng);

     })(jQuery);

   }

   function searchForAddress(address) {
     (function($) {

       var geocoder = new google.maps.Geocoder();
       var elevator = new google.maps.ElevationService();

       if (geocoder) {
         statusMessage("Searching for:" + address);
         geocoder.geocode({
           'address': address
         }, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             var l = results.length;

             if (l > 0) {
               statusMessage("Places found");
             } else if (l == 0) {
               errorMessage("No places found");
             }

             var html = '
';
             //mapSearchResults
             $.each(results, function(index, value) {
               var address = new Array();
               $.each(value.address_components, function(i, v) {
                 address.push(v.long_name);
               });

               html = html + '
' + address + "
";
             });

             html = html + "
";

             $('#mapSearchResults').html(html);

             //  setMarker(results[0].geometry.location.lat);
           } else {
             errorMessage("Unable to find any geocoded results");
           }
         });

       }

     })(jQuery);

   }

   // prime livequery events

   function initLivequery() {
     (function($) {

      //console.log('init live query');

       //triggers
       $('input[name=action_GetCoords]').livequery('click', function(e) {
         // get the data needed to ask coords
         var location = $('#Form_EditForm_Location').val();
         setCoordByAddress(location);
         return false;
       });

       $('#searchLocationButton').livequery('click', function(e) {
         // get the data needed to ask coords
         var location = $('#location_search').val();
         searchForAddress(location);
         return false;
       });

       //geocodedSearchResults
       $('.geocodedSearchResults li').livequery('click', function(e) {
         // get the data needed to ask coords
         var t = $(this);
         //console.log("ENTRY CLICKED");
         //console.log(t);
         var lat = t.attr("lat");
         var lon = t.attr("lon");
         var address = t.html();
         var latlng = new google.maps.LatLng(lat, lon);
         statusMessage("Setting map to " + address);
         $('.geocodedSearchResults').html('');
         $('#Form_EditForm_Latitude').val(lat);
         $('#Form_EditForm_Longitude').val(lon);

         var latField = $('input[name="$LatFieldName"]');
         var lonField = $('input[name="$LonFieldName"]');
         var zoomField = $('input[name="$ZoomFieldName"]');

         latField.val(lat);
         lonField.val(lon);

         // zoom in to an appropriate level
          map.setZoom(12);

         setMarker(latlng, true);
         return false;
       });

       $('#GoogleMap').livequery(function() {
          initMap();
       });

     })(jQuery);

   }

   (function($) {

     function loadGoogleMapsAPI() {
       var script = document.createElement("script");
       script.type = "text/javascript";
       script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=gmloaded";
       document.body.appendChild(script);
     }

     // deal with document ready - note this only gets called once due to the way silverstripe works, until the CMS is refreshed
     $(document).ready(function() {

       loadGoogleMapsAPI();

     });
   })(jQuery);<commit_msg>FIX: Tabs now resize map agan for ss3 beta 1<commit_after>// FIXME avoid global
var marker;

var bounds ;

   function gmloaded() {
    //console.log('google maps call back');
     initLivequery();
   }

   // initialise the map

   function initMap() {
    //console.log('init map');

     var myOptions = {
       zoom: 16,
       disableDefaultUI: false,
       mapTypeId: google.maps.MapTypeId.ROADMAP,
       disableDoubleClickZoom: false,
       draggable: true,
       keyboardShortcuts: false,
       scrollwheel: true
     };

     (function($) {
      var gm = $('#GoogleMap');
      var latFieldName = gm.attr('data-latfieldname');

      var latField = $('input[name='+gm.attr('data-latfieldname')+']'); //$('input[name="$LatFieldName"]');
      var lonField = $('input[name='+gm.attr('data-lonfieldname')+']'); // $('input[name="$LonFieldName"]');
      var zoomField = $('input[name='+gm.attr('data-zoomfieldname')+']'); // $('input[name="$ZoomFieldName"]');
      var guidePointsAttr = gm.attr('data-GuidePoints');

      var guidePoints = new Array();
      if (typeof guidePointsAttr != "undefined") {
        guidePoints = JSON.parse(guidePointsAttr);
      }

       myOptions.center = new google.maps.LatLng(latField.val(), lonField.val());

       if (zoomField.length) {
          myOptions['zoom'] = parseInt(zoomField.val());
       }

       map = new google.maps.Map(document.getElementById("GoogleMap"), myOptions);
       bounds = new google.maps.LatLngBounds ();

       // guide points are grey marked out pins that are used as contextual hints to the current desired location
       // An example of this would be photographs taken on the same bike ride or walk
       if (guidePoints.length) {
        var sumlat = 0;
        var sumlon = 0;
        for (var i = guidePoints.length - 1; i >= 0; i--) {
          var lat = guidePoints[i].latitude;
          var lon = guidePoints[i].longitude;
          addGuideMarker(lat,lon);
          var latlng = new google.maps.LatLng(lat, lon);
          sumlat = sumlat + parseFloat(lat);
          sumlon = sumlon + parseFloat(lon);

          // extend bounds
          bounds.extend (latlng);
        };

        if ((latField.val() == 0) && (lonField.val() == 0)) {
          var nPoints = guidePoints.length;
          var newMarkerPos = new google.maps.LatLng(sumlat/nPoints, sumlon/nPoints);
        }

        map.fitBounds(bounds);
      }

       if (latField.val() && lonField.val()) {
         marker = null;

         setMarker(myOptions.center, true);
       }

       // when one right clicks, set the red marker flag to that coordinate
       google.maps.event.addListener(map, "rightclick", function(event) {
         var lat = event.latLng.lat();
         var lng = event.latLng.lng();
         latField.val(lat);
         lonField.val(lng);
         setMarker(event.latLng, false);
         statusMessage('Location changed to '+lat+','+lng);
       });

       google.maps.event.addListener(map, "zoom_changed", function(e) {
         if (zoomField.length) {
           zoomField.val(map.getZoom());
         }
       });

      google.maps.event.trigger(map, 'resize');
      map.setZoom( map.getZoom() );

     // When any tab is clicked, resize the map
     $('.ui-tabs-anchor').click(function() {
        google.maps.event.trigger(map, 'resize');
        var gm = $('#GoogleMap');
        //console.log(gm);
        var useMapBounds = gm.attr('data-usemapbounds');
        if (useMapBounds) {
            map.fitBounds(bounds);
        } else {
            map.setCenter(marker.getPosition());
        }
     });

     })(jQuery);

   }

   // utility functions

   function addGuideMarker(lat,lon) {
    //console.log("LAT:"+lat);
    //console.log("LON:"+lon);
    var latlng = new google.maps.LatLng(lat, lon);
    var pinColor = "CCCCCC";
    var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));
    var guideMarker = new google.maps.Marker({
      position: latlng,
      title: "Marker",
      icon: pinImage,
      shadow: pinShadow
    });
    guideMarker.setMap(map);

   }

   function setMarker(location, recenter) {
     if (marker != null) {
       marker.setPosition(location);
     } else {
       marker = new google.maps.Marker({
         position: location,
         title: "Position",
         draggable: true
       });
       marker.setMap(map);
       google.maps.event.addListener(marker, 'dragend', setCoordByMarker);
     }

     if (recenter) {
       map.setCenter(location)
     }
   }

   function setCoordByMarker(event) {
     (function($) {

      //console.log("Set coord by drag");

      var latField = $('input[name="$LatFieldName"]');
      var lonField = $('input[name="$LonFieldName"]');
      var zoomField = $('input[name="$ZoomFieldName"]');

      var lat = event.latLng.lat();
      var lng = event.latLng.lng();
      latField.val(lat);
      lonField.val(lng);

      statusMessage('Location changed to '+lat+','+lng);

       if (zoomField.length) {
         zoomField.val(map.getZoom());
       }

       map.setCenter(event.latLng);

     })(jQuery);

   }

   function searchForAddress(address) {
     (function($) {

       var geocoder = new google.maps.Geocoder();
       var elevator = new google.maps.ElevationService();

       if (geocoder) {
         statusMessage("Searching for:" + address);
         geocoder.geocode({
           'address': address
         }, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             var l = results.length;

             if (l > 0) {
               statusMessage("Places found");
             } else if (l == 0) {
               errorMessage("No places found");
             }

             var html = '
';
             //mapSearchResults
             $.each(results, function(index, value) {
               var address = new Array();
               $.each(value.address_components, function(i, v) {
                 address.push(v.long_name);
               });

               html = html + '
' + address + "
";
             });

             html = html + "
";

             $('#mapSearchResults').html(html);

             //  setMarker(results[0].geometry.location.lat);
           } else {
             errorMessage("Unable to find any geocoded results");
           }
         });

       }

     })(jQuery);

   }

   // prime livequery events

   function initLivequery() {
     (function($) {

       //triggers
       $('input[name=action_GetCoords]').livequery('click', function(e) {
         // get the data needed to ask coords
         var location = $('#Form_EditForm_Location').val();
         setCoordByAddress(location);
         return false;
       });

       $('#searchLocationButton').livequery('click', function(e) {
         // get the data needed to ask coords
         var location = $('#location_search').val();
         searchForAddress(location);
         return false;
       });

       //geocodedSearchResults
       $('.geocodedSearchResults li').livequery('click', function(e) {
         // get the data needed to ask coords
         var t = $(this);
         //console.log("ENTRY CLICKED");
         //console.log(t);
         var lat = t.attr("lat");
         var lon = t.attr("lon");
         var address = t.html();
         var latlng = new google.maps.LatLng(lat, lon);
         statusMessage("Setting map to " + address);
         $('.geocodedSearchResults').html('');
         $('#Form_EditForm_Latitude').val(lat);
         $('#Form_EditForm_Longitude').val(lon);

         var latField = $('input[name="$LatFieldName"]');
         var lonField = $('input[name="$LonFieldName"]');
         var zoomField = $('input[name="$ZoomFieldName"]');

         latField.val(lat);
         lonField.val(lon);

         // zoom in to an appropriate level
          map.setZoom(12);

         setMarker(latlng, true);
         return false;
       });

       $('#GoogleMap').livequery(function() {
          initMap();
       });

     })(jQuery);

   }

   (function($) {

     function loadGoogleMapsAPI() {
       var script = document.createElement("script");
       script.type = "text/javascript";
       script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=gmloaded";
       document.body.appendChild(script);
     }

     // deal with document ready - note this only gets called once due to the way silverstripe works, until the CMS is refreshed
     $(document).ready(function() {

       loadGoogleMapsAPI();

     });
   })(jQuery);<|endoftext|>