<commit_before>// Copyright 2010 Google Inc. All Rights Reserved.
//
// 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.

// Functions for uploading to the server

// These are the URLs used by the backend for posting data
var kServerPostSetUrl = "set";
var kServerPostResultUrl = "result";
var kServerPostSummaryUrl = "summary";

// BrowserDetect is thanks to www.quirksmode.org/js/detect.html
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++)  {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1)
      return;
    var version_string = dataString.substring(index+this.versionSearchString.length+1);
    var end_index = version_string.indexOf(" ");
    if (end_index < 0) {
      return version_string;
    }
    return version_string.substring(0, end_index);
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {    // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
      string: navigator.userAgent,
      subString: "iPhone",
      identity: "iPhone/iPod"
    },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]
};
BrowserDetect.init();

// Returns the max value in the array.
Array.max = function(array) {
  return Math.max.apply(Math, array);
};

// Returns the min value in the array.
Array.min = function(array) {
  return Math.min.apply(Math, array);
};

// Returns the sum of all values in the array.
Array.sum = function(array) {
  var sum = 0;
  for (var i = array.length - 1; i >= 0; i--) {
    sum += array[i];
  }
  return sum;
};

// Returns the average value of the array, excluding the min and max values.
Array.trimmedMean = function(array) {
  var count = array.length;
  var sum = Array.sum(array);
  if (count > 2) {
    sum -= Array.min(array) + Array.max(array);
    count -= 2;
  }
  return Math.round(sum / count);
}

// Returns the standard deviation of the array, excluding the min and max values.
Array.trimmedStdDev = function(array) {
  var count = array.length;
  var trimmedMean = Array.trimmedMean(array);
  var min = Array.min(array);
  var max = Array.max(array);
  var variance = 0;
  for (var i = 0; i < count; i++) {
    if (count > 2 && (array[i] == min || array[i] == max)) continue;
    var deviation = trimmedMean - array[i];
    variance += deviation * deviation;
  }
  if (count > 2) count -= 2;
  variance /= count;
  return Math.sqrt(variance);
}

function XHRGet(url, callback) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.send();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status != 200)  {
        console.log("XHR error getting url " + url + ", error: " + xhr.status);
      }
      callback(xhr.responseText);
    }
  }
}

function XHRPost(url, data, callback) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(data);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status != 200)  {
        console.log("XHR error posting url " + url + ", error: " + xhr.status);
      }
      callback(xhr.responseText);
    }
  }
}

function copy(obj) {
  var copy = {};
  for (var prop in obj)
    copy[prop] = obj[prop];
  return copy;
}

function jsonToPostData(json) {
  var post_data = [];
  for (var prop in json) {
    post_data.push(prop + "=" + encodeURIComponent(json[prop]));
  }
  return post_data.join("&");
}

// Submits a set of test runs up to the server.
function TestResultSubmitter(config) {
  var self = this;
  var test_id;
  var create_test_started = false;
  var user_callback;

  this.AppEngineLogin = function(callback) {
    new XHRGet(config.server_login, function() {
      callback();
    });
  }

  // Creates the test.  This should only be called once.
  // Upon test creation, the callback will be called with a single argument
  // containing the status of the creation.
  this.CreateTest = function(callback) {
    if (create_test_started) {
      callback(test_id);
      return;
    }

    self.AppEngineLogin(function() {
      create_test_started = true;
      var data = copy(config);
      data["cmd"] = "create";
      data["version"] = BrowserDetect.browser + " " + BrowserDetect.version;
      data["platform"] = BrowserDetect.OS;

      url = config.server_url + kServerPostSetUrl;

      user_callback = callback;
      new XHRPost(url, jsonToPostData(data), function(result) {
        test_id = result;
        user_callback(result);
      });
    });
  }

  // Post a single result
  this.PostResult = function (result, callback) {
    var data = copy(result);
    data["set_id"] = test_id;
    // TODO: This is an artifact of the presentation. It should not be
    // stored in the DB this way.
    data["using_spdy"] = (result.using_spdy ? "CHECKED" : "");

    url = config.server_url + kServerPostResultUrl;
    user_callback = callback;
    new XHRPost(url, jsonToPostData(data),
		function(result) { user_callback(result); });
  }

  // Post the rollup summary of a set of data
  this.PostSummary = function(data, callback) {
    var result = copy(data);
    // Average everything except the special properties.
    for (var prop in result) {
      if (prop == "iterations") {
        result.iterations = data.iterations / data.total_time.length;
        continue;
      }
      if (prop == "url" || prop == "using_spdy")
	continue;
      result[prop] = Array.trimmedMean(result[prop]);
    }
    result["set_id"] = test_id
    result["total_time_stddev"] = Array.trimmedStdDev(data.total_time);

    url = config.server_url + kServerPostSummaryUrl;
    user_callback = callback;
    new XHRPost(url, jsonToPostData(result),
		function(result) { user_callback(result); });
  }

  // Update the set with its summary data
  this.UpdateSetSummary = function(data, callback) {
    var result = copy(data);
    // Divide everything by iterations except the special properties.
    for (var prop in result) {
      if (prop == "iterations") {
	result.iterations = data.iterations / data.url_count;
	continue;
      }
      if (prop == "url_count")
	continue;
      result[prop] = Math.round(result[prop] / data.iterations);
    }
    result["cmd"] = "update";
    result["set_id"] = test_id;

    url = config.server_url + kServerPostSetUrl;
    user_callback = callback;
    new XHRPost(url, jsonToPostData(result),
		function(result) { user_callback(result); });
  }

}
<commit_msg>Fix iteration counts that we upload<commit_after>// Copyright 2010 Google Inc. All Rights Reserved.
//
// 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.

// Functions for uploading to the server

// These are the URLs used by the backend for posting data
var kServerPostSetUrl = "set";
var kServerPostResultUrl = "result";
var kServerPostSummaryUrl = "summary";

// BrowserDetect is thanks to www.quirksmode.org/js/detect.html
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++)  {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1)
      return;
    var version_string = dataString.substring(index+this.versionSearchString.length+1);
    var end_index = version_string.indexOf(" ");
    if (end_index < 0) {
      return version_string;
    }
    return version_string.substring(0, end_index);
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {    // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
      string: navigator.userAgent,
      subString: "iPhone",
      identity: "iPhone/iPod"
    },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]
};
BrowserDetect.init();

// Returns the max value in the array.
Array.max = function(array) {
  return Math.max.apply(Math, array);
};

// Returns the min value in the array.
Array.min = function(array) {
  return Math.min.apply(Math, array);
};

// Returns the sum of all values in the array.
Array.sum = function(array) {
  var sum = 0;
  for (var i = array.length - 1; i >= 0; i--) {
    sum += array[i];
  }
  return sum;
};

// Returns the average value of the array, excluding the min and max values.
Array.trimmedMean = function(array) {
  var count = array.length;
  var sum = Array.sum(array);
  if (count > 2) {
    sum -= Array.min(array) + Array.max(array);
    count -= 2;
  }
  return Math.round(sum / count);
}

// Returns the standard deviation of the array, excluding the min and max values.
Array.trimmedStdDev = function(array) {
  var count = array.length;
  var trimmedMean = Array.trimmedMean(array);
  var min = Array.min(array);
  var max = Array.max(array);
  var variance = 0;
  for (var i = 0; i < count; i++) {
    if (count > 2 && (array[i] == min || array[i] == max)) continue;
    var deviation = trimmedMean - array[i];
    variance += deviation * deviation;
  }
  if (count > 2) count -= 2;
  variance /= count;
  return Math.sqrt(variance);
}

function XHRGet(url, callback) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.send();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status != 200)  {
        console.log("XHR error getting url " + url + ", error: " + xhr.status);
      }
      callback(xhr.responseText);
    }
  }
}

function XHRPost(url, data, callback) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(data);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status != 200)  {
        console.log("XHR error posting url " + url + ", error: " + xhr.status);
      }
      callback(xhr.responseText);
    }
  }
}

function copy(obj) {
  var copy = {};
  for (var prop in obj)
    copy[prop] = obj[prop];
  return copy;
}

function jsonToPostData(json) {
  var post_data = [];
  for (var prop in json) {
    post_data.push(prop + "=" + encodeURIComponent(json[prop]));
  }
  return post_data.join("&");
}

// Submits a set of test runs up to the server.
function TestResultSubmitter(config) {
  var self = this;
  var test_id;
  var create_test_started = false;
  var user_callback;

  this.AppEngineLogin = function(callback) {
    new XHRGet(config.server_login, function() {
      callback();
    });
  }

  // Creates the test.  This should only be called once.
  // Upon test creation, the callback will be called with a single argument
  // containing the status of the creation.
  this.CreateTest = function(callback) {
    if (create_test_started) {
      callback(test_id);
      return;
    }

    self.AppEngineLogin(function() {
      create_test_started = true;
      var data = copy(config);
      data["cmd"] = "create";
      data["version"] = BrowserDetect.browser + " " + BrowserDetect.version;
      data["platform"] = BrowserDetect.OS;

      url = config.server_url + kServerPostSetUrl;

      user_callback = callback;
      new XHRPost(url, jsonToPostData(data), function(result) {
        test_id = result;
        user_callback(result);
      });
    });
  }

  // Post a single result
  this.PostResult = function (result, callback) {
    var data = copy(result);
    data["set_id"] = test_id;
    // TODO: This is an artifact of the presentation. It should not be
    // stored in the DB this way.
    data["using_spdy"] = (result.using_spdy ? "CHECKED" : "");

    url = config.server_url + kServerPostResultUrl;
    user_callback = callback;
    new XHRPost(url, jsonToPostData(data),
		function(result) { user_callback(result); });
  }

  // Post the rollup summary of a set of data
  this.PostSummary = function(data, callback) {
    var result = copy(data);
    // Average everything except the special properties.
    for (var prop in result) {
      if (prop == "url" || prop == "using_spdy")
	continue;
      result[prop] = Array.trimmedMean(result[prop]);
    }
    result["set_id"] = test_id
    result["total_time_stddev"] = Array.trimmedStdDev(data.total_time);

    url = config.server_url + kServerPostSummaryUrl;
    user_callback = callback;
    new XHRPost(url, jsonToPostData(result),
		function(result) { user_callback(result); });
  }

  // Update the set with its summary data
  this.UpdateSetSummary = function(data, callback) {
    var result = copy(data);
    // Divide everything by iterations except the special properties.
    for (var prop in result) {
      if (prop == "iterations") {
	result.iterations = Math.round(data.iterations / data.url_count);
	continue;
      }
      if (prop == "url_count")
	continue;
      result[prop] = Math.round(result[prop] / data.iterations);
    }
    result["cmd"] = "update";
    result["set_id"] = test_id;

    url = config.server_url + kServerPostSetUrl;
    user_callback = callback;
    new XHRPost(url, jsonToPostData(result),
		function(result) { user_callback(result); });
  }

}
<|endoftext|>


<commit_before>
var url="http://127.0.0.1:1338/";
var game;

//Funciones que modifican el index

function inicio(){
	if ($.cookie("nombre")!=undefined)
	{
		comprobarUsuario();
	}
	else{
		mostrarCabecera();
	}
}

function borrarControl(){
	$('#control').remove();
}

function mostrarCabecera(){
	$('#cabecera').remove();
	$('#enh').remove();
	$('#datos').remove();
	$('#prog').remove();
	$('#control').append('

Panel de  Control
<input type="text" id="nombre" placeholder="introduce tu nombre">
');
	botonNombre();
}

function botonNombre(){
	var nombre="";
	$('#control').append('<button type="button" id="nombreBtn" class="btn btn-primary btn-md">Iniciar partida</button>');
	$('#nombreBtn').on('click',function(){
		nombre=$('#nombre').val();
		$('#nombre').remove();
		$('#nombreBtn').remove();
		crearUsuario(nombre);
	});
}

function mostrarInfoJugador(){
	var nombre=$.cookie("nombre");
	var id=$.cookie("id");
	var nivel=$.cookie("nivel");
	var percen=(nivel/3)*100;
	$('#datos').remove();
	$('#cabeceraP').remove();
	$('#cabecera').remove();
	$('#prog').remove();
	$('#control').append('

Panel

')
	$('#control').append('
Nombre: '+nombre+' Nivel: '+nivel+' Id:'+id+'
');
	$('#control').append('

');
	siguienteNivel();
}

function siguienteNivel(){
	$('#control').append('<button type="button" id="siguienteBtn" class="btn btn-primary btn-md">Siguiente nivel</button>')
	$('#siguienteBtn').on('click',function(){
		$('#siguienteBtn').remove();
		$('#enh').remove();
		$('#res').remove();
  		$('#resultados').remove();
		crearNivel($.cookie('nivel'));
	});
}

function noHayNiveles(){
	$('#juegoId').append("
Lo siento, no tenemos más niveles
");
	$('#control').append('<button type="button" id="siguienteBtn" class="btn btn-primary btn-md">Volver a empezar</button>')
	$('#siguienteBtn').on('click',function(){
		$('#siguienteBtn').remove();
		reset();
	});
}

function nivelCompletado(tiempo){
	//game.destroy();
	game.destroy();
	$('#juegoId').append("
Enhorabuena!
");
	comunicarNivelCompletado(tiempo);
	obtenerResultados();
}

function mostrarResultados(datos){
  //eliminarGame();
  //eliminarCabeceras();
  $('#res').remove();
  $('#resultados').remove();
  $('#juegoId').append('
Resultados
');
  var cadena="

Nombre	Nivel	Tiempo
";
    for(var i=0;i<datos.length;i++){
      cadena=cadena+"
"+datos[i].nombre+"	 "+datos[i].nivel+"	"+"	 "+datos[i].tiempo+"
";
    }
    cadena=cadena+"
";
    $('#juegoId').append(cadena);
}

function reset(){
	borrarCookies();
	mostrarCabecera();
}

function borrarCookies(){
	$.removeCookie("nombre");
	$.removeCookie("id");
	$.removeCookie("nivel");
}

//Funciones de comunicación con el servidor

function crearUsuario(nombre){
	if (nombre==""){
		nombre="jugador";
	}
	$.getJSON(url+'crearUsuario/'+nombre,function(datos){
		$.cookie('nombre',datos.nombre);
		$.cookie('id',datos.id);
		$.cookie('nivel',datos.nivel);
		mostrarInfoJugador();
	});
	//mostrar datos
}

function comprobarUsuario(){
	var id=$.cookie("id");

	$.getJSON(url+'comprobarUsuario/'+id,function(datos){
		if (datos.nivel<0){
			borrarCookies();
			mostrarCabecera();
		}
		else{
			$.cookie("nivel",datos.nivel);
			mostrarInfoJugador();
		}
	});
}

function comunicarNivelCompletado(tiempo){
	var id=$.cookie("id");

	$.getJSON(url+'nivelCompletado/'+id+"/"+tiempo,function(datos){
			$.cookie("nivel",datos.nivel);
			mostrarInfoJugador();
	});
}

function obtenerResultados(){
	var id=$.cookie("id");

	$.getJSON(url+'obtenerResultados/'+id,function(datos){
			//$.cookie("nivel",datos.nivel);
			mostrarResultados(datos);
	});
}<commit_msg>mostrar info jugador<commit_after>
var url="http://127.0.0.1:1338/";
var game;

//Funciones que modifican el index

function inicio(){
	if ($.cookie("nombre")!=undefined)
	{
		comprobarUsuario();
	}
	else{
		mostrarCabecera();
	}
}

function borrarControl(){
	$('#control').remove();
}

function mostrarCabecera(){
	$('#cabecera').remove();
	$('#enh').remove();
	$('#datos').remove();
	$('#prog').remove();
	$('#control').append('

Panel de  Control
<input type="text" id="nombre" placeholder="introduce tu nombre">
');
	botonNombre();
}

function botonNombre(){
	var nombre="";
	$('#control').append('<button type="button" id="nombreBtn" class="btn btn-primary btn-md">Iniciar partida</button>');
	$('#nombreBtn').on('click',function(){
		nombre=$('#nombre').val();
		$('#nombre').remove();
		$('#nombreBtn').remove();
		crearUsuario(nombre);
	});
}

function mostrarInfoJugador(){
	var nombre=$.cookie("nombre");
	var id=$.cookie("id");
	var nivel=$.cookie("nivel");
	var percen=Math.floor((nivel/3)*100);
	$('#datos').remove();
	$('#cabeceraP').remove();
	$('#cabecera').remove();
	$('#prog').remove();
	$('#control').append('

Panel

')
	$('#control').append('

Nombre: '+nombre+'
Nivel: '+nivel+'

');
	$('#control').append('

'+percen+'%

');
	siguienteNivel();
}

function siguienteNivel(){
	$('#control').append('<button type="button" id="siguienteBtn" class="btn btn-primary btn-md">Siguiente nivel</button>')
	$('#siguienteBtn').on('click',function(){
		$('#siguienteBtn').remove();
		$('#enh').remove();
		$('#res').remove();
  		$('#resultados').remove();
		crearNivel($.cookie('nivel'));
	});
}

function noHayNiveles(){
	$('#juegoId').append("
Lo siento, no tenemos más niveles
");
	$('#control').append('<button type="button" id="siguienteBtn" class="btn btn-primary btn-md">Volver a empezar</button>')
	$('#siguienteBtn').on('click',function(){
		$('#siguienteBtn').remove();
		reset();
	});
}

function nivelCompletado(tiempo){
	//game.destroy();
	game.destroy();
	$('#juegoId').append("
Enhorabuena!
");
	comunicarNivelCompletado(tiempo);
	obtenerResultados();
}

function mostrarResultados(datos){
  //eliminarGame();
  //eliminarCabeceras();
  $('#res').remove();
  $('#resultados').remove();
  $('#juegoId').append('
Resultados
');
  var cadena="

Nombre	Nivel	Tiempo
";
    for(var i=0;i<datos.length;i++){
      cadena=cadena+"
"+datos[i].nombre+"	 "+datos[i].nivel+"	"+"	 "+datos[i].tiempo+"
";
    }
    cadena=cadena+"
";
    $('#juegoId').append(cadena);
}

function reset(){
	borrarCookies();
	mostrarCabecera();
}

function borrarCookies(){
	$.removeCookie("nombre");
	$.removeCookie("id");
	$.removeCookie("nivel");
}

//Funciones de comunicación con el servidor

function crearUsuario(nombre){
	if (nombre==""){
		nombre="jugador";
	}
	$.getJSON(url+'crearUsuario/'+nombre,function(datos){
		$.cookie('nombre',datos.nombre);
		$.cookie('id',datos.id);
		$.cookie('nivel',datos.nivel);
		mostrarInfoJugador();
	});
	//mostrar datos
}

function comprobarUsuario(){
	var id=$.cookie("id");

	$.getJSON(url+'comprobarUsuario/'+id,function(datos){
		if (datos.nivel<0){
			borrarCookies();
			mostrarCabecera();
		}
		else{
			$.cookie("nivel",datos.nivel);
			mostrarInfoJugador();
		}
	});
}

function comunicarNivelCompletado(tiempo){
	var id=$.cookie("id");

	$.getJSON(url+'nivelCompletado/'+id+"/"+tiempo,function(datos){
			$.cookie("nivel",datos.nivel);
			mostrarInfoJugador();
	});
}

function obtenerResultados(){
	var id=$.cookie("id");

	$.getJSON(url+'obtenerResultados/'+id,function(datos){
			//$.cookie("nivel",datos.nivel);
			mostrarResultados(datos);
	});
}<|endoftext|>


<commit_before>/**
 * sivart-ci v0.1.0
 *
 * A simple interactive CI Dashboard built on MEAN stack.
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 27 November, 2015
 *
 * Sivart CI Angular App.
 */

(function() {
    var sivartCI = angular.module('sivartCI', []),
        pageLocation = window.location,
        socketListenerPort = 3000,
        socket;

    /*
     * Declare App Controllers
     */
    sivartCI.controller("MainController", ["$scope", "$http", "$sce", '$timeout', MainController]);

    /*
     * Create Directives
     */
    sivartCI.directive('onFinishRender', ['$timeout', '$parse', function($timeout, $parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                if (scope.$last)
                {
                    scope.$eval(attrs.onFinishRender);
                }
            }
        };
    }]);

    /*
     * Main Controller
     */
    MainController.$inject = ["$scope"];
    function MainController($scope, $http, $sce, $timeout) {

        // Load Data
        $http.get('/api/changelists')
        .success(function(data) {
            $scope.changelistItems = data;
            $scope.changelistItems.findChangelist = function(fieldName, lookupValue) {
                var matchedChangelist,
                    i;

                for (i = 0; i < $scope.changelistItems.length; i++)
                {
                    if ($scope.changelistItems[i][fieldName] === lookupValue)
                    {
                        matchedChangelist = $scope.changelistItems[i];
                        break;
                    }
                }

                return matchedChangelist;
            };
        })
        .error(function(data) {
            console.log('Error Loading Changelists');
        });

        // Event Listeners
        $scope.onChangelistReady = function(val) {
            $timeout(function() {
                $scope.initSocket();
            }, 1);
        };

        $scope.onChangelistItemClick = function(changelistId) {
            var changelistEl = $('#' + changelistId),
                changelistDetailsEl = $('#' + changelistId + '-details').find('.changelist-details');

            if (changelistEl.hasClass('item-pass') ||
                changelistEl.hasClass('item-fail'))
            {
                if (!changelistDetailsEl.is(':visible'))
                {
                    changelistEl.addClass('expanded');
                    changelistEl.find('.changelist-status').attr('rowspan', 2);
                    changelistDetailsEl.slideDown('fast');
                }
                else
                {
                    changelistEl.removeClass('expanded');
                    changelistEl.find('.changelist-status').removeAttr('rowspan');
                    changelistDetailsEl.slideUp('fast');
                }
            }
        };

        // Item Preprocessors.
        $scope.getTimeStarted = function(timeStarted) {
            var timeStartedObj = new Date(timeStarted),
                formattedString;

            formattedString = timeStartedObj.getMonth() + '/' +
                              timeStartedObj.getDate() + '/' +
                              timeStartedObj.getUTCFullYear() + ' ' +
                              '' +
                              this.formatTime(timeStartedObj);

            return $sce.trustAsHtml(formattedString);
        };

        $scope.getStatus = function(status) {
            var statusEl = {
                "-1": "Failed",
                "0": "Pending",
                "1": "Passed",
                "2": "Running"
            };

            switch (status) {
                case -1:
                    statusEl =  '' +
                                    'Failed' +
                                '' +
                                '' +
                                    'Build Failure' +
                                '';
                    break;
                case 0:
                    statusEl = 'Pending';
                    break;
                case 1:
                statusEl =  '' +
                                'Passed' +
                            '' +
                            '' +
                                'Build Passed' +
                            '';
                    break;
                default:
                    statusEl = 'Running';
            }

            return $sce.trustAsHtml(statusEl);
        };

        $scope.getBuildStatus = function(status, timeCompleted) {
            var timeCompletedObj = new Date(timeCompleted),
                buildIconEl = status === 1 ? '' : '',
                buildStatusEl;

            buildStatusEl = 'Build ' + buildIconEl + '' +
                            '' +
                                '' +
                                this.formatTime(timeCompletedObj) +
                            '';

            return $sce.trustAsHtml(buildStatusEl);
        };

        $scope.getInitialStatusClass = function(status) {
            var statusMap = {
                "-1": "item-fail",
                "0": "item-pending",
                "1": "item-pass",
                "2": "item-active"
            };

            return statusMap[status];
        };

        // Utility Functions.
        $scope.formatTime = function(dateObj) {
            var hh = dateObj.getHours(),
                mm = dateObj.getMinutes(),
                ampm = hh >= 12 ? 'pm' : 'am';

            return hh + ':' + mm + ' ' + ampm;
        };

        $scope.initSocket = function() {
            var i;

            socket = io.connect(pageLocation.protocol + '//' + pageLocation.hostname + ':' + socketListenerPort);

            // Invokes build on Server.
            for (i = 1; i <=  $scope.changelistItems.length; i++)
            {
                $timeout(function(changelistId) {
                    socket.emit('triggerbuild', changelistId);
                }, i * 1000, true, $scope.changelistItems[i - 1]._id);
            }

            socket.on('buildstart', function(changelistId) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = $('tr#' + changelistId).find('.progress-steps .buildStep');
                console.log('Build started for Changelist ', $scope.changelistItems.findChangelist('_id', changelistId).changeListName);

                $scope.changelistItems.findChangelist('_id', changelistId).activity.status = 2;
                buildStepEl.removeClass('step-pending').addClass('step-active');
                buildStepEl.find('.step-icon').removeClass('step-icon-pending').addClass('step-icon-active');
            });

            socket.on('buildfinished', function(changelistId, status) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep');
                console.log('Build finished for Changelist ', $scope.changelistItems.findChangelist('_id', changelistId).changeListName, ' with status ', status);

                if (status === 1)
                    buildStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-pass');
                else
                {
                    $scope.changelistItems.findChangelist('_id', changelistId).activity.status = status;
                    buildStepEl.removeClass('step-active').addClass('step-fail');
                    buildStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-fail');
                }
            });

            socket.on('unitteststart', function(changelistId) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep');

                console.log('Unit Tests started for Changelist ', $scope.changelistItems.findChangelist('_id', changelistId).changeListName);

                buildStepEl.addClass('fill-step-progress');
                $timeout(function() {
                    utStepEl.removeClass('step-empty').addClass('step-active');
                    utStepEl.find('.step-icon').addClass('step-icon-active');
                }, 1000);
            });

            socket.on('unittestfinished', function(changelistId, status) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep');

                if (status === 1)
                    utStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-pass');
                else
                {
                    $scope.changelistItems.findChangelist('_id', changelistId).activity.status = status;
                    utStepEl.removeClass('step-active').addClass('step-fail');
                    buildStepEl.removeClass('step-active fill-step-progress').addClass('step-fail fill-step-progress');
                    $timeout(function() {
                        utStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-fail');
                    }, 1000);
                }
            });

            socket.on('functionalteststart', function(changelistId) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep'),
                    ftStepEl = changeListItemEl.find('.progress-steps .ftStep');

                utStepEl.addClass('fill-step-progress');
                $timeout(function() {
                    ftStepEl.removeClass('step-empty').addClass('step-active');
                    ftStepEl.find('.step-icon').addClass('step-icon-active');
                }, 1000);
            });

            socket.on('functionaltestfinished', function(changelistId, status) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep'),
                    ftStepEl = changeListItemEl.find('.progress-steps .ftStep');

                if (status === 1)
                {
                    $scope.changelistItems.findChangelist('_id', changelistId).activity.status = status;
                    buildStepEl.removeClass('step-active fill-step-progress').addClass('step-pass fill-step-progress');
                    utStepEl.removeClass('step-active fill-step-progress').addClass('step-pass fill-step-progress');
                    ftStepEl.addClass('step-pass');
                    $timeout(function() {
                        ftStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-pass');
                    }, 1000);
                }
                else
                {
                    $scope.changelistItems.findChangelist('_id', changelistId).activity.status = status;
                    buildStepEl.removeClass('step-active fill-step-progress').addClass('step-fail fill-step-progress');
                    utStepEl.removeClass('step-active fill-step-progress').addClass('step-fail fill-step-progress');
                    ftStepEl.addClass('step-fail');
                    $timeout(function() {
                        ftStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-fail');
                    }, 1000);
                }
            });
        };
    }
})();
<commit_msg>Property update on socket events.<commit_after>/**
 * sivart-ci v0.1.0
 *
 * A simple interactive CI Dashboard built on MEAN stack.
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 27 November, 2015
 *
 * Sivart CI Angular App.
 */

(function() {
    var sivartCI = angular.module('sivartCI', []),
        pageLocation = window.location,
        socketListenerPort = 3000,
        socket;

    /*
     * Declare App Controllers
     */
    sivartCI.controller("MainController", ["$scope", "$http", "$sce", '$timeout', MainController]);

    /*
     * Create Directives
     */
    sivartCI.directive('onFinishRender', ['$timeout', '$parse', function($timeout, $parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                if (scope.$last)
                {
                    scope.$eval(attrs.onFinishRender);
                }
            }
        };
    }]);

    /*
     * Main Controller
     */
    MainController.$inject = ["$scope"];
    function MainController($scope, $http, $sce, $timeout) {

        // Load Data
        $http.get('/api/changelists')
        .success(function(data) {
            $scope.changelistItems = data;
            $scope.changelistItems.findChangelist = function(fieldName, lookupValue) {
                var matchedChangelist,
                    i;

                for (i = 0; i < $scope.changelistItems.length; i++)
                {
                    if ($scope.changelistItems[i][fieldName] === lookupValue)
                    {
                        matchedChangelist = $scope.changelistItems[i];
                        break;
                    }
                }

                return matchedChangelist;
            };
        })
        .error(function(data) {
            console.log('Error Loading Changelists');
        });

        // Event Listeners
        $scope.onChangelistReady = function(val) {
            $timeout(function() {
                $scope.initSocket();
            }, 1);
        };

        $scope.onShowMenu = function() {
            $("#wrapper").toggleClass("toggled");
        };

        $scope.onChangelistItemClick = function(changelistId) {
            var changelistEl = $('#' + changelistId),
                changelistDetailsEl = $('#' + changelistId + '-details').find('.changelist-details');

            if (changelistEl.hasClass('item-pass') ||
                changelistEl.hasClass('item-fail'))
            {
                if (!changelistDetailsEl.is(':visible'))
                {
                    changelistEl.addClass('expanded');
                    changelistEl.find('.changelist-status').attr('rowspan', 2);
                    changelistDetailsEl.slideDown('fast');

                    changelistDetailsEl.find('.css-pie').each(function(e) {
                    	var p = $(this).text();
                    	$(this)[0].style.animationDelay = '-' + parseFloat(p) + 's';
                    });
                }
                else
                {
                    changelistEl.removeClass('expanded');
                    changelistEl.find('.changelist-status').removeAttr('rowspan');
                    changelistDetailsEl.slideUp('fast');
                }
            }
        };

        // Item Preprocessors.
        $scope.getTimeStarted = function(timeStarted) {
            var timeStartedObj = new Date(timeStarted),
                formattedString;

            formattedString = timeStartedObj.getMonth() + '/' +
                              timeStartedObj.getDate() + '/' +
                              timeStartedObj.getUTCFullYear() + ' ' +
                              '' +
                              this.formatTime(timeStartedObj);

            return $sce.trustAsHtml(formattedString);
        };

        $scope.getStatus = function(status) {
            var statusEl = {
                "-1": "Failed",
                "0": "Pending",
                "1": "Passed",
                "2": "Running"
            };

            switch (status) {
                case -1:
                    statusEl =  '' +
                                    'Failed' +
                                '' +
                                '' +
                                    'Build Failure' +
                                '';
                    break;
                case 0:
                    statusEl = 'Pending';
                    break;
                case 1:
                statusEl =  '' +
                                'Passed' +
                            '' +
                            '' +
                                'Build Passed' +
                            '';
                    break;
                default:
                    statusEl = 'Running';
            }

            return $sce.trustAsHtml(statusEl);
        };

        $scope.getBuildStatus = function(status, timeCompleted) {
            var timeCompletedObj = new Date(timeCompleted),
                buildIconEl = status === 1 ? '' : '',
                buildStatusEl;

            buildStatusEl = 'Build ' + buildIconEl + '' +
                            '' +
                                '' +
                                this.formatTime(timeCompletedObj) +
                            '';

            return $sce.trustAsHtml(buildStatusEl);
        };

        $scope.getBuildDirectories = function(status) {
            var releaseDirEl,
                buildDirEl =    '' +
                                    '' +
                                    'debug' +
                                '';

            if (status > 0)
            {
                releaseDirEl = '' +
                                    '' +
                                    'release' +
                                '';
            }
            else
            {
                releaseDirEl = '' +
                                    '' +
                                    'release' +
                                    'get logs' +
                                '';
            }

            return $sce.trustAsHtml(buildDirEl + releaseDirEl);
        };

        $scope.getTestBuildStatus = function(activity, tests, testType) {
            var testName = testType === 'ut' ? 'Unit Test' : 'Functional Test',
                targetPhase = testType === 'ut' ? 2 : 3,
                buildMetaEl = '',
                buildChartEl = '',
                buildChartLegendEl = '',
                testScore;

            if (activity.status > 0)
            {
                if (activity.phase > (targetPhase - 1))
                {
                    testScore = Math.round(tests.passCount / tests.total * 100) + '%';

                    buildMetaEl = '' +
                                        '' +
                                            testName +
                                            '' +
                                        '' +
                                        '' +
                                            testScore +
                                        '' +
                                    '';

                    buildChartEl = '
' + testScore + '
';

                    buildChartLegendEl = '
' +
                                            '
' + tests.total + '
' +
                                            '
' + (tests.total - tests.passCount) + '
' +
                                            '
' + this.getDuration(tests.duration) + '
' +
                                         '
';
                }
            }
            else
            {
                buildMetaEl = '' +
                                    '' +
                                        testName +
                                        '' +
                                    '' +
                                    '0%'+
                                    '' +
                                        'Status: Can\'t Run' +
                                    '' +
                                '';
            }

            return $sce.trustAsHtml(buildMetaEl + buildChartEl + buildChartLegendEl);
        };

        $scope.getInitialStatusClass = function(status) {
            var statusMap = {
                "-1": "item-fail",
                "0": "item-pending",
                "1": "item-pass",
                "2": "item-active"
            };

            return statusMap[status];
        };

        // Utility Functions.
        $scope.formatTime = function(dateObj) {
            var hh = dateObj.getHours(),
                mm = dateObj.getMinutes(),
                ampm = hh >= 12 ? 'pm' : 'am';

            return hh + ':' + mm + ' ' + ampm;
        };

        $scope.getDuration = function(milliseconds) {
            var sec = Math.round((milliseconds / 1000) % 60),
                min = Math.round((milliseconds / (1000 * 60)) % 60),
                hours = Math.round((milliseconds / (1000 * 60 * 60)) % 24);

            return hours + ':' + min + ':' + sec;
        };

        $scope.initSocket = function() {
            var i;

            socket = io.connect(pageLocation.protocol + '//' + pageLocation.hostname + ':' + socketListenerPort);

            // Invokes build on Server.
            for (i = 1; i <=  $scope.changelistItems.length; i++)
            {
                $timeout(function(changelistId) {
                    socket.emit('triggerbuild', changelistId);
                }, i * 1000, true, $scope.changelistItems[i - 1]._id);
            }

            socket.on('buildstart', function(changelistId, timeStarted) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = $('tr#' + changelistId).find('.progress-steps .buildStep'),
                    changeListItem;

                console.log('Build started for Changelist ', $scope.changelistItems.findChangelist('_id', changelistId).changeListName);

                changeListItem = $scope.changelistItems.findChangelist('_id', changelistId);
                changeListItem.timeStarted = timeStarted;
                changeListItem.activity.status = 2;
                buildStepEl.removeClass('step-pending').addClass('step-active');
                buildStepEl.find('.step-icon').removeClass('step-icon-pending').addClass('step-icon-active');
            });

            socket.on('buildfinished', function(changelistId, status, timeCompleted) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    changeListItem;

                console.log('Build finished for Changelist ', $scope.changelistItems.findChangelist('_id', changelistId).changeListName, ' with status ', status);

                changeListItem = $scope.changelistItems.findChangelist('_id', changelistId);
                changeListItem.activity.phase = 1;
                changeListItem.build.timeCompleted = timeCompleted;

                if (status === 1)
                    buildStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-pass');
                else
                {
                    changeListItem.activity.status = status;
                    buildStepEl.removeClass('step-active').addClass('step-fail');
                    buildStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-fail');
                }
            });

            socket.on('unitteststart', function(changelistId) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep');

                console.log('Unit Tests started for Changelist ', $scope.changelistItems.findChangelist('_id', changelistId).changeListName);

                buildStepEl.addClass('fill-step-progress');
                $timeout(function() {
                    utStepEl.removeClass('step-empty').addClass('step-active');
                    utStepEl.find('.step-icon').addClass('step-icon-active');
                }, 1000);
            });

            socket.on('unittestfinished', function(changelistId, status, timeCompleted, passCount) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep'),
                    changeListItem;

                changeListItem = $scope.changelistItems.findChangelist('_id', changelistId);
                changeListItem.activity.phase = 2;
                changeListItem.unitTest.duration = timeCompleted - changeListItem.timeStarted;
                changeListItem.unitTest.passCount = passCount;
                changeListItem.build.timeCompleted = timeCompleted;

                if (status === 1)
                    utStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-pass');
                else
                {
                    changeListItem.activity.status = status;
                    utStepEl.removeClass('step-active').addClass('step-fail');
                    buildStepEl.removeClass('step-active fill-step-progress').addClass('step-fail fill-step-progress');
                    $timeout(function() {
                        utStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-fail');
                    }, 1000);
                }
            });

            socket.on('functionalteststart', function(changelistId) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep'),
                    ftStepEl = changeListItemEl.find('.progress-steps .ftStep');

                utStepEl.addClass('fill-step-progress');
                $timeout(function() {
                    ftStepEl.removeClass('step-empty').addClass('step-active');
                    ftStepEl.find('.step-icon').addClass('step-icon-active');
                }, 1000);
            });

            socket.on('functionaltestfinished', function(changelistId, status, timeCompleted, passCount) {
                var changeListItemEl = $('tr#' + changelistId),
                    buildStepEl = changeListItemEl.find('.progress-steps .buildStep'),
                    utStepEl = changeListItemEl.find('.progress-steps .utStep'),
                    ftStepEl = changeListItemEl.find('.progress-steps .ftStep'),
                    changeListItem;

                changeListItem = $scope.changelistItems.findChangelist('_id', changelistId);
                changeListItem.activity.status = status;
                changeListItem.activity.phase = 3;
                changeListItem.functionalTest.duration = timeCompleted - changeListItem.timeStarted;
                changeListItem.functionalTest.passCount = passCount;
                changeListItem.build.timeCompleted = timeCompleted;

                if (status === 1)
                {
                    buildStepEl.removeClass('step-active fill-step-progress').addClass('step-pass fill-step-progress');
                    utStepEl.removeClass('step-active fill-step-progress').addClass('step-pass fill-step-progress');
                    ftStepEl.addClass('step-pass');
                    $timeout(function() {
                        ftStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-pass');
                    }, 1000);
                }
                else
                {
                    buildStepEl.removeClass('step-active fill-step-progress').addClass('step-fail fill-step-progress');
                    utStepEl.removeClass('step-active fill-step-progress').addClass('step-fail fill-step-progress');
                    ftStepEl.addClass('step-fail');
                    $timeout(function() {
                        ftStepEl.find('.step-icon').removeClass('step-icon-active').addClass('step-icon-fail');
                    }, 1000);
                }
            });
        };
    }
})();
<|endoftext|>


<commit_before>function	sync_sv()
{
	socket.emit("get seated players");
	socket.on("seated players info", function(seat, seat_idx)
	{
		$("#qr" + seat_idx).css("visibility", "hidden");
		$("#qr_spot" + seat_idx).css("visibility", "hidden");
		$("#scan_msg" + seat_idx).css("visibility", "hidden");
		$("#player_name" + seat_idx).css("visibility", "visible");
		$("#player_name" + seat_idx).text(seat.player.nickname);
		$("#player_bankroll" + seat_idx).css("visibility", "visible");
		$("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ seat_idx).css("visibility", "visible");
	});
	socket.on("new player", function(player)
	{
		$("#qr" + player.seat_nb).css("visibility", "hidden");
		$("#qr_spot" + player.seat_nb).css("visibility", "hidden");
		$("#scan_msg" + player.seat_nb).css("visibility", "hidden");
		$("#player_name" + player.seat_nb).css("visibility", "visible");
		$("#player_name" + player.seat_nb).text(player.nickname);
		$("#player_bankroll" + player.seat_nb).css("visibility", "visible");
		$("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ player.seat_nb).css("visibility", "visible");
	});
	socket.on("kick player", function(seat_nb)
	{
		$("#qr" + seat_nb).css("visibility", "visible");
		$("#qr_spot" + seat_nb).css("visibility", "visible");
		$("#scan_msg" + seat_nb).css("visibility", "visible");
		$("#player_name" + seat_nb).css("visibility", "hidden");
		$("#player_name" + seat_nb).text("");
		$("#player_bankroll" + seat_nb).css("visibility", "hidden");
		$("#player_bankroll" + seat_nb).text("");
		$("#player_cards"+ seat_nb).css("visibility", "hidden");
		$("#btn" + seat_nb).attr("src", "");
		$("#btn" + seat_nb).css("visibility", "hidden");
	});
	socket.emit("ask buttons");
	socket.on("place button", function(type, seat_nb)
	{
		if (seat_nb <= 0 || seat_nb >= 7)
			return ;
		if (type == "dealer")
		{
			$("#btn" + seat_nb).attr("src", "../img/Dealer.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "sb")
		{
			$("#btn" + seat_nb).attr("src", "../img/sb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "bb")
		{
			$("#btn" + seat_nb).attr("src", "../img/bb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("give cards", function(seat_nb)
	{
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("highlights", function(seat_idx, new_state)
	{
		if (new_state == "off")
			$("#seat" + seat_idx).css("background-color", "#006F60");
		else if (new_state == "on")
			$("#seat" + seat_idx).css("background-color", "#FE554C");
	});
	socket.on("bankroll modification", function(seat_idx, player)
	{
		if (player.bankroll == "ALL IN")
			$("#player_bankroll" + seat_idx).text("ALL IN");
		else
			$("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
	});
	socket.on("pot modification", function(pot_amount)
	{
		$("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
	});
	socket.on("bet", function(seat_idx, amount)
	{
		if (!amount)
			$("#bet_val" + seat_idx).text('');
		else {
			$("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
		}
	});

	socket.on("last action", function(decision, seat_nb)
	{
		$("#last_action" + seat_nb).text(decision);
	});
	socket.on("fold", function(seat_nb)
	{
		$("#btn" + seat_nb).css("visibility", "hidden");
		$("#bet_val" + seat_nb).text('');
		$("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
		$("#last_action" + seat_nb).text('');
	});
	socket.emit("get board");
	socket.on("send flop", function(card1, card2, card3)
	{
		$("#b1").attr("src", "img/cards/" + card1 + ".png");
		$("#b2").attr("src", "img/cards/" + card2 + ".png");
		$("#b3").attr("src", "img/cards/" + card3 + ".png");
		$("#b1, #b2, #b3").css("visibility", "visible");
	});
	socket.on("send turn", function(card4)
	{
		$("#b4").attr("src", "img/cards/" + card4 + ".png");
		$("#b4").css("visibility", "visible");
	});
	socket.on("send river", function(card5)
	{
		$("#b5").attr("src", "img/cards/" + card5 + ".png");
		$("#b5").css("visibility", "visible");
	});
	socket.on("remove last actions", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#last_action" + idx).remove();
	});
	socket.on("remove board", function()
	{
		$("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
		for (var idx = 1; idx <= 6; ++idx)
			$("#player_cards" + idx).attr("src", "../img/avatar.png");
	});
	socket.on("remove emplacements", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#btn" + idx).css("visibility", "hidden");
	});
	socket.on("show down", function(card1, card2, seat_nb)
	{
		if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
			$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
			$("#card1_" + seat_nb).css("visibility", "visible");
			$("#card2_" + seat_nb).css("visibility", "visible");
		}
	});
	socket.on("show down off", function(seat_nb)
	{
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
	});
	socket.on("winner", function(seat_nb, rank_name)
	{
		var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
		var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

		if (rank_name == 'disconnected') {
			//$("#winner_msg").text($("#player_name" + seat_nb).text());
			$('#histoContent').empty();
			$('#histoContent').append(disconnect);
		}
		else if (seat_nb == 42 && rank_name == 'null') {
			//$("#winner_msg").text("Split!");
			$('#histoContent').empty();
			$('#histoContent').append('
Split !
');
		}
		else {
			$('#histoContent').empty();
			$('#histoContent').append(won);
		}
		//$("#winner").css("visibility", "visible");
	});
	socket.on("win off", function()
	{
		$("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
	});
}

function	get_table(table_id, tables)
{
	var		idx = 0;

	while (idx < tables.length)
	{
		if (tables[idx].id == table_id)
			return tables[idx];
		++idx;
	}
	return "not found";
}

var id;
var array;
var game;
var newTables;
var push = true;

socket.on('tableId', function(tableId, tables, tableGame){
	id = tableId;
	array = tables;
	game = tableGame;
});

function restart() {
	socket.emit('get tableId and tableGame', id);
	socket.on('give tableId and tableGame', function(tables, tableGame) {
		array = tables;
		game = tableGame;
	});
	console.log(array);
	console.log(game);
//	console.log(array.game);
	push = false;
}
function confirm(){
	push = true;
	socket.emit('get tableId and tableGame', id);
	socket.on('give tableId and tableGame', function(tables, tableGame) {
		array = tables;
		game = tableGame;
	});
	console.log(array);
	console.log(game);
//	socket.emit('re init', get_table(id, array), table.game);
}
<commit_msg>fix log<commit_after>function	sync_sv()
{
	socket.emit("get seated players");
	socket.on("seated players info", function(seat, seat_idx)
	{
		$("#qr" + seat_idx).css("visibility", "hidden");
		$("#qr_spot" + seat_idx).css("visibility", "hidden");
		$("#scan_msg" + seat_idx).css("visibility", "hidden");
		$("#player_name" + seat_idx).css("visibility", "visible");
		$("#player_name" + seat_idx).text(seat.player.nickname);
		$("#player_bankroll" + seat_idx).css("visibility", "visible");
		$("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ seat_idx).css("visibility", "visible");
	});
	socket.on("new player", function(player)
	{
		$("#qr" + player.seat_nb).css("visibility", "hidden");
		$("#qr_spot" + player.seat_nb).css("visibility", "hidden");
		$("#scan_msg" + player.seat_nb).css("visibility", "hidden");
		$("#player_name" + player.seat_nb).css("visibility", "visible");
		$("#player_name" + player.seat_nb).text(player.nickname);
		$("#player_bankroll" + player.seat_nb).css("visibility", "visible");
		$("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
		$("#player_cards"+ player.seat_nb).css("visibility", "visible");
	});
	socket.on("kick player", function(seat_nb)
	{
		$("#qr" + seat_nb).css("visibility", "visible");
		$("#qr_spot" + seat_nb).css("visibility", "visible");
		$("#scan_msg" + seat_nb).css("visibility", "visible");
		$("#player_name" + seat_nb).css("visibility", "hidden");
		$("#player_name" + seat_nb).text("");
		$("#player_bankroll" + seat_nb).css("visibility", "hidden");
		$("#player_bankroll" + seat_nb).text("");
		$("#player_cards"+ seat_nb).css("visibility", "hidden");
		$("#btn" + seat_nb).attr("src", "");
		$("#btn" + seat_nb).css("visibility", "hidden");
	});
	socket.emit("ask buttons");
	socket.on("place button", function(type, seat_nb)
	{
		if (seat_nb <= 0 || seat_nb >= 7)
			return ;
		if (type == "dealer")
		{
			$("#btn" + seat_nb).attr("src", "../img/Dealer.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "sb")
		{
			$("#btn" + seat_nb).attr("src", "../img/sb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		else if (type == "bb")
		{
			$("#btn" + seat_nb).attr("src", "../img/bb.png")
			$("#btn" + seat_nb).css("visibility", "visible");
		}
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("give cards", function(seat_nb)
	{
		$("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
	});
	socket.on("highlights", function(seat_idx, new_state)
	{
		if (new_state == "off")
			$("#seat" + seat_idx).css("background-color", "#006F60");
		else if (new_state == "on")
			$("#seat" + seat_idx).css("background-color", "#FE554C");
	});
	socket.on("bankroll modification", function(seat_idx, player)
	{
		if (player.bankroll == "ALL IN")
			$("#player_bankroll" + seat_idx).text("ALL IN");
		else
			$("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
	});
	socket.on("pot modification", function(pot_amount)
	{
		$("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
	});
	socket.on("bet", function(seat_idx, amount)
	{
		if (!amount)
			$("#bet_val" + seat_idx).text('');
		else {
			$("#bet_val" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
		}
	});

	socket.on("last action", function(decision, seat_nb)
	{
		$("#last_action" + seat_nb).text(decision);
	});
	socket.on("fold", function(seat_nb)
	{
		$("#btn" + seat_nb).css("visibility", "hidden");
		$("#bet_val" + seat_nb).text('');
		$("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
		$("#last_action" + seat_nb).text('');
	});
	socket.emit("get board");
	socket.on("send flop", function(card1, card2, card3)
	{
		$("#b1").attr("src", "img/cards/" + card1 + ".png");
		$("#b2").attr("src", "img/cards/" + card2 + ".png");
		$("#b3").attr("src", "img/cards/" + card3 + ".png");
		$("#b1, #b2, #b3").css("visibility", "visible");
	});
	socket.on("send turn", function(card4)
	{
		$("#b4").attr("src", "img/cards/" + card4 + ".png");
		$("#b4").css("visibility", "visible");
	});
	socket.on("send river", function(card5)
	{
		$("#b5").attr("src", "img/cards/" + card5 + ".png");
		$("#b5").css("visibility", "visible");
	});
	socket.on("remove last actions", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#last_action" + idx).remove();
	});
	socket.on("remove board", function()
	{
		$("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
		for (var idx = 1; idx <= 6; ++idx)
			$("#player_cards" + idx).attr("src", "../img/avatar.png");
	});
	socket.on("remove emplacements", function()
	{
		for (var idx = 1; idx <= 6; ++idx)
			$("#btn" + idx).css("visibility", "hidden");
	});
	socket.on("show down", function(card1, card2, seat_nb)
	{
		if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
			$("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
			$("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
			$("#card1_" + seat_nb).css("visibility", "visible");
			$("#card2_" + seat_nb).css("visibility", "visible");
		}
	});
	socket.on("show down off", function(seat_nb)
	{
		$("#card1_" + seat_nb).css("visibility", "hidden");
		$("#card2_" + seat_nb).css("visibility", "hidden");
	});
	socket.on("winner", function(seat_nb, rank_name)
	{
		var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
		var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

		if (rank_name == 'disconnected') {
			//$("#winner_msg").text($("#player_name" + seat_nb).text());
			$('#histoContent').empty();
			$('#histoContent').append(disconnect);
		}
		else if (seat_nb == 42 && rank_name == 'null') {
			//$("#winner_msg").text("Split!");
			$('#histoContent').empty();
			$('#histoContent').append('
Split !
');
		}
		else {
			$('#histoContent').empty();
			$('#histoContent').append(won);
		}
		//$("#winner").css("visibility", "visible");
	});
	socket.on("win off", function()
	{
		$("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
	});
}

function	get_table(table_id, tables)
{
	var		idx = 0;

	while (idx < tables.length)
	{
		if (tables[idx].id == table_id)
			return tables[idx];
		++idx;
	}
	return "not found";
}

var id;
var array;
var game;
var newTables;
var push = true;

socket.on('tableId', function(tableId, tables, tableGame){
	id = tableId;
	array = tables;
	game = tableGame;
});

function restart() {
	socket.emit('get tableId and tableGame', id);
	socket.on('give tableId and tableGame', function(tables, tableGame) {
		array = tables;
		game = tableGame;
	});
	array = get_table(id,array)
	console.log(array);
	console.log(array.game);
//	console.log(array.game);
	push = false;
}
function confirm(){
	push = true;
	socket.emit('get tableId and tableGame', id);
	socket.on('give tableId and tableGame', function(tables, tableGame) {
		array = tables;
		game = tableGame;
	});
	array = get_table(id,array)
	console.log(array);
	console.log(array.game);
//	socket.emit('re init', get_table(id, array), table.game);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var platformId = cordova.require('cordova/platform').id;
var exec = cordova.require('cordova/exec');

// Generate a failure function.
//
// The chrome.fileSystem API generally signals failure through the
// chrome.runtime.lastError object, and calls the single callback
// function regardless of whether the API call succeeded or not.
function fail(errorMessage, callback) {
  return function() {
    console.log(errorMessage);
    chrome.runtime.lastError = { 'message': errorMessage };
    callback && callback();
  }
}

exports.getDisplayPath = function(fileEntry, callback) {
  callback(fileEntry.fullPath);
};

exports.getWritableEntry = function(fileEntry, callback) {
  //TODO: Check whether fileEntry is / can be writable. (Chrome does not do this)
  //TODO: Check whether this is required to return a new FileEntry object
  tagFileEntryWritable(fileEntry, true);
  callback && callback(fileEntry);
};

exports.isWritableEntry = function(fileEntry, callback) {
  //TODO: Check whether fileEntry is / can be writable. (Chrome does not do this)
  callback && callback(fileEntry.__chrome_is_writable);
};

function tagFileEntryWritable(fileEntry, isWritable) {
  Object.defineProperty(fileEntry, '__chrome_is_writable', {
    value: isWritable,
    writable: false
  });
}

exports.chooseEntry = function(options, callback) {
  // Ensure that the type is either unspecified or one of the valid values
  if (options.type && options.type != 'openFile' &&
                      options.type != 'openWritableFile' &&
                      options.type != 'saveFile') {
    fail("Unsupported type for chooseEntry", callback);
    return;
  }

  if (platformId == 'ios') {
    getFileIos(options, callback);
  } else if (platformId == 'android') {
    getFileAndroid(options, callback);
  }
};

function getFileIos(options, callback) {
//  // Determine the media type.
//  var mediaType = determineMediaType(options.accepts, options.acceptsAllTypes);
//
//  // Prepare the options for getting the file.
//  var getFileOptions = { destinationType: navigator.camera.DestinationType.NATIVE_URI,
//                         sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
//                         mediaType: mediaType };
//
//  // Use the camera to get an image or video.
//  navigator.camera.getPicture(onFileReceivedCallback, null, getFileOptions);

  var onFileDetailsReceived = function(fileDetails) {
    // file details will be populated if the user selected a file, and false if
    // the user cancelled.
    if (!fileDetails) {
      fail('User cancelled', callback);
    } else {
      resolveLocalFileSystemURI(fileDetails.pathuri, function(dirEntry) {
        dirEntry.getFile(fileDetails.file, {create: options.type === 'saveFile'}, function(fileEntry) {
          // Set the writable bit and execute the callback
          tagFileEntryWritable(fileEntry, (options.type !== 'openFile'));
          callback && callback(fileEntry);
        }, fail("Unable to open file", callback));
      }, fail("Unable to open file", callback));
    }
  }

  fileChooserOptions = {
    title: options.type === 'saveFile' ? "Save File" : "Open File",
    canCreate: options.type === 'saveFile',
    needWritable: options.type !== 'openFile',
    includeTextInput: options.type === 'saveFile',
    accepts: options.accepts,
    acceptsAllTypes: !!(options.acceptsAllTypes) || !options.accepts || (options.accepts.length === 0)
  }
  exec(onFileDetailsReceived, fail("Error choosing file", callback), "ChromeFileSystem", "chooseEntry", [fileChooserOptions]);
}

function getFileAndroid(options, callback) {
  var AndroidFileChooser = cordova.require('org.chromium.FileChooser.FileChooser');

  // Determine the relevant mime types.
  var mimeTypes = determineMimeTypes(options.accepts, options.acceptsAllTypes);

  // Create the callback for getFile.
  // It creates a file entry and passes it to the chooseEntry callback.
  var onFileReceived = function(nativeUri) {

    var onUriResolveError = function(error) {
      fail(error.code);
    };

    if (!chrome.runtime.lastError) {
      resolveLocalFileSystemURL(nativeUri, callback, onUriResolveError);
    } else {
      callback && callback();
    }
  };

  // Use the file chooser to get a file.
  AndroidFileChooser.chooseFile(onFileReceived, null, [ mimeTypes ]);
}

function determineMediaType(acceptOptions, acceptsAllTypes) {
  if (acceptsAllTypes) {
    return navigator.camera.MediaType.ALLMEDIA;
  }

  var imageMimeTypeRegex = /^image\//;
  var videoMimeTypeRegex = /^video\//;
  var imageExtensionRegex = /^(?:jpg|png)$/;
  var videoExtensionRegex = /^mov$/;
  var imagesAllowed = false;
  var videosAllowed = false;

  // Iterate through all accept options.
  // If we see anything image related, allow images.  If we see anything video related, allow videos.
  if (acceptOptions) {
    for (var i = 0; i < acceptOptions.length; i++) {
      if (acceptOptions[i].mimeTypes) {
        for (var j = 0; j < acceptOptions[i].mimeTypes.length; j++) {
          if (imageMimeTypeRegex.test(acceptOptions[i].mimeTypes[j])) {
            imagesAllowed = true;
          } else if (videoMimeTypeRegex.test(acceptOptions[i].mimeTypes[j])) {
            videosAllowed = true;
          }
        }
      }
      if (acceptOptions[i].extensions) {
        for (var k = 0; k < acceptOptions[i].extensions.length; k++) {
          if (imageExtensionRegex.test(acceptOptions[i].extensions[k])) {
            imagesAllowed = true;
          } else if (videoExtensionRegex.test(acceptOptions[i].extensions[k])) {
            videosAllowed = true;
          }
        }
      }
    }
  }

  if (imagesAllowed && !videosAllowed) {
    return navigator.camera.MediaType.PICTURE;
  } else if (!imagesAllowed && videosAllowed) {
    return navigator.camera.MediaType.VIDEO;
  }

  return navigator.camera.MediaType.ALLMEDIA;
}

function determineMimeTypes(acceptOptions, acceptsAllTypes) {
  if (acceptsAllTypes) {
    return [ '*/*' ];
  }

  // Pull out all the mime types.
  // TODO(maxw): Determine mime types from extensions and add them to the returned list.
  var mimeTypes = [ ];
  if (acceptOptions) {
    for (var i = 0; i < acceptOptions.length; i++) {
      if (acceptOptions[i].mimeTypes) {
        for (var j = 0; j < acceptOptions[i].mimeTypes.length; j++) {
          mimeTypes.push(acceptOptions[i].mimeTypes[j]);
        }
      }
    }
  }

  if (mimeTypes.length !== 0) {
    return mimeTypes;
  }

  return [ '*/*' ];
}
<commit_msg>Switch to org.chromium.filechooser<commit_after>// Copyright (c) 2012, 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var platformId = cordova.require('cordova/platform').id;
var exec = cordova.require('cordova/exec');

// Generate a failure function.
//
// The chrome.fileSystem API generally signals failure through the
// chrome.runtime.lastError object, and calls the single callback
// function regardless of whether the API call succeeded or not.
function fail(errorMessage, callback) {
  return function() {
    console.log(errorMessage);
    chrome.runtime.lastError = { 'message': errorMessage };
    callback && callback();
  }
}

exports.getDisplayPath = function(fileEntry, callback) {
  callback(fileEntry.fullPath);
};

exports.getWritableEntry = function(fileEntry, callback) {
  //TODO: Check whether fileEntry is / can be writable. (Chrome does not do this)
  //TODO: Check whether this is required to return a new FileEntry object
  tagFileEntryWritable(fileEntry, true);
  callback && callback(fileEntry);
};

exports.isWritableEntry = function(fileEntry, callback) {
  //TODO: Check whether fileEntry is / can be writable. (Chrome does not do this)
  callback && callback(fileEntry.__chrome_is_writable);
};

function tagFileEntryWritable(fileEntry, isWritable) {
  Object.defineProperty(fileEntry, '__chrome_is_writable', {
    value: isWritable,
    writable: false
  });
}

exports.chooseEntry = function(options, callback) {
  // Ensure that the type is either unspecified or one of the valid values
  if (options.type && options.type != 'openFile' &&
                      options.type != 'openWritableFile' &&
                      options.type != 'saveFile') {
    fail("Unsupported type for chooseEntry", callback);
    return;
  }

  if (platformId == 'ios') {
    getFileIos(options, callback);
  } else if (platformId == 'android') {
    getFileAndroid(options, callback);
  }
};

function getFileIos(options, callback) {
//  // Determine the media type.
//  var mediaType = determineMediaType(options.accepts, options.acceptsAllTypes);
//
//  // Prepare the options for getting the file.
//  var getFileOptions = { destinationType: navigator.camera.DestinationType.NATIVE_URI,
//                         sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
//                         mediaType: mediaType };
//
//  // Use the camera to get an image or video.
//  navigator.camera.getPicture(onFileReceivedCallback, null, getFileOptions);

  var onFileDetailsReceived = function(fileDetails) {
    // file details will be populated if the user selected a file, and false if
    // the user cancelled.
    if (!fileDetails) {
      fail('User cancelled', callback);
    } else {
      resolveLocalFileSystemURI(fileDetails.pathuri, function(dirEntry) {
        dirEntry.getFile(fileDetails.file, {create: options.type === 'saveFile'}, function(fileEntry) {
          // Set the writable bit and execute the callback
          tagFileEntryWritable(fileEntry, (options.type !== 'openFile'));
          callback && callback(fileEntry);
        }, fail("Unable to open file", callback));
      }, fail("Unable to open file", callback));
    }
  }

  fileChooserOptions = {
    title: options.type === 'saveFile' ? "Save File" : "Open File",
    canCreate: options.type === 'saveFile',
    needWritable: options.type !== 'openFile',
    includeTextInput: options.type === 'saveFile',
    accepts: options.accepts,
    acceptsAllTypes: !!(options.acceptsAllTypes) || !options.accepts || (options.accepts.length === 0)
  }
  exec(onFileDetailsReceived, fail("Error choosing file", callback), "ChromeFileSystem", "chooseEntry", [fileChooserOptions]);
}

function getFileAndroid(options, callback) {
  var AndroidFileChooser = cordova.require('org.chromium.filechooser.FileChooser');

  // Determine the relevant mime types.
  var mimeTypes = determineMimeTypes(options.accepts, options.acceptsAllTypes);

  // Create the callback for getFile.
  // It creates a file entry and passes it to the chooseEntry callback.
  var onFileReceived = function(nativeUri) {

    var onUriResolveError = function(error) {
      fail(error.code);
    };

    if (!chrome.runtime.lastError) {
      resolveLocalFileSystemURL(nativeUri, callback, onUriResolveError);
    } else {
      callback && callback();
    }
  };

  // Use the file chooser to get a file.
  AndroidFileChooser.chooseFile(onFileReceived, null, [ mimeTypes ]);
}

function determineMediaType(acceptOptions, acceptsAllTypes) {
  if (acceptsAllTypes) {
    return navigator.camera.MediaType.ALLMEDIA;
  }

  var imageMimeTypeRegex = /^image\//;
  var videoMimeTypeRegex = /^video\//;
  var imageExtensionRegex = /^(?:jpg|png)$/;
  var videoExtensionRegex = /^mov$/;
  var imagesAllowed = false;
  var videosAllowed = false;

  // Iterate through all accept options.
  // If we see anything image related, allow images.  If we see anything video related, allow videos.
  if (acceptOptions) {
    for (var i = 0; i < acceptOptions.length; i++) {
      if (acceptOptions[i].mimeTypes) {
        for (var j = 0; j < acceptOptions[i].mimeTypes.length; j++) {
          if (imageMimeTypeRegex.test(acceptOptions[i].mimeTypes[j])) {
            imagesAllowed = true;
          } else if (videoMimeTypeRegex.test(acceptOptions[i].mimeTypes[j])) {
            videosAllowed = true;
          }
        }
      }
      if (acceptOptions[i].extensions) {
        for (var k = 0; k < acceptOptions[i].extensions.length; k++) {
          if (imageExtensionRegex.test(acceptOptions[i].extensions[k])) {
            imagesAllowed = true;
          } else if (videoExtensionRegex.test(acceptOptions[i].extensions[k])) {
            videosAllowed = true;
          }
        }
      }
    }
  }

  if (imagesAllowed && !videosAllowed) {
    return navigator.camera.MediaType.PICTURE;
  } else if (!imagesAllowed && videosAllowed) {
    return navigator.camera.MediaType.VIDEO;
  }

  return navigator.camera.MediaType.ALLMEDIA;
}

function determineMimeTypes(acceptOptions, acceptsAllTypes) {
  if (acceptsAllTypes) {
    return [ '*/*' ];
  }

  // Pull out all the mime types.
  // TODO(maxw): Determine mime types from extensions and add them to the returned list.
  var mimeTypes = [ ];
  if (acceptOptions) {
    for (var i = 0; i < acceptOptions.length; i++) {
      if (acceptOptions[i].mimeTypes) {
        for (var j = 0; j < acceptOptions[i].mimeTypes.length; j++) {
          mimeTypes.push(acceptOptions[i].mimeTypes[j]);
        }
      }
    }
  }

  if (mimeTypes.length !== 0) {
    return mimeTypes;
  }

  return [ '*/*' ];
}
<|endoftext|>


<commit_before>'use strict';

/**
 * CDS Pipe Tool main module
 *
 * @author David Taieb
 */

var express = require('express');
var fs = require('fs');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require("express-session");
var errorHandler = require('errorhandler');
var morgan = require('morgan');
var bluemixHelperConfig = require('bluemix-helper-config');
var global = bluemixHelperConfig.global;
var configManager = bluemixHelperConfig.configManager;

var sdpLog = require('simple-data-pipe-sdk').logging.getLogger('sdp_common');
//var sdpLog = require('./server/logging/sdpLogger.js').getLogger('sdp_common');

var VCAP_APPLICATION = JSON.parse(process.env.VCAP_APPLICATION || "{}");
var VCAP_SERVICES = JSON.parse(process.env.VCAP_SERVICES || "{}");

var app = global.app = express();

sdpLog.info('Simple Data Pipe is initializing.');

//Enforce https on Bluemix
app.use( function( req, res, next ){
	if ( req.headers && req.headers.$wssc === 'http'){
		sdpLog.info("Automatically redirecting to https...");
		return res.redirect('https://' + req.get('host') + req.url);
	}
	return next();
});

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(errorHandler({ dumpExceptions:true, showStack:true }));

app.use(expressSession({
	secret: "simple_data_pipe"
}));

var env = app.get('env');
if ('production' === env) {
	app.use(morgan('dev'));
}

if ('development' === env || 'test' === env) {
	app.use(morgan('dev'));
	app.use(errorHandler()); // Error handler - has to be last
}

var port = process.env.VCAP_APP_PORT || configManager.get("DEV_PORT") || 443
if (!process.env.VCAP_APP_HOST){
	//Running locally. Salesforce requires authCallbacks to use SSL by default
	global.appHost = "https://127.0.0.1";
	global.appPort = port;
}

//Configure security if we are bound to an SSO service
var ssoService = bluemixHelperConfig.vcapServices.getService( "pipes-sso" );
if ( ssoService ){
	sdpLog.info("Security is enabled.");
	require('bluemix-helper-sso')(app, {
		ssoService: ssoService,
		relaxedUrls:[
		    "/js", "/img", "/css", "/bower_components", "templates"
		],
		createSessionStore: function( session ){
			//Create a session store based on redis if available, if not, use the default in-memory store
			var redisService = bluemixHelperConfig.vcapServices.getService("pipes-redis");
			if ( redisService ){
				var redisStore = require('connect-redis')(session);
				return new redisStore({
					host: redisService.credentials.hostname,
					port: redisService.credentials.port,
					pass: redisService.credentials.password
				});
			}
			return null;
		}
	});
}else{
	app.get("/userid", function( req, res, next ){
		res.status(200).end();
	})
}

app.use(express.static(path.join(__dirname, 'app')));

//Configure the endpoints
require("./server/connectorAPI").initEndPoints(app);	//Pipe connector API
var wssConfigurator = require("./server/pipeAPI")(app);	//Pipe configuration

var connected = function() {
	sdpLog.info('Simple Data Pipe application started on port %s : %s', port, Date(Date.now()));
};

var options = {
  key: fs.readFileSync('development/certs/server/my-server.key.pem'),
  cert: fs.readFileSync('development/certs/server/my-server.crt.pem')
};

var server = null;
if (process.env.VCAP_APP_HOST){
	server = require('http').createServer(app);
	server.listen(port,
                 process.env.VCAP_APP_HOST,
                 connected);
}else{
	server = require('https').createServer(options, app);
	server.listen(port,connected);
}

if ( wssConfigurator && server ){
	wssConfigurator( server );
}

require("cf-deployment-tracker-client").track();
<commit_msg>i41 use 8082 as default port<commit_after>'use strict';

/**
 * CDS Pipe Tool main module
 *
 * @author David Taieb
 */

var express = require('express');
var fs = require('fs');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require("express-session");
var errorHandler = require('errorhandler');
var morgan = require('morgan');
var bluemixHelperConfig = require('bluemix-helper-config');
var global = bluemixHelperConfig.global;
var configManager = bluemixHelperConfig.configManager;

var sdpLog = require('simple-data-pipe-sdk').logging.getLogger('sdp_common');
//var sdpLog = require('./server/logging/sdpLogger.js').getLogger('sdp_common');

var VCAP_APPLICATION = JSON.parse(process.env.VCAP_APPLICATION || "{}");
var VCAP_SERVICES = JSON.parse(process.env.VCAP_SERVICES || "{}");

var app = global.app = express();

sdpLog.info('Simple Data Pipe is initializing.');

//Enforce https on Bluemix
app.use( function( req, res, next ){
	if ( req.headers && req.headers.$wssc === 'http'){
		sdpLog.info("Automatically redirecting to https...");
		return res.redirect('https://' + req.get('host') + req.url);
	}
	return next();
});

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(errorHandler({ dumpExceptions:true, showStack:true }));

app.use(expressSession({
	secret: "simple_data_pipe"
}));

var env = app.get('env');
if ('production' === env) {
	app.use(morgan('dev'));
}

if ('development' === env || 'test' === env) {
	app.use(morgan('dev'));
	app.use(errorHandler()); // Error handler - has to be last
}

var port = process.env.VCAP_APP_PORT || configManager.get("DEV_PORT") || 8082;
if (!process.env.VCAP_APP_HOST){
	//Running locally. Salesforce requires authCallbacks to use SSL by default
	global.appHost = "https://127.0.0.1";
	global.appPort = port;
}

//Configure security if we are bound to an SSO service
var ssoService = bluemixHelperConfig.vcapServices.getService( "pipes-sso" );
if ( ssoService ){
	sdpLog.info("Security is enabled.");
	require('bluemix-helper-sso')(app, {
		ssoService: ssoService,
		relaxedUrls:[
		    "/js", "/img", "/css", "/bower_components", "templates"
		],
		createSessionStore: function( session ){
			//Create a session store based on redis if available, if not, use the default in-memory store
			var redisService = bluemixHelperConfig.vcapServices.getService("pipes-redis");
			if ( redisService ){
				var redisStore = require('connect-redis')(session);
				return new redisStore({
					host: redisService.credentials.hostname,
					port: redisService.credentials.port,
					pass: redisService.credentials.password
				});
			}
			return null;
		}
	});
}else{
	app.get("/userid", function( req, res, next ){
		res.status(200).end();
	})
}

app.use(express.static(path.join(__dirname, 'app')));

//Configure the endpoints
require("./server/connectorAPI").initEndPoints(app);	//Pipe connector API
var wssConfigurator = require("./server/pipeAPI")(app);	//Pipe configuration

var connected = function() {
	sdpLog.info('Simple Data Pipe application started on port %s : %s', port, Date(Date.now()));
};

var options = {
  key: fs.readFileSync('development/certs/server/my-server.key.pem'),
  cert: fs.readFileSync('development/certs/server/my-server.crt.pem')
};

var server = null;
if (process.env.VCAP_APP_HOST){
	server = require('http').createServer(app);
	server.listen(port,
                 process.env.VCAP_APP_HOST,
                 connected);
}else{
	server = require('https').createServer(options, app);
	server.listen(port,connected);
}

if ( wssConfigurator && server ){
	wssConfigurator( server );
}

require("cf-deployment-tracker-client").track();
<|endoftext|>