<commit_before>/**
 *
 * check of bank and card
 *
 *
 *
 * 20150617
 */

function Log(msg){
	msg = msg || 'empty';
	if(envirment=="production"){

	} else {
		console.log(msg);
	}

}

(function($, undefined){
	//生产类
	var Pub = function(el, op){
		this.$el = $(el);

		this.boxFlag = 0;//标志卡号合法之后，下面层出现与否
		this.iFlag = 1;//标志所有数据合法时，提交按钮提交次数
		this.nameInput = this.$el.find('[node-type="LoanNameInput"]');
		this.cardInput = this.$el.find('[node-type="LoanCardInput"]');
		this.submitBtn = this.$el.find('[node-type="LoanSubmitBtn"]');
		this.bankCardIcon = this.$el.find('[node-type="LoanBankCardIcon"]');
		this.idCardInput = this.$el.find('[node-type="LoanIdCardInput"]');
		this.mobileIcon = this.$el.find('[node-type="LoanMobileIcon"]');
		this.mobileInput = this.$el.find('[node-type="LoanMobileInput"]');
		this.agreement = $("#agreement-btn");
		this.agreeClose = $("#close10");
		this.agree= $("#agreement");
		this.imbox = $("#imbox");
		this.bankName = $("#bank_name");
		this.mask = $("#masker");
		this.iconOption = $(".icon-option");
		this._addEvents();
	}

	Pub.prototype = {
		//所有事件绑定
		_addEvents : function(){
			var sthis=this;

			/*判断信息完整*/
			this.$el.find("input").on("input", function(){
				var _this = this;
				/*Log('AAA');*/
				setTimeout(function(){
					sthis._fnComplete();
					var Id = $(_this).attr("id");
					if(Id=="ID_card"){
						var idCard_val = $(_this).val();
						_this.value = sthis._fnIdentity(idCard_val);
					}
				},500)
			})

			/*卡号输入判断*/
			this.cardInput.on("keyup", function(){
				var card_id=this.value;
				this.value=sthis._fnCard(card_id);
			})
			/*身份证号输入判断*/
			this.idCardInput.on("keyup", function(){
				var idCard_val = this.value;
				this.value = sthis._fnIdentity(idCard_val);
				if(this.value==0){
					$(this).siblings().hide();
				}else{
					$(this).siblings().show();
				}
			})
			/*icon单机操作*/
			this.$el.find(".icon-option").on("click", function(){
				var icon_this=this;
				sthis._fnIcon(icon_this);
			})

			/*失去焦点隐藏icon*/
			this.$el.find("input").on("focus", function(){
				sthis.iconOption.hide();
				if(this.id=="ID_card"){
					if(this.value.length > 1){
						$(this).siblings().show();
					}
				}else{
					$(this).siblings().show();
				}
			})
			/*手机号输入判断*/
			this.mobileInput.on("keyup",function(){
				var mobile_val = this.value;
				this.value = sthis._fnModile(mobile_val);
			})

			/*提交按钮*/
			this.submitBtn.on("click",function(){

				var zCard = $("#bank_card").val();
				var zIdCard = $("#ID_card").val();
				var zMobile = $("#mobile").val();
				var zName = $("#name").val();
				sthis._fnSubmit(zCard,zIdCard,zMobile,zName);

			})
			/*协议*/
			this.agreement.on("click",function(){
				var wheight = $(window).height();
					wwidth = $(window).width();
					agreeList = $("#agree_list");

				/*sthis.agree.css("left",-wwidth);*/
				agreeList.height(wheight/6*4);
				sthis.agree.css("top",wheight/8);
				sthis._fnGetAgree();
				sthis.mask.show();
				sthis.agree.show();
				sthis.agree.css("left",0);
			})

			this.agreeClose.on("click",function(){
				sthis.mask.hide();
				sthis.agree.hide();
			})

		},
		//卡号处理
		_fnCard : function(card_id){
			card_id = card_id.replace(/\D/g,'').replace(/....(?!$)/g,'$& ');
			var b_len = card_id.length,
				bRIcon = $("#bRIcon");
			if(b_len==0){
				bRIcon.addClass("active").show().siblings().hide();
				this.imbox.hide();
				this.bankName.hide();
			}else if(b_len==1){
				bRIcon.removeClass("active").hide().siblings().show().removeClass("active");
			}else if(b_len==18){

			}else if(b_len==19){
				var bank_type=TOOLS.isBank(card_id.replace(/\s+/g,""));
				if(bank_type){
					this.boxFlag=1;
					this.imbox.show();
				}
			}else if(b_len<12){
				this.imbox.hide();
				this.boxFlag=0;
				this.bankName.hide();
			}else if(b_len>=12){
				var bank_type=TOOLS.isBank(card_id.replace(/\s+/g,""));
				if(bank_type){
					this.bankName.find("span").removeClass();
					this.bankName.find("span").addClass("bankName "+bank_type);
					this.bankName.show();

				}
			}
			return card_id;
		},
		//身份证处理
		_fnIdentity : function(idCard_val){
			idCard_val=idCard_val.replace(/[^\d|xX]/g,"");
			return idCard_val;
		},
		//手机号验证
		_fnModile : function(mobile_val){
			mobile_val = mobile_val.replace(/\D/g,'');
			var m_len = mobile_val.length;
				mRIcon = $("#mRIcon");

			if(m_len==0){
				mRIcon.addClass("active").show().siblings().hide();
			}else if(m_len==1){
				mRIcon.removeClass("active").hide().siblings().show().removeClass("active");
			}

			return mobile_val;
		},
		//表单处理
		_fnComplete : function(){
			var ipt=this.$el.find("input"),
				next=$("#next2"),
				ipt_flag=1,
				ipt_len=4;

			if(this.boxFlag==0){
				ipt_len=2;
			}
			for(var i=0; i<ipt_len; i++){
				if(ipt[i].value.length == 0){
					ipt_flag=0;
				}
			}
			if(ipt_flag==1){
				next.removeAttr("disabled");
			}else{
				next.attr("disabled","disabled");
			}
		},
		//icon处理
		_fnIcon : function(icon_this){
			var intype = $(icon_this).attr("node-type");
			var inIs = $(icon_this).find("i");
			var inIsD = $(inIs[0]).css("display");
			var next=$("#next2");
			if(inIs.hasClass("icons-infoNew active")){
				if(inIs.is(".icons-infoNew") && intype=="bank_card"){
					MessageBox.alert({type:"message",txt:CS.ERRORMSG["EFFECTIVEBANK"]});
				}else{
					MessageBox.alert({type:"message",txt:CS.ERRORMSG["AVAILABLEPHONENUMBER"]});
				}
			}else{
				if(inIs.is(".icons-infoNew")){
					$('#'+intype).val("");
					$(inIs[0]).addClass("active").show();
					$(inIs[1]).hide();
					if(intype=="bank_card"){
						this.imbox.hide();
						this.bankName.hide();
						this.idCardInput.val("");
						this.mobileInput.val("");
					}
					next.attr("disabled","disabled");
				}else{
					$('#'+intype).val("");
					$(inIs[0]).parent().hide();
					next.attr("disabled","disabled");
				}
			}
		},

		/*获取协议*/
		_fnGetAgree : function(){
			var now = new Date();
				year = now.getFullYear();
				month = now.getMonth()+1;
				day = now.getDate();
				name = $("#name").val();
				id_card = $("#ID_card").val();
				bank_card = $("#bank_card").val();
			$("#year").html(year);
			$("#year1").html(year);
			$("#month").html(month);
			$("#month1").html(month);
			$("#day").html(day);
			$("#day1").html(day);
			$("#c_id").html(id_card);
			$("#c_bid").html(bank_card);
			$("#c_name").html(name);
		},

		//提交按钮处理
		_fnSubmit : function(zCard,zIdCard,zMobile,zName){
			var zCard_len = zCard.length,
				age = TOOLS.isIdentity(zIdCard),
				phone = TOOLS.isMobile(zMobile),
				bcflag = TOOLS.isCard(zCard.replace(/\s+/g,"")),
				bcflag2 = TOOLS.isBank(zCard.replace(/\s+/g,"")),
				zzCard = zCard.replace(/\s+/g,""),
				smBtn = $("#next2");

			if(this.boxFlag){
				if(zCard_len != 19 && zCard_len == 23 || zCard_len != 23 && zCard_len == 19){
					if(bcflag){
						if(age){
							if(age>30 || age<16){
								MessageBox.alert({type:"common",txt:CS.ERRORMSG["AGENOTRANGEERROR"]});
							}else{
								if(phone){
									/*提交*/
									if(smBtn.hasClass("disabled")) return false;
									smBtn.addClass('disabled');
									TOOLS.ajax({
										url:"./index.php?r=loan/verify",
										data:{name:zName,bank_card:zzCard,id_card:zIdCard,mobile:zMobile},
										dataType:"json",
										type:"get",
										fnSuccess:function(data){
											if(data.stat == "1"){
												window.location= "./index.php?r=loan/sms&mobile="+data.mobile;
											}else if(data.stat == "2"){
												if(data.verify_times == "2"){
													MessageBox.alert({type:"message",txt:CS.ERRORMSG["TWOCHANCE"],cls:true});
													smBtn.removeClass("disabled");
												}else if(data.verify_times == "1"){
													MessageBox.alert({type:"message",txt:CS.ERRORMSG["ONECHANCE"],cls:true});
													smBtn.removeClass("disabled");
												}else if(data.verify_times == "0"){
													alert("没机会了");
												}
											}else{
												alert("系统错误");
											}

										},
										fnError:function(){}
									});

								}else{
									MessageBox.alert({type:"common",txt:CS.ERRORMSG["MOBILEERROR"]});
								}
							}
						}else{
							MessageBox.alert({type:"common",txt:CS.ERRORMSG["IDENTITYERROR"]});
						}
					}else{
						MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
					}

				}else{
					MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
				}
			}else{
				if(zCard_len != 19 && zCard_len == 23 || zCard_len != 23 && zCard_len == 19){
					if(bcflag){
						if(bcflag2){
						}else{
							MessageBox.alert({type:"common",txt:CS.ERRORMSG["NOBANKERROR"]});
						}
					}else{
						MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
					}
				}else{
					MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
				}
			}

		}
	}

	$.fn.PUB = function(options){
		return this.each(function(){
			var $this = $(this) ,
				data = $this.data('PUB');

	          if (!data) {
	        	  $this.data('PUB', (data = new Pub(this, options)))
	          }

	          if (typeof options == 'string') data[options](setData);
		});
	}
})(window.jQuery||window.Zepto)
<commit_msg>update<commit_after>/**
 *
 * check of bank and card
 *
 *
 *
 * 20150617
 */

function Log(msg){
	msg = msg || 'empty';
	if(envirment=="production"){

	} else {
		console.log(msg);
	}

}

(function($, undefined){
	//生产类
	var Pub = function(el, op){
		this.$el = $(el);

		this.boxFlag = 0;//标志卡号合法之后，下面层出现与否
		this.iFlag = 1;//标志所有数据合法时，提交按钮提交次数
		this.nameInput = this.$el.find('[node-type="LoanNameInput"]');
		this.cardInput = this.$el.find('[node-type="LoanCardInput"]');
		this.submitBtn = this.$el.find('[node-type="LoanSubmitBtn"]');
		this.bankCardIcon = this.$el.find('[node-type="LoanBankCardIcon"]');
		this.idCardInput = this.$el.find('[node-type="LoanIdCardInput"]');
		this.mobileIcon = this.$el.find('[node-type="LoanMobileIcon"]');
		this.mobileInput = this.$el.find('[node-type="LoanMobileInput"]');
		this.agreement = $("#agreement-btn");
		this.agreeClose = $("#close10");
		this.agree= $("#agreement");
		this.imbox = $("#imbox");
		this.bankName = $("#bank_name");
		this.mask = $("#masker");
		this.iconOption = $(".icon-option");
		this._addEvents();
	}

	Pub.prototype = {
		//所有事件绑定
		_addEvents : function(){
			var sthis=this;

			/*判断信息完整*/
			this.$el.find("input").on("input", function(){
				var _this = this;
				/*Log('AAA');*/
				setTimeout(function(){
					sthis._fnComplete();
					var Id = $(_this).attr("id");
					if(Id=="ID_card"){
						var idCard_val = $(_this).val();
						_this.value = sthis._fnIdentity(idCard_val);
					}
				},500)
			})

			/*卡号输入判断*/
			this.cardInput.on("keyup", function(){
				var card_id=this.value;
				this.value=sthis._fnCard(card_id);
			})
			/*身份证号输入判断*/
			this.idCardInput.on("keyup", function(){
				var idCard_val = this.value;
				this.value = sthis._fnIdentity(idCard_val);
				if(this.value==0){
					$(this).siblings().hide();
				}else{
					$(this).siblings().show();
				}
			})
			/*icon单机操作*/
			this.$el.find(".icon-option").on("click", function(){
				var icon_this=this;
				sthis._fnIcon(icon_this);
			})

			/*失去焦点隐藏icon*/
			this.$el.find("input").on("focus", function(){
				sthis.iconOption.hide();
				if(this.id=="ID_card"){
					if(this.value.length > 1){
						$(this).siblings().show();
					}
				}else{
					$(this).siblings().show();
				}
			})
			/*手机号输入判断*/
			this.mobileInput.on("keyup",function(){
				var mobile_val = this.value;
				this.value = sthis._fnModile(mobile_val);
			})

			/*提交按钮*/
			this.submitBtn.on("click",function(){

				var zCard = $("#bank_card").val();
				var zIdCard = $("#ID_card").val();
				var zMobile = $("#mobile").val();
				var zName = $("#name").val();
				sthis._fnSubmit(zCard,zIdCard,zMobile,zName);

			})
			/*协议*/
			this.agreement.on("click",function(){
				var wheight = $(window).height();
					wwidth = $(window).width();
					agreeList = $("#agree_list");

				/*sthis.agree.css("left",-wwidth);*/
				agreeList.height(wheight/6*4);
				sthis.agree.css("top",wheight/8);
				sthis._fnGetAgree();
				sthis.mask.show();
				sthis.agree.show();
				sthis.agree.css("left",0);
			})

			this.agreeClose.on("click",function(){
				sthis.mask.hide();
				sthis.agree.hide();
			})

		},
		//卡号处理
		_fnCard : function(card_id){
			card_id = card_id.replace(/\D/g,'').replace(/....(?!$)/g,'$& ');
			var b_len = card_id.length,
				bRIcon = $("#bRIcon");
			if(b_len==0){
				bRIcon.addClass("active").show().siblings().hide();
				this.imbox.hide();
				this.bankName.hide();
			}else if(b_len==1){
				bRIcon.removeClass("active").hide().siblings().show().removeClass("active");
			}else if(b_len==18){

			}else if(b_len==19){
				var bank_type=TOOLS.isBank(card_id.replace(/\s+/g,""));
				if(bank_type){
					this.boxFlag=1;
					this.imbox.show();
				}
			}else if(b_len<12){
				this.imbox.hide();
				this.boxFlag=0;
				this.bankName.hide();
			}else if(b_len>=12){
				var bank_type=TOOLS.isBank(card_id.replace(/\s+/g,""));
				if(bank_type){
					this.bankName.find("span").removeClass();
					this.bankName.find("span").addClass("bankName "+bank_type);
					this.bankName.show();

				}
			}
			return card_id;
		},
		//身份证处理
		_fnIdentity : function(idCard_val){
			idCard_val=idCard_val.replace(/[^\d|xX]/g,"");
			return idCard_val;
		},
		//手机号验证
		_fnModile : function(mobile_val){
			mobile_val = mobile_val.replace(/\D/g,'');
			var m_len = mobile_val.length;
				mRIcon = $("#mRIcon");

			if(m_len==0){
				mRIcon.addClass("active").show().siblings().hide();
			}else if(m_len==1){
				mRIcon.removeClass("active").hide().siblings().show().removeClass("active");
			}

			return mobile_val;
		},
		//表单处理
		_fnComplete : function(){
			var ipt=this.$el.find("input"),
				next=$("#next2"),
				ipt_flag=1,
				ipt_len=4;

			if(this.boxFlag==0){
				ipt_len=2;
			}
			for(var i=0; i<ipt_len; i++){
				if(ipt[i].value.length == 0){
					ipt_flag=0;
				}
			}
			if(ipt_flag==1){
				next.removeAttr("disabled");
			}else{
				next.attr("disabled","disabled");
			}
		},
		//icon处理
		_fnIcon : function(icon_this){
			var intype = $(icon_this).attr("node-type");
			var inIs = $(icon_this).find("i");
			var inIsD = $(inIs[0]).css("display");
			var next=$("#next2");
			if(inIs.hasClass("icons-infoNew active")){
				if(inIs.is(".icons-infoNew") && intype=="bank_card"){
					MessageBox.alert({type:"message",txt:CS.ERRORMSG["EFFECTIVEBANK"]});
				}else{
					MessageBox.alert({type:"message",txt:CS.ERRORMSG["AVAILABLEPHONENUMBER"]});
				}
			}else{
				if(inIs.is(".icons-infoNew")){
					$('#'+intype).val("");
					$(inIs[0]).addClass("active").show();
					$(inIs[1]).hide();
					if(intype=="bank_card"){
						this.imbox.hide();
						this.bankName.hide();
						this.idCardInput.val("");
						this.mobileInput.val("");
					}
					next.attr("disabled","disabled");
				}else{
					$('#'+intype).val("");
					$(inIs[0]).parent().hide();
					next.attr("disabled","disabled");
				}
			}
		},

		/*获取协议*/
		_fnGetAgree : function(){
			var now = new Date();
				year = now.getFullYear();
				month = now.getMonth()+1;
				day = now.getDate();
				name = $("#name").val();
				id_card = $("#ID_card").val();
				bank_card = $("#bank_card").val();
			$("#year").html(year);
			$("#year1").html(year);
			$("#month").html(month);
			$("#month1").html(month);
			$("#day").html(day);
			$("#day1").html(day);
			$("#c_id").html(id_card);
			$("#c_bid").html(bank_card);
			$("#c_name").html(name);
		},

		//提交按钮处理
		_fnSubmit : function(zCard,zIdCard,zMobile,zName){
			var zCard_len = zCard.length,
				age = TOOLS.isIdentity(zIdCard),
				phone = TOOLS.isMobile(zMobile),
				bcflag = TOOLS.isCard(zCard.replace(/\s+/g,"")),
				bcflag2 = TOOLS.isBank(zCard.replace(/\s+/g,"")),
				zzCard = zCard.replace(/\s+/g,""),
				smBtn = $("#next2");

			if(this.boxFlag){
				if(zCard_len != 19 && zCard_len == 23 || zCard_len != 23 && zCard_len == 19){
					if(bcflag){
						if(age){
							if(age>30 || age<16){
								MessageBox.alert({type:"common",txt:CS.ERRORMSG["AGENOTRANGEERROR"]});
							}else{
								if(phone){
									/*提交*/
									if(smBtn.hasClass("disabled")) return false;
									smBtn.addClass('disabled');
									TOOLS.ajax({
										url:"./index.php?r=loan/verify",
										data:{name:zName,bank_card:zzCard,id_card:zIdCard,mobile:zMobile},
										dataType:"json",
										type:"get",
										fnSuccess:function(data){
											if(data.stat == "1"){
												window.location= "./index.php?r=loan/sms&mobile="+data.mobile;
											}else if(data.stat == "2"){
												if(data.verify_times == "2"){
													MessageBox.alert({type:"message",txt:CS.ERRORMSG["TWOCHANCE"],cls:true});
													smBtn.removeClass("disabled");
												}else if(data.verify_times == "1"){
													MessageBox.alert({type:"message",txt:CS.ERRORMSG["ONECHANCE"],cls:true});
													smBtn.removeClass("disabled");
												}else if(data.verify_times == "0"){
													window.location= "./index.php?r=loan/failed";
												}
											}else{
												alert("系统错误");
											}

										},
										fnError:function(){}
									});

								}else{
									MessageBox.alert({type:"common",txt:CS.ERRORMSG["MOBILEERROR"]});
								}
							}
						}else{
							MessageBox.alert({type:"common",txt:CS.ERRORMSG["IDENTITYERROR"]});
						}
					}else{
						MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
					}

				}else{
					MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
				}
			}else{
				if(zCard_len != 19 && zCard_len == 23 || zCard_len != 23 && zCard_len == 19){
					if(bcflag){
						if(bcflag2){
						}else{
							MessageBox.alert({type:"common",txt:CS.ERRORMSG["NOBANKERROR"]});
						}
					}else{
						MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
					}
				}else{
					MessageBox.alert({type:"common",txt:CS.ERRORMSG["BANKCARDERROR"]});
				}
			}

		}
	}

	$.fn.PUB = function(options){
		return this.each(function(){
			var $this = $(this) ,
				data = $this.data('PUB');

	          if (!data) {
	        	  $this.data('PUB', (data = new Pub(this, options)))
	          }

	          if (typeof options == 'string') data[options](setData);
		});
	}
})(window.jQuery||window.Zepto)
<|endoftext|>


<commit_before>"use strict";

var firstBackgroundUpdate = true;
var countdownStarted = false;
var countdownTimeoutId = -1;

var QUIZ_AVAILABLE_SECONDS = 10;
var quizStartTime = QUIZ_AVAILABLE_SECONDS;

var numAnswersCorrect = 0;
var numAnswersGiven = 0;

function resetState() {
  numAnswersGiven = numAnswersCorrect = 0;
  countdownTimeoutId = -1;
  countdownStarted = false;
}

$(function() {
  $('#repeat-box').click(function() {
    // reset vars

    $(this).hide();
  });
});

function updateTime() {
  quizStartTime--;

  if (quizStartTime < 0) {
    // reset vars
    clearInterval(countdownTimeoutId);
    countdownTimeoutId = -1;
    quizStartTime = QUIZ_AVAILABLE_SECONDS;

    timeIsOver();

    return;
  }

  // update timer
  var progressPercent = (QUIZ_AVAILABLE_SECONDS - quizStartTime) / QUIZ_AVAILABLE_SECONDS * 100;
  $('#time-left').html(quizStartTime);
  $('#time-left-indicator').animate({'width': progressPercent + '%'}, 300);
}

$('#start-quiz').click(function() {
  resetState();
  showStartLayout();

});

function showStartLayout() {
  // hide timing tags
  $('#questionbox').show();
  $('#time-box').show();
  $('.flashbox').show()

  // show evaluation tags
  $('#start-quiz').hide();
  $('#results').hide();
  $('#sharebuttons').hide();

  $('#question-answer').focus();
}

function showEvaluationLayout() {
  // hide timing tags
  $('#questionbox').hide();
  $('#time-box').hide();
  $('.flashbox').hide();

  // show evaluation tags
  $('#start-quiz').css({'display': 'inline-block'});
  $('#results').show();
  $('#sharebuttons').show();

  $('#time-left').text(QUIZ_AVAILABLE_SECONDS);
  $('#time-left-indicator').css({'width': '0%'});

}

$(document).keypress(function(e) {
  if(e.which == 13 && $('#start-quiz').is(':visible')) {
    $('#start-quiz a').click();
  }
});

// make sure always at least one checkbox is checked
$('#div-operations :checkbox').change(function(e){
  if (!$(this).is(':checked')) {
    if ($("#div-operations :checkbox:checked").length === 0) {
      $(this).prop('checked', true);
    }
  }
});

// timeIsOver();
function timeIsOver() {
  showEvaluationLayout();
  var score = calculateScore();
  setEvaluation(score, getRank(score));

  updateTwitterButton();
  // facebook does update itself

  // function definitions follow //

  function updateTwitterButton() {
    var twitterButtons = $('.twitter-share-button');
    if (twitterButtons.size() !== 0) {
      $('#sharebuttons .twitter-share-button').remove();
      // Generate new markup
      var $tweetBtn = $('')
          .addClass('twitter-share-button')
          .attr('href', 'http://twitter.com/share')
          .attr('data-url', 'http://mental-math-trainer.com')
          .attr('data-text', 'Check out my math score: ' + score + '! In just 10 seconds <3');
      $('.sharebutton').first().append($tweetBtn);
      twttr.widgets.load();
    }
  }

  function calculateScore() {
    var sliderMax = parseInt($('#math-range-slider').val());

    if (sliderMax > 100) {
      sliderMax = 100;
    }

    var numOperatorsEnabled =  $('#div-operations :checkbox').size();
    return Math.ceil(numAnswersCorrect * (sliderMax / 10 + numOperatorsEnabled));
  }

  function getRank(score) {
    // TODO we should add a real ranking one day

    var ONE_BARELY_REACHES_THIS_SCORE = 200;
    return Math.floor(100 * Math.min(Math.E * score / (ONE_BARELY_REACHES_THIS_SCORE * Math.PI), 1));
  }

  function setEvaluation(score, rank) {
    var description = 'You scored ' + score + '' +
                      'You are better than ' + rank + ' %';
    $('#results .description').html(description);
  }
}

// set up listeners
$(function() {
  var $question = $('#question');
  var $answer = $('#question-answer');
  var $mathRangeSlider = $('#math-range-slider');
  var currentQuestion;
  var factory = new QuestionFactory();

  setFirstQuestion();
  function setFirstQuestion() {
    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
    $answer.val('');
  }

  // update question on slider or checkbox change
  $('#math-range-slider, #div-operations :checkbox').change(function(){
    setNewQuestion();
  });

  function setNewQuestion() {
    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
  }

  function increaseMathRangeSlider() {
    var delta = 10;
    $mathRangeSlider.val(parseInt($mathRangeSlider.val(), 10) + delta);
  }

  function evaluateAnswer() {
    if (countdownTimeoutId === -1) {
      countdownTimeoutId = setInterval(updateTime, 1000);
    }

    numAnswersGiven++;

    if (currentQuestion !== undefined && currentQuestion.getAnswer() == $answer.val()) {
      numAnswersCorrect++;

      if (numAnswersCorrect % 5 == 0) {
        increaseMathRangeSlider();
      }

      if (Math.random() < .5) {
        _flashboxLeft.fire();
      } else {
        _flashboxRight.fire();
      }
      quizStartTime += 2;
    } else {
      //_flashboxRight.fire();
    }

    setNewQuestion();
    $answer.val('');
  }

  function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

  function submitInputPressed(e) {
    if(e === undefined || e.which == 13) {
      if ($answer.val().trim() !== '' && isNumber($answer.val())) {
        evaluateAnswer();
      }
      $answer.val('');
    }
  }

  // auto-submit correct answers
  $answer.keyup(function(e) {
     if ($answer.val() == currentQuestion.getAnswer()) {
        // $answer.trigger({type: 'keypress', which: 13, keyCode: 13});
        submitInputPressed();
      }
  });

  // register answer submit listeners
  // $answer.keypress(function(e) {
  //   submitInputPressed(e);
  // });

  // $('#submit-answer').click(function() {
  //   submitInputPressed();
  //   $answer.focus();
  // });
});<commit_msg>disable range slider after first answer<commit_after>"use strict";

var firstBackgroundUpdate = true;
var countdownStarted = false;
var countdownTimeoutId = -1;

var QUIZ_AVAILABLE_SECONDS = 10;
var quizStartTime = QUIZ_AVAILABLE_SECONDS;

var numAnswersCorrect = 0;
var numAnswersGiven = 0;

function resetState() {
  numAnswersGiven = numAnswersCorrect = 0;
  countdownTimeoutId = -1;
  countdownStarted = false;
}

$(function() {
  $('#repeat-box').click(function() {
    // reset vars

    $(this).hide();
  });
});

function updateTime() {
  quizStartTime--;

  if (quizStartTime < 0) {
    // reset vars
    clearInterval(countdownTimeoutId);
    countdownTimeoutId = -1;
    quizStartTime = QUIZ_AVAILABLE_SECONDS;

    timeIsOver();

    return;
  }

  // update timer
  var progressPercent = (QUIZ_AVAILABLE_SECONDS - quizStartTime) / QUIZ_AVAILABLE_SECONDS * 100;
  $('#time-left').html(quizStartTime);
  $('#time-left-indicator').animate({'width': progressPercent + '%'}, 300);
}

$('#start-quiz').click(function() {
  resetState();
  showStartLayout();

});

function showStartLayout() {
  // hide timing tags
  $('#questionbox').show();
  $('#time-box').show();
  $('.flashbox').show()

  // show evaluation tags
  $('#start-quiz').hide();
  $('#results').hide();
  $('#sharebuttons').hide();

  $('#question-answer').focus();
  $('#math-range-slider').attr('disabled', 'disabled');
}

function showEvaluationLayout() {
  // hide timing tags
  $('#questionbox').hide();
  $('#time-box').hide();
  $('.flashbox').hide();

  // show evaluation tags
  $('#start-quiz').css({'display': 'inline-block'});
  $('#results').show();
  $('#sharebuttons').show();

  $('#time-left').text(QUIZ_AVAILABLE_SECONDS);
  $('#time-left-indicator').css({'width': '0%'});

  $('#math-range-slider').removeAttr('disabled');

}

$(document).keypress(function(e) {
  if(e.which == 13 && $('#start-quiz').is(':visible')) {
    $('#start-quiz a').click();
  }
});

// make sure always at least one checkbox is checked
$('#div-operations :checkbox').change(function(e){
  if (!$(this).is(':checked')) {
    if ($("#div-operations :checkbox:checked").length === 0) {
      $(this).prop('checked', true);
    }
  }
});

// timeIsOver();
function timeIsOver() {
  showEvaluationLayout();
  var score = calculateScore();
  setEvaluation(score, getRank(score));

  updateTwitterButton();
  // facebook does update itself

  // function definitions follow //

  function updateTwitterButton() {
    var twitterButtons = $('.twitter-share-button');
    if (twitterButtons.size() !== 0) {
      $('#sharebuttons .twitter-share-button').remove();
      // Generate new markup
      var $tweetBtn = $('')
          .addClass('twitter-share-button')
          .attr('href', 'http://twitter.com/share')
          .attr('data-url', 'http://mental-math-trainer.com')
          .attr('data-text', 'Check out my math score: ' + score + '! In just 10 seconds <3');
      $('.sharebutton').first().append($tweetBtn);
      twttr.widgets.load();
    }
  }

  function calculateScore() {
    var sliderMax = parseInt($('#math-range-slider').val());

    if (sliderMax > 100) {
      sliderMax = 100;
    }

    var numOperatorsEnabled =  $('#div-operations :checkbox').size();
    return Math.ceil(numAnswersCorrect * (sliderMax / 10 + numOperatorsEnabled));
  }

  function getRank(score) {
    // TODO we should add a real ranking one day

    var ONE_BARELY_REACHES_THIS_SCORE = 500;
    return Math.floor(100 * Math.min(Math.E * score / (ONE_BARELY_REACHES_THIS_SCORE * Math.PI), 1));
  }

  function setEvaluation(score, rank) {
    var description = 'You scored ' + score + '' +
                      'You are better than ' + rank + ' %';
    $('#results .description').html(description);
  }
}

// set up listeners
$(function() {
  var $question = $('#question');
  var $answer = $('#question-answer');
  var $mathRangeSlider = $('#math-range-slider');
  var currentQuestion;
  var factory = new QuestionFactory();

  setFirstQuestion();
  function setFirstQuestion() {
    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
    $answer.val('');
  }

  // update question on slider or checkbox change
  $('#math-range-slider, #div-operations :checkbox').change(function(){
    setNewQuestion();
  });

  function setNewQuestion() {
    currentQuestion = factory.nextQuestion();
    $question.text(currentQuestion.getDisplay());
  }

  function increaseMathRangeSlider() {
    var delta = 10;
    $mathRangeSlider.val(parseInt($mathRangeSlider.val(), 10) + delta);
  }

  function evaluateAnswer() {
    $('#math-range-slider').attr('disabled', 'disabled');

    if (countdownTimeoutId === -1) {
      countdownTimeoutId = setInterval(updateTime, 1000);
    }

    numAnswersGiven++;

    if (currentQuestion !== undefined && currentQuestion.getAnswer() == $answer.val()) {
      numAnswersCorrect++;

      if (numAnswersCorrect % 5 == 0) {
        increaseMathRangeSlider();
      }

      if (Math.random() < .5) {
        _flashboxLeft.fire();
      } else {
        _flashboxRight.fire();
      }
      quizStartTime += 2;
    } else {
      //_flashboxRight.fire();
    }

    setNewQuestion();
    $answer.val('');
  }

  function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

  function submitInputPressed(e) {
    if(e === undefined || e.which == 13) {
      if ($answer.val().trim() !== '' && isNumber($answer.val())) {
        evaluateAnswer();
      }
      $answer.val('');
    }
  }

  // auto-submit correct answers
  $answer.keyup(function(e) {
     if ($answer.val() == currentQuestion.getAnswer()) {
        // $answer.trigger({type: 'keypress', which: 13, keyCode: 13});
        submitInputPressed();
      }
  });

  // register answer submit listeners
  // $answer.keypress(function(e) {
  //   submitInputPressed(e);
  // });

  // $('#submit-answer').click(function() {
  //   submitInputPressed();
  //   $answer.focus();
  // });
});<|endoftext|>


<commit_before>//var syncpage = "http://10.46.18.22/remote/remote.php";
var evento;
var db = new Dexie( "encontro_estadual" );
db.version(1).stores({
	usuarios: "id, nome",
	eventos: "id, nome",
	frequencia: "++idx, usuario, evento",
});
db.open();

function deleteDatabase() {
	db.delete();
}

function loadInitialData( f ) {

	$.get( f, function(data){
		var lines = data.split( '\n' );
		var N = lines.length;

		for( i = 0; i < N; ++i )
		{
			var aux = lines[i].split( '\t' );
			var _id = aux[0];
			var _nome = aux[1].toUpperCase();

			//console.log('{"id":'+ _id +',"nome":"'+ _nome +'"}');
			db.usuarios.add({
				id: parseInt( _id ),
				nome: "" + _nome,
			});
		}
	});

	/*
	db.usuarios.add({
		id: 1,
		nome: "Wilk Coêlho Maia",
	});
	db.usuarios.add({
		id: 2,
		nome: "Marcos Henrique",
	});

	db.eventos.add({
		id: 1,
		nome: "Olimpíada de Programação",
	});
	*/
}

loadInitialData( 'data.in' );

if( document.location.search )
{
	var queries = document.location.search.split('?')[1].split('&');
	var evento = parseInt( queries[0].split('=')[1] );
}

(function(window) {
	'use strict';
	var decoder = $('#qr-canvas'),
		sl = $('.scanner-laser'),
		sQ = $('#scanned-QR');
	sl.css('opacity', .5);

	decoder.click(function(){
		if (decoder.data().plugin_WebCodeCam.options.ReadBarecode)
			decoder.data().plugin_WebCodeCam.tryParseBarecode();

		if (decoder.data().plugin_WebCodeCam.options.ReadQRCode)
			decoder.data().plugin_WebCodeCam.tryParseQRCode();
	});

	function gotSources(sourceInfos) {
		for (var i = 0; i !== sourceInfos.length; ++i) {
			var sourceInfo = sourceInfos[i];
			var option = document.createElement('option');
			option.value = sourceInfo.id;
			if (sourceInfo.kind === 'video') {
				var face = sourceInfo.facing == '' ? 'unknown' : sourceInfo.facing;
				switch(face)
				{
					case "unknown":
						face = "Desconhecida";
						break;

					case "user":
						face = "Frontal";
						break;

					case "environment":
						face = "Traseira";
						break;

					default:
						break;
				}

				option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1) + ' (Câmera: ' + face + ')';
				videoSelect.appendChild(option);
			}
		}
	}
	if (typeof MediaStreamTrack.getSources !== 'undefined') {
		var videoSelect = document.querySelector('select#cameraId');
		$(videoSelect).change(function(event) {
			if (typeof decoder.data().plugin_WebCodeCam !== "undefined") {
				decoder.data().plugin_WebCodeCam.options.videoSource.id = $(this).val();
				decoder.data().plugin_WebCodeCam.cameraStop();
				decoder.data().plugin_WebCodeCam.cameraPlay(false);
			}
		});

		MediaStreamTrack.getSources(gotSources);
	} else {
		document.querySelector('select#cameraId').remove();
	}

	if (typeof decoder.data().plugin_WebCodeCam == "undefined") {
		decoder.WebCodeCam({
			videoSource: {
				id: document.querySelector('select#cameraId').value,
				maxWidth: 640,
				maxHeight: 480
			},
			autoBrightnessValue: 120,
			resultFunction: function(text, imgSrc) {
				text = JSON.parse(text +"");
				evento = 2;

				sQ.html(""+ text.nome +" registrado com sucesso.");
				sl.fadeOut(150, function() {
					sl.fadeIn(150);
				});

				// Banco de dados local
				db.usuarios.where("id").equals(text.id).count(function(c){
					// Não há usuário com esse ID
					if( c == 0 )
					{
						sQ.html("Erro na leitura. Por favor, tente novamente.
Caso o erro persista, busque ajuda.");
						return;
					}

					db.eventos.where("id").equals(evento).count(function(c2){
						// Não há evento com esse ID
						if( c2 == 0 )
						{
							sQ.html("ERRO - EVENTO NÃO CADASTRADO");
							return;
						}

						// Caso tudo corra bem, insere a frequência
						db.frequencia.where("usuario").equals(text.id).count(function(c3){
							// Para evitar dados reinseridos sem necessidade
							if( c3 == 0 )
							{

								/*
								$.ajax({
									type: 'GET',
									url: syncpage + "?callback=successFreq2&opt=1",
									data: "usuario=" + text.id + "&evento=" + evento,
									dataType: "jsonp",
									jsonpCallback: "successFreq2",
									crossDomain: true,
									sucess: successFreq,
									error: function(a, b, e) {
										console.error(e);
									}
								});
								*/

								db.frequencia.add({
									usuario: text.id,
									evento: evento,
								});
							}
						});
					});
				});
			},
			getUserMediaError: function() {
				alert('Sorry, the browser you are using doesn\'t support getUserMedia');
			},
			cameraError: function(error) {
				var p, message = 'Error detected with the following parameters:\n';
				for (p in error) {
					message += p + ': ' + error[p] + '\n';
				}
				alert(message);
			}
		});
		sQ.text('Direcione a câmera ao QR Code e pressione quando estiver enquadrado');
	} else {
		sQ.text('Direcione a câmera ao QR Code e pressione quando estiver enquadrado');
		$("#qr-canvas").data().plugin_WebCodeCam.cameraPlay();
	}
}).call(window.Page = window.Page || {});

function syncData() {

	var syncpage = prompt( "Entre com o IP do servidor, apenas números. Deixe em branco caso não saiba o que está fazendo.", "" );
	if( syncpage == "" )
		return;

	syncpage = "http://" + syncpage + "/WebCodeCam/remote/remote.php";
	var r = confirm( "Confirmando o endereço final do servidor de atualização: " + syncpage );
	if( r == false )
		return;

	// ENVIA FREQUÊNCIAS
	var n = -1;
	var _f_u = [];
	var _f_e = [];

	db.frequencia.each(function(f){
		++n;

		_f_u[n] = f.usuario;
		_f_e[n] = f.evento;

		console.log( "n = " + n + " - Usuario = " + f.usuario );
	}).then(function(){
		if( typeof _f_u !== "undefined" )
		{
			f_u = _f_u.join(',');
			f_e = _f_e.join(',');
		}
		else
		{
			f_u = "";
			f_e = "";
		}

		$.ajax({
			type: 'GET',
			url: syncpage + "?callback=successFreq&opt=1",
			data: "usuario=" + f_u + "&evento=" + f_e,
			dataType: "jsonp",
			jsonpCallback: "successFreq",
			crossDomain: true,
			sucess: successFreq,
			error: function(a, b, e) {
				console.error(e);
			}
		});
	});

	$.ajax({
		type: 'GET',
		url: syncpage + "?callback=successUsers&opt=2",
		dataType: "jsonp",
		jsonpCallback: "successUsers",
		crossDomain: true,
		sucess: successUsers,
		error: function(a, b, e) {
			console.error(e);
		}
	});

	$.ajax({
		type: 'GET',
		url: syncpage + "?callback=successEvents&opt=3",
		dataType: "jsonp",
		jsonpCallback: "successEvents",
		crossDomain: true,
		sucess: successEvents,
		error: function(a, b, e) {
			console.error(e);
		}
	});
}

function successFreq(res){
	for( i = 0; data = res[i]; ++i )
	{
		data = JSON.parse(data);

		if( data.id == -1 )
			console.error( data );
		else if( data.error != 0 && data.error != "23000" )
			console.error( data );
		else
		{
			console.log( data );
			db.frequencia.where("usuario").equals(parseInt(data.id)).delete();
		}
	}
}

function successUsers(res){
	db.usuarios.clear().then(function(){
		for( i = 0; data = res[i]; ++i )
		{
			data = JSON.parse(data);

			if( data.error != 0 && data.error != "23000" )
				console.error(data);
			else
			{
				db.usuarios.add({
					id: parseInt(data.id),
					nome: data.nome,
				});
			}
		}
	});
}

function successEvents(res){
	db.eventos.clear().then(function(){
		for( i = 0; data = res[i]; ++i )
		{
			data = JSON.parse(data);

			if( data.error != 0 && data.error != "23000" )
				console.error(data);
			else
			{
				db.eventos.add({
					id: parseInt(data.id),
					nome: data.nome,
				});
			}
		}
	});
}

function successFreq2(res){
	console.log("Coleta efetuada.");
}<commit_msg>Correções finais.<commit_after>//var syncpage = "http://10.46.18.22/remote/remote.php";
var evento;
var db = new Dexie( "encontro_estadual" );
db.version(1).stores({
	usuarios: "id, nome",
	eventos: "id, nome",
	frequencia: "++idx, usuario, evento",
});
db.open();

function deleteDatabase() {
	db.delete();
}

function loadInitialData( f ) {

	$.get( f, function(data){
		var lines = data.split( '\n' );
		var N = lines.length;

		for( i = 0; i < N; ++i )
		{
			var aux = lines[i].split( '\t' );
			var _id = aux[0];
			var _nome = aux[1].toUpperCase();

			console.log('{"id":'+ _id +',"nome":"'+ _nome +'"}');
			db.usuarios.add({
				id: parseInt( _id ),
				nome: "" + _nome,
			});
		}
	});

	db.eventos.add({
		id: 1,
		nome: "Encontro Estadual",
	});

	/*
	db.usuarios.add({
		id: 1,
		nome: "Wilk Coêlho Maia",
	});
	db.usuarios.add({
		id: 2,
		nome: "Marcos Henrique",
	});

	db.eventos.add({
		id: 1,
		nome: "Olimpíada de Programação",
	});
	*/
}

loadInitialData( 'data.in' );

if( document.location.search )
{
	var queries = document.location.search.split('?')[1].split('&');
	var evento = parseInt( queries[0].split('=')[1] );
}

(function(window) {
	'use strict';
	var decoder = $('#qr-canvas'),
		sl = $('.scanner-laser'),
		sQ = $('#scanned-QR');
	sl.css('opacity', .5);

	decoder.click(function(){
		if (decoder.data().plugin_WebCodeCam.options.ReadBarecode)
			decoder.data().plugin_WebCodeCam.tryParseBarecode();

		if (decoder.data().plugin_WebCodeCam.options.ReadQRCode)
			decoder.data().plugin_WebCodeCam.tryParseQRCode();
	});

	function gotSources(sourceInfos) {
		for (var i = 0; i !== sourceInfos.length; ++i) {
			var sourceInfo = sourceInfos[i];
			var option = document.createElement('option');
			option.value = sourceInfo.id;
			if (sourceInfo.kind === 'video') {
				var face = sourceInfo.facing == '' ? 'unknown' : sourceInfo.facing;
				switch(face)
				{
					case "unknown":
						face = "Desconhecida";
						break;

					case "user":
						face = "Frontal";
						break;

					case "environment":
						face = "Traseira";
						break;

					default:
						break;
				}

				option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1) + ' (Câmera: ' + face + ')';
				videoSelect.appendChild(option);
			}
		}
	}
	if (typeof MediaStreamTrack.getSources !== 'undefined') {
		var videoSelect = document.querySelector('select#cameraId');
		$(videoSelect).change(function(event) {
			if (typeof decoder.data().plugin_WebCodeCam !== "undefined") {
				decoder.data().plugin_WebCodeCam.options.videoSource.id = $(this).val();
				decoder.data().plugin_WebCodeCam.cameraStop();
				decoder.data().plugin_WebCodeCam.cameraPlay(false);
			}
		});

		MediaStreamTrack.getSources(gotSources);
	} else {
		document.querySelector('select#cameraId').remove();
	}

	if (typeof decoder.data().plugin_WebCodeCam == "undefined") {
		decoder.WebCodeCam({
			videoSource: {
				id: document.querySelector('select#cameraId').value,
				maxWidth: 640,
				maxHeight: 480
			},
			autoBrightnessValue: 120,
			resultFunction: function(text, imgSrc) {
				text = JSON.parse(text +"");
				evento = 1;

				sQ.html(""+ text.nome +" registrado com sucesso.");
				sl.fadeOut(150, function() {
					sl.fadeIn(150);
				});

				// Banco de dados local
				db.usuarios.where("id").equals(text.id).count(function(c){
					// Não há usuário com esse ID
					if( c == 0 )
					{
						sQ.html("Erro na leitura. Por favor, tente novamente.
Caso o erro persista, busque ajuda.");
						return;
					}

					db.eventos.where("id").equals(evento).count(function(c2){
						// Não há evento com esse ID
						if( c2 == 0 )
						{
							sQ.html("ERRO - EVENTO NÃO CADASTRADO");
							return;
						}

						// Caso tudo corra bem, insere a frequência
						db.frequencia.where("usuario").equals(text.id).count(function(c3){
							// Para evitar dados reinseridos sem necessidade
							if( c3 == 0 )
							{

								/*
								$.ajax({
									type: 'GET',
									url: syncpage + "?callback=successFreq2&opt=1",
									data: "usuario=" + text.id + "&evento=" + evento,
									dataType: "jsonp",
									jsonpCallback: "successFreq2",
									crossDomain: true,
									sucess: successFreq,
									error: function(a, b, e) {
										console.error(e);
									}
								});
								*/

								db.frequencia.add({
									usuario: text.id,
									evento: evento,
								});
							}
						});
					});
				});
			},
			getUserMediaError: function() {
				alert('Sorry, the browser you are using doesn\'t support getUserMedia');
			},
			cameraError: function(error) {
				var p, message = 'Error detected with the following parameters:\n';
				for (p in error) {
					message += p + ': ' + error[p] + '\n';
				}
				alert(message);
			}
		});
		sQ.text('Direcione a câmera ao QR Code e pressione quando estiver enquadrado');
	} else {
		sQ.text('Direcione a câmera ao QR Code e pressione quando estiver enquadrado');
		$("#qr-canvas").data().plugin_WebCodeCam.cameraPlay();
	}
}).call(window.Page = window.Page || {});

function syncData() {

	var syncpage = prompt( "Entre com o IP do servidor, apenas números. Deixe em branco caso não saiba o que está fazendo.", "" );
	if( syncpage == "" )
		return;

	syncpage = "http://" + syncpage + "/WebCodeCam/remote/remote.php";
	var r = confirm( "Confirmando o endereço final do servidor de atualização: " + syncpage );
	if( r == false )
		return;

	// ENVIA FREQUÊNCIAS
	var n = -1;
	var _f_u = [];
	var _f_e = [];

	db.frequencia.each(function(f){
		++n;

		_f_u[n] = f.usuario;
		_f_e[n] = f.evento;

		console.log( "n = " + n + " - Usuario = " + f.usuario );
	}).then(function(){
		if( typeof _f_u !== "undefined" )
		{
			f_u = _f_u.join(',');
			f_e = _f_e.join(',');
		}
		else
		{
			f_u = "";
			f_e = "";
		}

		$.ajax({
			type: 'GET',
			url: syncpage + "?callback=successFreq&opt=1",
			data: "usuario=" + f_u + "&evento=" + f_e,
			dataType: "jsonp",
			jsonpCallback: "successFreq",
			crossDomain: true,
			sucess: successFreq,
			error: function(a, b, e) {
				console.error(e);
			}
		});
	});

	$.ajax({
		type: 'GET',
		url: syncpage + "?callback=successUsers&opt=2",
		dataType: "jsonp",
		jsonpCallback: "successUsers",
		crossDomain: true,
		sucess: successUsers,
		error: function(a, b, e) {
			console.error(e);
		}
	});

	$.ajax({
		type: 'GET',
		url: syncpage + "?callback=successEvents&opt=3",
		dataType: "jsonp",
		jsonpCallback: "successEvents",
		crossDomain: true,
		sucess: successEvents,
		error: function(a, b, e) {
			console.error(e);
		}
	});
}

function successFreq(res){
	for( i = 0; data = res[i]; ++i )
	{
		data = JSON.parse(data);

		if( data.id == -1 )
			console.error( data );
		else if( data.error != 0 && data.error != "23000" )
			console.error( data );
		else
		{
			console.log( data );
			db.frequencia.where("usuario").equals(parseInt(data.id)).delete();
		}
	}
}

function successUsers(res){
	db.usuarios.clear().then(function(){
		for( i = 0; data = res[i]; ++i )
		{
			data = JSON.parse(data);

			if( data.error != 0 && data.error != "23000" )
				console.error(data);
			else
			{
				db.usuarios.add({
					id: parseInt(data.id),
					nome: data.nome,
				});
			}
		}
	});
}

function successEvents(res){
	db.eventos.clear().then(function(){
		for( i = 0; data = res[i]; ++i )
		{
			data = JSON.parse(data);

			if( data.error != 0 && data.error != "23000" )
				console.error(data);
			else
			{
				db.eventos.add({
					id: parseInt(data.id),
					nome: data.nome,
				});
			}
		}
	});
}

function successFreq2(res){
	console.log("Coleta efetuada.");
}<|endoftext|>


<commit_before>var directionsDisplay;
var map = null;
var elevator = null;
var polyline;
var routes = null;
var slopes = null;
var distance = null;
var duration = null;
var markersArray = [];
var elevations = [];
var mapPaths = [];
var measurementMode;
var metricUnit = null;
var feetMultiplicator = null;
// Load the visualization API with the columnchart package.
google.load("visualization", "1", {packages: ["columnchart"]});

// Runs after page is loaded.
$(function () {
    var from = getURLParameter('from');
    var to = getURLParameter('to');
    var travelMode = getURLParameter('travelMode');
    measurementMode = getURLParameter('measurementMode');

    // If this link is being shared set to and from
    if (from != "null") {
        $('#from').val(decodeURLParameter(from));
    }

    if (to != "null") {
        $('#to').val(decodeURLParameter(to));
    }

    if (travelMode != "null") {
        $('#travel-mode').val(decodeURLParameter(travelMode));
    }

    if (measurementMode === 'null') {
        measurementMode = 'miles';
    } else {
        $('#measurement-mode').val(decodeURLParameter(measurementMode));
    }

    $("#from-to-switcher").on("click", function (e) {
        var $fromInput = $("#from");
        var $toInput = $("#to");
        var oldFromVal = $fromInput.val();
        $fromInput.val($toInput.val());
        $toInput.val(oldFromVal);
    });

    //  Create event handler that will start the calcRoute function when
    //  the go button is clicked.
    $("form#routes").on("submit", function (e) {

        measurementMode = $("#measurement-mode").val();
        metricUnit = measurementMode == "miles" ? "ft" : "m";
        e.preventDefault();
        calcRoute();
    });

    initialize_maps();
    initAutoComplete('from');
    initAutoComplete('to');

    if (from != "null" && to != "null") {
        calcRoute();
    }
});

function initialize_maps() {
    // Set ability to make route draggable.
    var rendererOptions = {
        draggable: true,
        hideRouteList: true,
        polylineOptions: {
            strokeOpacity: 0
        }
    };
    // Initialize the directions renderer.
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    var mapCanvas = $('#map-canvas').get(0);
    var mapOptions = {
        center: new google.maps.LatLng(37.787930,-122.4074990),
        zoom: 13,
        // Disables zoom and streetview bar but can stil zoom with mouse.
        disableDefaultUI: false,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    // Create a google maps object.
    map = new google.maps.Map(mapCanvas, mapOptions);
    directionsDisplay.setMap(map);
    // Add elevation service.
    elevator = new google.maps.ElevationService();

    // Set up listener to change path elevation information if the user
    // clicks on another suggested route.
    google.maps.event.addListener(
        directionsDisplay,
        'routeindex_changed',
        updateRoutes
    );
}

function initAutoComplete(field) {
    var input = document.getElementById(field);
    autocomplete = new google.maps.places.Autocomplete(input);

    // Prevent form submission when selecting place with enter.
    // http://stackoverflow.com/questions/11388251/google-autocomplete-enter-to-select
    $('#' + field).keydown(function (e) {
      if (e.which == 13 && $('.pac-container:visible').length)
        return false;
    });
}

function calcRoute() {
    var start = $("#from").val() || $("#from").attr("placeholder");
    var end = $("#to").val() || $("#to").attr("placeholder");
    var travelMode = $("#travel-mode").val();
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode[travelMode.toUpperCase()]
    };
    var DirectionsService = new google.maps.DirectionsService();
    DirectionsService.route(request, function(result, status) {
        if (status === "ZERO_RESULTS") {
            alert("No directions found.");
            return;
        }
        // Checks region for directions eligibility.
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });
    sharableLink(start, end, travelMode);
}
function sharableLink(start, end, travelMode) {
    // Update url to include sharable link
    history.replaceState('null', 'Flat Route Finder', '?from=' + encodeURLParameter(start) + '&to=' + encodeURLParameter(end) +
        '&travelMode=' + travelMode + '&measurementMode=' + measurementMode);
}

var updating = false;
function updateRoutes() {
    if (updating) return;
    updating = true;
    setTimeout(function () { updating = false; }, 100);
    console.log("Updating routes");
    // Check if the path has been populated, if it has been already
    // populated, clear it.

    var routes = this.directions.routes;
    var path = routes[this.routeIndex].overview_path;
    distance = routes[this.routeIndex].legs[0].distance;
    duration = routes[this.routeIndex].legs[0].duration;

    /* Shows distance in miles or kilometres, depending on measurement mode. */
    if(measurementMode == "miles"){
        $("#distance").html(distance.text);
    }
    else{
        $("#distance").html((distance.value / 1000) + "Km");
    }

    $("#travel-time").html(duration.text);
    $(".travel-info").show();
    newPath(path, distance.value);
}

function newPath(path) {
        var pathRequest = {
        'path': path,
        'samples': 300
    };
        // Initiate the path request.
    elevator.getElevationAlongPath(pathRequest, plotElevation);
}
// Take an array of elevation result objects, draws a path on the map
// and plots the elevation profile on the chart.
function plotElevation(elevations, status) {
    var slope, data, i, slopeChart, elevationChart, slopeChartDiv;
    if (status !== google.maps.ElevationStatus.OK) {
        alert("Error getting elevation data from Google");
        return;
    }
    // Create a new chart in the elevation chart div.
    elevationChartDiv = $("#elevation_chart").css('display', 'block');
    // Extract the data to populate the chart.
    map.elevationData = new google.visualization.DataTable();
    map.elevationData.addColumn('string', 'Sample');
    map.elevationData.addColumn('number', 'Elevation');
    map.elevationData.locations = [];
    map.elevationData.elevation = [];
    for (i = 0; i < elevations.length; i++) {

        // Change elevation from meters to feet.
        //console.log(measurementMode);
        if(measurementMode == "miles"){
            feetMultiplicator = 3.28084;
        }
        else{
            feetMultiplicator = 1;
        }

        map.elevationData.addRow([
            '',
            elevations[i].elevation * feetMultiplicator
        ]);
        map.elevationData.locations.push( elevations[i].location );
        map.elevationData.elevation.push( elevations[i].elevation * feetMultiplicator );

    }

    // Draw the chart using the data within its div.

    elevationChart = new google.visualization.ColumnChart(elevationChartDiv.get(0));
    elevationChart.draw(map.elevationData, {
        // width: 500,
        // height: 245,
        legend: 'none',
        titleY: 'Elevation ('+metricUnit+')'
    });
    changeElevation(elevationChart, elevations);
}
function changeElevation(elevationChart, elevations) {
    // Create event listenter on slope to show location and elevation.
    google.visualization.events.addListener(elevationChart, 'onmouseover', elevationHover);
    google.visualization.events.addListener(elevationChart, 'onmouseout',
        elevationClear);

    plotSlope(elevations);
}
function plotSlope(elevations){
    slopeChartDiv = $("#slope_chart").css('display', 'block');
    // Extract the data to populate the chart.
    map.slopeData = new google.visualization.DataTable();
    map.slopeData.addColumn('string', 'Sample');
    map.slopeData.addColumn('number', 'Slope');

    // Loop through each element of the elevation data,
    // call the calc slope function using elevations.legth[i]
    // and elevations.length[i+1]
    // Create a slopes array so we can search through it later
    slopes = [];
    for (i = 0; i < elevations.length - 1; i++) {
        slope = (calcSlope(elevations[i+1].elevation, elevations[i].elevation, distance.value/300)) * 100;
        map.slopeData.addRow(['', slope]);
        slopes.push({
            slope: slope,
            location: midpoint(elevations[i], elevations[i+1])
        });
    }

// Draw the chart using the slope data within its div.
    slopeChart = new google.visualization.ColumnChart(slopeChartDiv.get(0));
    slopeChart.draw(map.slopeData, {
        // width: 500,
        // height: 245,
        legend: 'none',
        titleY: 'slope %'
    });
    $('.chart').removeClass('hide');
    changeSlope(slopeChart, elevations, slopes);
}
function changeSlope(slopeChart, elevations, slopes) {
    // Create event listenter on slope to show location and slope.
    google.visualization.events.addListener(slopeChart, 'onmouseover', elevationHover);
    google.visualization.events.addListener(slopeChart, 'onmouseout',
        elevationClear);
    drawPolyline(elevations, slopes);
}

function removePolylines() {
    for (var i = 0; i < mapPaths.length; i++) {
        var path = mapPaths[i];
        path.setMap(null);
    }

    mapPaths = [];
}

function drawPolyline (elevations, slopes) {
    // Create a polyline between each elevation, color code by slope.
    // Remove any existing polylines before drawing a new polyline.
    removePolylines();

    for (var i = 0; i < slopes.length; i++) {
        var routePath = [
            elevations[i].location,
            elevations[i+1].location
        ];
        var absSlope = Math.abs(slopes[i].slope);
        if (absSlope <= 5) {
            pathColor = "#3CB371";
        } else if (absSlope <= 10) {
            pathColor = "#FFFF00";
        } else if (absSlope <= 15) {
            pathColor = "#FF9800";
        } else if (absSlope <= 20) {
            pathColor = "#F44336";
        }
        else {
            pathColor = "#000000";
        }
        mapPath = new google.maps.Polyline({
            path: routePath,
            strokeColor: pathColor,
            strokeOpacity: 0.8,
            strokeWeight: 5,
            draggable: true
        });
        mapPath.setMap(map);
        mapPaths.push(mapPath);
    }
}

function deg(slope) {
    return Math.floor(slope * 45) / 100;
}

function elevationHover (x) {
    // Show location on the map.
    var location = map.elevationData.locations[x.row];
    var elevation = map.elevationData.elevation[x.row];
    var slope = slopes[x.row].slope;
    var contentString = "Elevation: " + Math.round(elevation) + " " + metricUnit + "<br>" +
        "Slope: " + Math.round(slope) + "% (" + deg(slope) + "°)";

    map.locationMarker = new google.maps.Marker({
        position: location,
        map: map,
        labelContent: "Lat: " + location.lat() + ". Lng: " + location.lng() +
            ". Elevation: " + elevation
    });
    addinfoWindow(contentString);
}
function addinfoWindow(contentString) {
    // Add info window to the map.
    map.infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    map.infowindow.open(map, map.locationMarker);
}
function elevationClear (x) {
    map.locationMarker.setMap(null);
}

function midpoint(point1, point2) {
    // To get the midpoint, find the average between each respective point
    var lat = (point1.location.lat() + point2.location.lat()) / 2;
    var lng = (point1.location.lng() + point2.location.lng()) / 2;
    return new google.maps.LatLng(lat, lng);
}

// Calculate slope using elevation change between two points
// over a given distance in m, the distance between each measurement.
function calcSlope(elev1M, elev2M, distanceM) {
    slope = (elev1M - elev2M) / distanceM;
    return slope;
}

// Gets the 'to' and 'from' url Parameter for sharing links
// Source: http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
function getURLParameter(name) {
    return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)')
        .exec(location.search)||[,null])[1]);
}

//change spaces to plus(+) sign
function encodeURLParameter(str) {
  return encodeURIComponent(str).replace(/%20/g, "+");
}

//change plus(+) sign to spaces
function decodeURLParameter(str) {
  return decodeURIComponent(str).replace(/[!'()]/g, escape)
    .replace(/\+/g, " ");
}
<commit_msg>Fix 404 error keyword.<commit_after>var directionsDisplay;
var map = null;
var elevator = null;
var polyline;
var routes = null;
var slopes = null;
var distance = null;
var duration = null;
var markersArray = [];
var elevations = [];
var mapPaths = [];
var measurementMode;
var metricUnit = null;
var feetMultiplicator = null;
// Load the visualization API with the columnchart package.
google.load("visualization", "1", {packages: ["columnchart"]});

// Runs after page is loaded.
$(function () {
    var from = getURLParameter('from');
    var to = getURLParameter('to');
    var travelMode = getURLParameter('travelMode');
    measurementMode = getURLParameter('measurementMode');

    // If this link is being shared set to and from
    if (from != "null") {
        $('#from').val(decodeURLParameter(from));
    }

    if (to != "null") {
        $('#to').val(decodeURLParameter(to));
    }

    if (travelMode != "null") {
        $('#travel-mode').val(decodeURLParameter(travelMode));
    }

    if (measurementMode === 'null') {
        measurementMode = 'miles';
    } else {
        $('#measurement-mode').val(decodeURLParameter(measurementMode));
    }

    $("#from-to-switcher").on("click", function (e) {
        var $fromInput = $("#from");
        var $toInput = $("#to");
        var oldFromVal = $fromInput.val();
        $fromInput.val($toInput.val());
        $toInput.val(oldFromVal);
    });

    //  Create event handler that will start the calcRoute function when
    //  the go button is clicked.
    $("form#routes").on("submit", function (e) {

        measurementMode = $("#measurement-mode").val();
        metricUnit = measurementMode == "miles" ? "ft" : "m";
        e.preventDefault();
        calcRoute();
    });

    initialize_maps();
    initAutoComplete('from');
    initAutoComplete('to');

    if (from != "null" && to != "null") {
        calcRoute();
    }
});

function initialize_maps() {
    // Set ability to make route draggable.
    var rendererOptions = {
        draggable: true,
        hideRouteList: true,
        polylineOptions: {
            strokeOpacity: 0
        }
    };
    // Initialize the directions renderer.
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    var mapCanvas = $('#map-canvas').get(0);
    var mapOptions = {
        center: new google.maps.LatLng(37.787930,-122.4074990),
        zoom: 13,
        // Disables zoom and streetview bar but can stil zoom with mouse.
        disableDefaultUI: false,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    // Create a google maps object.
    map = new google.maps.Map(mapCanvas, mapOptions);
    directionsDisplay.setMap(map);
    // Add elevation service.
    elevator = new google.maps.ElevationService();

    // Set up listener to change path elevation information if the user
    // clicks on another suggested route.
    google.maps.event.addListener(
        directionsDisplay,
        'routeindex_changed',
        updateRoutes
    );
}

function initAutoComplete(field) {
    var input = document.getElementById(field);
    autocomplete = new google.maps.places.Autocomplete(input);

    // Prevent form submission when selecting place with enter.
    // http://stackoverflow.com/questions/11388251/google-autocomplete-enter-to-select
    $('#' + field).keydown(function (e) {
      if (e.which == 13 && $('.pac-container:visible').length)
        return false;
    });
}

function calcRoute() {
    var start = $("#from").val() || $("#from").attr("placeholder");
    var end = $("#to").val() || $("#to").attr("placeholder");
    var travelMode = $("#travel-mode").val();
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode[travelMode.toUpperCase()]
    };
    var DirectionsService = new google.maps.DirectionsService();
    DirectionsService.route(request, function(result, status) {
        if (status === "NOT_FOUND") {
            alert("No directions found.");
            return;
        }
        // Checks region for directions eligibility.
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });
    sharableLink(start, end, travelMode);
}
function sharableLink(start, end, travelMode) {
    // Update url to include sharable link
    history.replaceState('null', 'Flat Route Finder', '?from=' + encodeURLParameter(start) + '&to=' + encodeURLParameter(end) +
        '&travelMode=' + travelMode + '&measurementMode=' + measurementMode);
}

var updating = false;
function updateRoutes() {
    if (updating) return;
    updating = true;
    setTimeout(function () { updating = false; }, 100);
    console.log("Updating routes");
    // Check if the path has been populated, if it has been already
    // populated, clear it.

    var routes = this.directions.routes;
    var path = routes[this.routeIndex].overview_path;
    distance = routes[this.routeIndex].legs[0].distance;
    duration = routes[this.routeIndex].legs[0].duration;

    /* Shows distance in miles or kilometres, depending on measurement mode. */
    if(measurementMode == "miles"){
        $("#distance").html(distance.text);
    }
    else{
        $("#distance").html((distance.value / 1000) + "Km");
    }

    $("#travel-time").html(duration.text);
    $(".travel-info").show();
    newPath(path, distance.value);
}

function newPath(path) {
        var pathRequest = {
        'path': path,
        'samples': 300
    };
        // Initiate the path request.
    elevator.getElevationAlongPath(pathRequest, plotElevation);
}
// Take an array of elevation result objects, draws a path on the map
// and plots the elevation profile on the chart.
function plotElevation(elevations, status) {
    var slope, data, i, slopeChart, elevationChart, slopeChartDiv;
    if (status !== google.maps.ElevationStatus.OK) {
        alert("Error getting elevation data from Google");
        return;
    }
    // Create a new chart in the elevation chart div.
    elevationChartDiv = $("#elevation_chart").css('display', 'block');
    // Extract the data to populate the chart.
    map.elevationData = new google.visualization.DataTable();
    map.elevationData.addColumn('string', 'Sample');
    map.elevationData.addColumn('number', 'Elevation');
    map.elevationData.locations = [];
    map.elevationData.elevation = [];
    for (i = 0; i < elevations.length; i++) {

        // Change elevation from meters to feet.
        //console.log(measurementMode);
        if(measurementMode == "miles"){
            feetMultiplicator = 3.28084;
        }
        else{
            feetMultiplicator = 1;
        }

        map.elevationData.addRow([
            '',
            elevations[i].elevation * feetMultiplicator
        ]);
        map.elevationData.locations.push( elevations[i].location );
        map.elevationData.elevation.push( elevations[i].elevation * feetMultiplicator );

    }

    // Draw the chart using the data within its div.

    elevationChart = new google.visualization.ColumnChart(elevationChartDiv.get(0));
    elevationChart.draw(map.elevationData, {
        // width: 500,
        // height: 245,
        legend: 'none',
        titleY: 'Elevation ('+metricUnit+')'
    });
    changeElevation(elevationChart, elevations);
}
function changeElevation(elevationChart, elevations) {
    // Create event listenter on slope to show location and elevation.
    google.visualization.events.addListener(elevationChart, 'onmouseover', elevationHover);
    google.visualization.events.addListener(elevationChart, 'onmouseout',
        elevationClear);

    plotSlope(elevations);
}
function plotSlope(elevations){
    slopeChartDiv = $("#slope_chart").css('display', 'block');
    // Extract the data to populate the chart.
    map.slopeData = new google.visualization.DataTable();
    map.slopeData.addColumn('string', 'Sample');
    map.slopeData.addColumn('number', 'Slope');

    // Loop through each element of the elevation data,
    // call the calc slope function using elevations.legth[i]
    // and elevations.length[i+1]
    // Create a slopes array so we can search through it later
    slopes = [];
    for (i = 0; i < elevations.length - 1; i++) {
        slope = (calcSlope(elevations[i+1].elevation, elevations[i].elevation, distance.value/300)) * 100;
        map.slopeData.addRow(['', slope]);
        slopes.push({
            slope: slope,
            location: midpoint(elevations[i], elevations[i+1])
        });
    }

// Draw the chart using the slope data within its div.
    slopeChart = new google.visualization.ColumnChart(slopeChartDiv.get(0));
    slopeChart.draw(map.slopeData, {
        // width: 500,
        // height: 245,
        legend: 'none',
        titleY: 'slope %'
    });
    $('.chart').removeClass('hide');
    changeSlope(slopeChart, elevations, slopes);
}
function changeSlope(slopeChart, elevations, slopes) {
    // Create event listenter on slope to show location and slope.
    google.visualization.events.addListener(slopeChart, 'onmouseover', elevationHover);
    google.visualization.events.addListener(slopeChart, 'onmouseout',
        elevationClear);
    drawPolyline(elevations, slopes);
}

function removePolylines() {
    for (var i = 0; i < mapPaths.length; i++) {
        var path = mapPaths[i];
        path.setMap(null);
    }

    mapPaths = [];
}

function drawPolyline (elevations, slopes) {
    // Create a polyline between each elevation, color code by slope.
    // Remove any existing polylines before drawing a new polyline.
    removePolylines();

    for (var i = 0; i < slopes.length; i++) {
        var routePath = [
            elevations[i].location,
            elevations[i+1].location
        ];
        var absSlope = Math.abs(slopes[i].slope);
        if (absSlope <= 5) {
            pathColor = "#3CB371";
        } else if (absSlope <= 10) {
            pathColor = "#FFFF00";
        } else if (absSlope <= 15) {
            pathColor = "#FF9800";
        } else if (absSlope <= 20) {
            pathColor = "#F44336";
        }
        else {
            pathColor = "#000000";
        }
        mapPath = new google.maps.Polyline({
            path: routePath,
            strokeColor: pathColor,
            strokeOpacity: 0.8,
            strokeWeight: 5,
            draggable: true
        });
        mapPath.setMap(map);
        mapPaths.push(mapPath);
    }
}

function deg(slope) {
    return Math.floor(slope * 45) / 100;
}

function elevationHover (x) {
    // Show location on the map.
    var location = map.elevationData.locations[x.row];
    var elevation = map.elevationData.elevation[x.row];
    var slope = slopes[x.row].slope;
    var contentString = "Elevation: " + Math.round(elevation) + " " + metricUnit + "<br>" +
        "Slope: " + Math.round(slope) + "% (" + deg(slope) + "°)";

    map.locationMarker = new google.maps.Marker({
        position: location,
        map: map,
        labelContent: "Lat: " + location.lat() + ". Lng: " + location.lng() +
            ". Elevation: " + elevation
    });
    addinfoWindow(contentString);
}
function addinfoWindow(contentString) {
    // Add info window to the map.
    map.infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    map.infowindow.open(map, map.locationMarker);
}
function elevationClear (x) {
    map.locationMarker.setMap(null);
}

function midpoint(point1, point2) {
    // To get the midpoint, find the average between each respective point
    var lat = (point1.location.lat() + point2.location.lat()) / 2;
    var lng = (point1.location.lng() + point2.location.lng()) / 2;
    return new google.maps.LatLng(lat, lng);
}

// Calculate slope using elevation change between two points
// over a given distance in m, the distance between each measurement.
function calcSlope(elev1M, elev2M, distanceM) {
    slope = (elev1M - elev2M) / distanceM;
    return slope;
}

// Gets the 'to' and 'from' url Parameter for sharing links
// Source: http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
function getURLParameter(name) {
    return decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)')
        .exec(location.search)||[,null])[1]);
}

//change spaces to plus(+) sign
function encodeURLParameter(str) {
  return encodeURIComponent(str).replace(/%20/g, "+");
}

//change plus(+) sign to spaces
function decodeURLParameter(str) {
  return decodeURIComponent(str).replace(/[!'()]/g, escape)
    .replace(/\+/g, " ");
}
<|endoftext|>


<commit_before>const bus = new Vue()

function isNumber (str) {
  return typeof str === 'string' && /^-?(\d+\.?\d*|\.\d+)$/.test(str)
}

function fixFloatCalculation (o, a, b) {
  const aa = String(a).split('.')
  const bb = String(b).split('.')
  if (aa[1] || bb[1]) {
    const al = aa[1] ? aa[1].length : 0
    const bl = bb[1] ? bb[1].length : 0
    const m = Math.pow(10, Math.max(al, bl))
    switch (o) {
      case '+':
        return (a * m + b * m) / m
      case '-':
        return (a * m - b * m) / m
      case '×':
        return (a * m) * (b * m) / (m * m)
      case '÷':
        return (a * m) / (b * m)
    }
  } else {
    switch (o) {
      case '+':
        return a + b
      case '-':
        return a - b
      case '×':
        return a * b
      case '÷':
        return a / b
    }
  }
}

function compute (arr) {
  arr = [].concat(arr)
  if (arr.length <= 1) {
    if (!isNumber(arr[0])) {
      console.log('Illegal formula')
    }
    return +arr[0]
  }
  if (arr[0] === '(' && arr[arr.length - 1] === ')') {
    return compute(arr.slice(1, -1))
  }
  let right = arr
  let left = []
  let parentheseDiff = 0
  let item = ''
  while (item = right.shift()) {
    switch (item) {
      case '%':
        left.push('/')
        left.push('100')
        break
      case '(':
        parentheseDiff++
        left.push(item)
        break
      case ')':
        parentheseDiff--
        left.push(item)
        break
      case '+':
        if (parentheseDiff) {
          left.push('+')
          break
        }
        return fixFloatCalculation('+', compute(left), compute(right))
      case '-':
        if (parentheseDiff) {
          left.push('-')
          break
        }
        return fixFloatCalculation('-', compute(left), compute(right))
      default:
        left.push(item)
    }
  }
  parentheseDiff = 0
  while (item = left.pop()) {
    switch (item) {
      case ')':
        parentheseDiff++
        right.unshift(item)
        break
      case '(':
        parentheseDiff--
        right.unshift(item)
        break
      case '×':
        if (parentheseDiff) {
          right.unshift('×')
          break
        }
        return fixFloatCalculation('×', compute(left), compute(right))
      case '÷':
        if (parentheseDiff) {
          right.unshift('÷')
          break
        }
        return fixFloatCalculation('÷', compute(left), compute(right))
      default:
        right.unshift(item)
    }
  }
  console.log('Illegal formula')
}

Vue.component('display', {
  template: '#display-template',
  data () {
    return {
      items: [],
      answer: 0
    }
  },
  computed: {
    expression () {
      return this.items.join('')
    },
    parentheseDiff () {
      return this.items.reduce((acc, val) => {
        if (val === '(') {
          return acc + 1
        } else if (val === ')') {
          return acc - 1
        } else {
          return acc
        }
      }, 0)
    }
  },
  mounted () {
    bus.$on('input', val => {
      let items = this.items
      let lastItem = items[items.length - 1]
      if (lastItem === '=') {
        items.length = 0
        lastItem = null
      }
      switch (val) {
        case 'C':
          this.cleanAll()
          return
        case '=':
          this.computeAnswer()
          return
        case '±':
          if (!lastItem) {
            items.push(this.answer >= 0 ? '-' + this.answer : -this.answer + '')
            return
          }
          items.pop()
          if (isNumber(lastItem) && lastItem[0] === '-') {
            items.push(lastItem.slice(1))
          } else {
            items.push('-' + lastItem)
          }
          return
        case '%':
          if (!lastItem) {
            items.push(this.answer)
            return
          }
          if (!isNumber(lastItem)) {
            items.pop()
          }
          items.push('%')
          return
        case '.':
          if (isNumber(lastItem) && !lastItem.includes('.')) {
            items.pop()
            items.push(lastItem + '.')
          } else {
            items.push('.')
          }
          return
        case '+':
        case '-':
        case '×':
        case '÷':
          if (!lastItem) {
            items.push(this.answer + '')
          } else if (['+', '-', '×', '÷', '%'].includes(lastItem)) {
            items.pop()
          }
          items.push(val)
          return
        case ')':
          if (this.parentheseDiff) {
            items.push(val)
          }
          return
        default:
          if ((lastItem === '.' || isNumber(lastItem)) && isNumber(val)) {
            if (lastItem === '0') {
              items.pop()
              items.push(val)
              return
            }
            items.pop()
            items.push(lastItem + val)
          } else {
            items.push(val)
          }
      }
    })
  },
  methods: {
    cleanAll () {
      this.items = []
      this.answer = 0
    },
    computeAnswer () {
      if (!this.items.length) {
        return
      }
      try {
        // this.answer = eval(this.expression.replace(/×/g, '*').replace(/÷/g, '/').replace(/%/g, '/100'))
        this.answer = compute(this.items)
      } catch (e) {
        this.answer = 'Error'
        console.log(e)
      }
      this.items.push('=')
    },
    clearEnter () {
      lastItem = this.items.pop()
      if (lastItem && lastItem.length > 1) {
        this.items.push(lastItem.slice(0, -1))
      }
    }
  },
  filters: {
    short (answer, length) {
      if (!isFinite(answer) || String(answer).length <= length) {
        return answer
      }
      answer = answer.toPrecision(length - 3)
      let [mantissa, exponent] = String(answer).split('e')
      if (mantissa.length + exponent.length + 1 > length) {
        answer = mantissa.substr(0, length - 1 - exponent.length) + 'e' + exponent
      }
      return answer
    }
  }
})

Vue.component('panel', {
  template: '#panel-template',
  data () {
    return {
      showMore: false,
      buttons: [
        ['C', '±', '%', '÷'],
        ['7', '8', '9', '+'],
        [{main: '4', more: '('}, '5', '6', '-'],
        [{main: '1', more: ')'}, '2', '3', '×'],
        [{main: '...', more: '⏎'}, '0', '.', '=']
      ]
    }
  },
  methods: {
    getButtonContent (item) {
      return this.showMore && item.more ? item.more : item.main || item
    },
    buttonAction (e) {
      const val = e.currentTarget.value
      switch (val) {
        case '...':
          this.showMore = true
          break
        case '⏎':
          this.showMore = false
          break
        default:
          bus.$emit('input', val)
      }
    }
  }
})

new Vue({
  el: '#calculator'
})

// 暴力解决iOS10 Safari不识别viewport禁用缩放
document.documentElement.addEventListener('touchstart', function (event) {
  if (event.touches.length > 1) {
    event.preventDefault()
  }
}, false)
var lastTouchEnd = 0
document.documentElement.addEventListener('touchend', function (event) {
  var now = Date.now()
  if (now - lastTouchEnd <= 300) {
    event.preventDefault()
  }
  lastTouchEnd = now
}, false)
<commit_msg>Add some test code<commit_after>const bus = new Vue()

function isNumber (str) {
  return typeof str === 'string' && /^-?(\d+\.?\d*|\.\d+)$/.test(str)
}

function fixFloatCalculation (o, a, b) {
  const aa = String(a).split('.')
  const bb = String(b).split('.')
  if (aa[1] || bb[1]) {
    const al = aa[1] ? aa[1].length : 0
    const bl = bb[1] ? bb[1].length : 0
    const m = Math.pow(10, Math.max(al, bl))
    switch (o) {
      case '+':
        return (a * m + b * m) / m
      case '-':
        return (a * m - b * m) / m
      case '×':
        return (a * m) * (b * m) / (m * m)
      case '÷':
        return (a * m) / (b * m)
    }
  } else {
    switch (o) {
      case '+':
        return a + b
      case '-':
        return a - b
      case '×':
        return a * b
      case '÷':
        return a / b
    }
  }
}

function compute (arr) {
  arr = [].concat(arr)
  if (arr.length <= 1) {
    if (!isNumber(arr[0])) {
      console.log('Illegal formula')
    }
    return +arr[0]
  }
  if (arr[0] === '(' && arr[arr.length - 1] === ')') {
    return compute(arr.slice(1, -1))
  }
  let right = arr
  let left = []
  let parentheseDiff = 0
  let item = ''
  while (item = right.shift()) {
    switch (item) {
      case '%':
        left.push('÷')
        left.push('100')
        break
      case '(':
        parentheseDiff++
        left.push(item)
        break
      case ')':
        parentheseDiff--
        left.push(item)
        break
      case '+':
        if (parentheseDiff) {
          left.push('+')
          break
        }
        return fixFloatCalculation('+', compute(left), compute(right))
      case '-':
        if (parentheseDiff) {
          left.push('-')
          break
        }
        return fixFloatCalculation('-', compute(left), compute(right))
      default:
        left.push(item)
    }
  }
  parentheseDiff = 0
  while (item = left.pop()) {
    switch (item) {
      case ')':
        parentheseDiff++
        right.unshift(item)
        break
      case '(':
        parentheseDiff--
        right.unshift(item)
        break
      case '×':
        if (parentheseDiff) {
          right.unshift('×')
          break
        }
        return fixFloatCalculation('×', compute(left), compute(right))
      case '÷':
        if (parentheseDiff) {
          right.unshift('÷')
          break
        }
        return fixFloatCalculation('÷', compute(left), compute(right))
      default:
        right.unshift(item)
    }
  }
  console.log('Illegal formula')
}

Vue.component('display', {
  template: '#display-template',
  data () {
    return {
      items: [],
      answer: 0
    }
  },
  computed: {
    expression () {
      return this.items.join('')
    },
    parentheseDiff () {
      return this.items.reduce((acc, val) => {
        if (val === '(') {
          return acc + 1
        } else if (val === ')') {
          return acc - 1
        } else {
          return acc
        }
      }, 0)
    }
  },
  mounted () {
    bus.$on('input', val => {
      let items = this.items
      let lastItem = items[items.length - 1]
      if (lastItem === '=') {
        items.length = 0
        lastItem = null
      }
      switch (val) {
        case 'C':
          this.cleanAll()
          return
        case '=':
          this.computeAnswer()
          return
        case '±':
          if (!lastItem) {
            items.push(this.answer >= 0 ? '-' + this.answer : -this.answer + '')
            return
          }
          items.pop()
          if (isNumber(lastItem) && lastItem[0] === '-') {
            items.push(lastItem.slice(1))
          } else {
            items.push('-' + lastItem)
          }
          return
        case '%':
          if (!lastItem) {
            items.push(this.answer)
            return
          }
          if (!isNumber(lastItem)) {
            items.pop()
          }
          items.push('%')
          return
        case '.':
          if (isNumber(lastItem) && !lastItem.includes('.')) {
            items.pop()
            items.push(lastItem + '.')
          } else {
            items.push('.')
          }
          return
        case '+':
        case '-':
        case '×':
        case '÷':
          if (!lastItem) {
            items.push(this.answer + '')
          } else if (['+', '-', '×', '÷', '%'].includes(lastItem)) {
            items.pop()
          }
          items.push(val)
          return
        case ')':
          if (this.parentheseDiff) {
            items.push(val)
          }
          return
        default:
          if ((lastItem === '.' || isNumber(lastItem)) && isNumber(val)) {
            if (lastItem === '0') {
              items.pop()
              items.push(val)
              return
            }
            items.pop()
            items.push(lastItem + val)
          } else {
            items.push(val)
          }
      }
    })
  },
  methods: {
    cleanAll () {
      this.items = []
      this.answer = 0
    },
    computeAnswer () {
      if (!this.items.length) {
        return
      }
      try {
        // this.answer = eval(this.expression.replace(/×/g, '*').replace(/÷/g, '/').replace(/%/g, '/100'))
        this.answer = compute(this.items)
      } catch (e) {
        this.answer = 'Error'
        console.log(e)
      }
      this.items.push('=')
    },
    clearEnter () {
      lastItem = this.items.pop()
      if (lastItem && lastItem.length > 1) {
        this.items.push(lastItem.slice(0, -1))
      }
    }
  },
  filters: {
    short (answer, length) {
      if (!isFinite(answer) || String(answer).length <= length) {
        return answer
      }
      answer = String(answer.toPrecision(length))
      if (!answer.includes('e')) {
        return answer.substr(0, length)
      }
      let [mantissa, exponent] = String(answer).split('e')
      if (mantissa.length + exponent.length + 1 > length) {
        answer = mantissa.substr(0, length - 1 - exponent.length) + 'e' + exponent
      }
      return answer
    }
  }
})

Vue.component('panel', {
  template: '#panel-template',
  data () {
    return {
      showMore: false,
      buttons: [
        ['C', '±', '%', '÷'],
        ['7', '8', '9', '+'],
        [{main: '4', more: '('}, '5', '6', '-'],
        [{main: '1', more: ')'}, '2', '3', '×'],
        [{main: '...', more: '⏎'}, '0', '.', '=']
      ]
    }
  },
  methods: {
    getButtonContent (item) {
      return this.showMore && item.more ? item.more : item.main || item
    },
    buttonAction (e) {
      const val = e.currentTarget.value
      switch (val) {
        case '...':
          this.showMore = true
          break
        case '⏎':
          this.showMore = false
          break
        default:
          bus.$emit('input', val)
      }
    }
  }
})

new Vue({
  el: '#calculator'
})

// 暴力解决iOS10 Safari不识别viewport禁用缩放
document.documentElement.addEventListener('touchstart', function (event) {
  if (event.touches.length > 1) {
    event.preventDefault()
  }
}, false)
var lastTouchEnd = 0
document.documentElement.addEventListener('touchend', function (event) {
  var now = Date.now()
  if (now - lastTouchEnd <= 300) {
    event.preventDefault()
  }
  lastTouchEnd = now
}, false)

module.exports = {
  fixFloatCalculation,
  compute
}<|endoftext|>


<commit_before>console.log("hello requireJS");
require(['Controller-AMD'], function(Controller) {
    Controller.initAll();
    localStorage.clear();
});<commit_msg>fix little bug<commit_after>console.log("hello requireJS");

// localStorage.clear();

require(['Controller-AMD'], function(Controller) {
    Controller.initAll();
});<|endoftext|>


<commit_before>var camera, scene;
var MTS = 1e7;
var PI = Math.PI;
var shipName;
var z0, x0;
var lifeSocket;

var tile38Host = "localhost";
var tile38 = "ws://" + tile38Host+ ":9851";

var socketHost = "localhost";
socketHost = "ws://" + socketHost + ":8080";

init();
animate();

function init() {
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth * 0.9, window.innerHeight * 0.8);

  var container = document.getElementById("three-container");
  container.appendChild(renderer.domElement);

  setKeys();

  lifeSocket = new WebSocket(socketHost);
  var collisionSocket = new WebSocket(socketHost);

  lifeSocket.onopen = function (event) {
    lifeSocket.send(JSON.stringify({message:"init"}));
    lifeSocket.send(JSON.stringify({message:"scan rocks"}));
  }

  lifeSocket.onmessage = function(event) {
    var data  = JSON.parse(event.data);
    if ( data.message == "init" ) {
      var angle = data.name;
      var lat = Number(data.lat);
      var lng = Number(data.lng);
      shipName = angle;
      angle = Number(angle);

      camera.position.z = z0 = lng * MTS;
      camera.position.x = x0 = lat * MTS;
      camera.rotateY((90-angle) * PI /180);

      showMessage("Welcome ship" + shipName);

      lifeSocket.send(JSON.stringify({
        message:"show collitions", name: shipName
      }));

      setInterval(sendPosition, 500);
      setInterval(function(){
        lifeSocket.send(JSON.stringify({message:"scan ships"}));
      }, 500);
    }
    if (data.message == "rocks")
      showRocks(data.data);
    if (data.message == "ships")
      show_ships(data.data);
    if (data.message == "show collitions")
      showCollition(data.data);
  }

}

function setKeys() {
  window.addEventListener('keydown', function(event) {
    switch (event.keyCode) {
      case 87: // w
        var direction = camera.getWorldDirection();
        camera.position.add( direction.multiplyScalar(20) );
        break;
      case 65: // a
        camera.rotateY(5*PI/180);
        break;
      case 68: // d
        camera.rotateY(-5*PI/180);
        break;
      case 32: // space
        break;
    }
  });
}

function sendPosition() {
  var lat = camera.position.x / MTS;
  var lng = camera.position.z / MTS;
  lifeSocket.send(JSON.stringify({
    message: "set position", name:shipName, lat:lat, lng:lng
  }));
}

function animate() {
  requestAnimationFrame(animate);

  for (const rock of scene.children) {
    rock.rotation.y += 0.01;
  }

  var direction = camera.getWorldDirection();
  camera.position.add( direction.multiplyScalar(4) );

  renderer.render(scene, camera);
}

function showCollition(data) {
  var data = JSON.parse(data);
  if (data.detect == 'roam') {
    camera.position.x = x0;
    camera.position.z = z0;
    var msg = "Ship" + shipName + " collision with rock " + data.nearby.id + "!";
    showMessage(msg);
    showMessage("Restarted");
  }
}

function showMessage(msg) {
  var msgBox = document.getElementsByClassName('log-history')[0];
  msgBox.innerHTML += new Date() + ": "+ msg + '
';
}

function showRocks(data) {
  var material = new THREE.MeshBasicMaterial({
    color: 0xF3E5F5,
    wireframe: true
  });

  for (const rock of data) {
    var name = rock[0];
    var coor = JSON.parse(rock[1]).coordinates;
    var lat = coor[0];
    var lng = coor[1];
    var geometry = new THREE.BoxGeometry(100, 400, 100);
    var mesh_rock  = new THREE.Mesh(geometry, material);
    mesh_rock.name = name;
    mesh_rock.position.x = lat * MTS;
    mesh_rock.position.z = lng * MTS;
    scene.add(mesh_rock);
  }
}

function show_ships(data) {
  var material = new THREE.MeshBasicMaterial({
    color: 0xFF0000,
    wireframe: true
  });

  for (const ship of data) {
    var name = ship[0];
    if ( name == shipName ) continue;
    var coor = JSON.parse(ship[1]).coordinates;
    var lat = coor[0] * MTS;
    var lng = coor[1] * MTS;
    var local_ship = scene.getObjectByName(name);
    if (local_ship) {
      local_ship.position.x = lat;
      local_ship.position.z = lng;
    } else {
      var geometry = new THREE.SphereGeometry(20, 10, 4);
      var mesh_ship  = new THREE.Mesh(geometry, material);
      mesh_ship.name = name;
      mesh_ship.position.x = lat;
      mesh_ship.position.z = lng;
      scene.add(mesh_ship);
    }
  }
}
<commit_msg>websocket server with static ip<commit_after>var camera, scene;
var MTS = 1e7;
var PI = Math.PI;
var shipName;
var z0, x0;
var lifeSocket;

var socketHost = "209.177.93.71";
socketHost = "ws://" + socketHost + ":8080";

init();
animate();

function init() {
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);

  scene = new THREE.Scene();

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth * 0.9, window.innerHeight * 0.8);

  var container = document.getElementById("three-container");
  container.appendChild(renderer.domElement);

  setKeys();

  lifeSocket = new WebSocket(socketHost);
  var collisionSocket = new WebSocket(socketHost);

  lifeSocket.onopen = function (event) {
    lifeSocket.send(JSON.stringify({message:"init"}));
    lifeSocket.send(JSON.stringify({message:"scan rocks"}));
  }

  lifeSocket.onmessage = function(event) {
    var data  = JSON.parse(event.data);
    if ( data.message == "init" ) {
      var angle = data.name;
      var lat = Number(data.lat);
      var lng = Number(data.lng);
      shipName = angle;
      angle = Number(angle);

      camera.position.z = z0 = lng * MTS;
      camera.position.x = x0 = lat * MTS;
      camera.rotateY((90-angle) * PI /180);

      showMessage("Welcome ship" + shipName);

      lifeSocket.send(JSON.stringify({
        message:"show collitions", name: shipName
      }));

      setInterval(sendPosition, 500);
      setInterval(function(){
        lifeSocket.send(JSON.stringify({message:"scan ships"}));
      }, 500);
    }
    if (data.message == "rocks")
      showRocks(data.data);
    if (data.message == "ships")
      show_ships(data.data);
    if (data.message == "show collitions")
      showCollition(data.data);
  }

}

function setKeys() {
  window.addEventListener('keydown', function(event) {
    switch (event.keyCode) {
      case 87: // w
        var direction = camera.getWorldDirection();
        camera.position.add( direction.multiplyScalar(20) );
        break;
      case 65: // a
        camera.rotateY(5*PI/180);
        break;
      case 68: // d
        camera.rotateY(-5*PI/180);
        break;
      case 32: // space
        break;
    }
  });
}

function sendPosition() {
  var lat = camera.position.x / MTS;
  var lng = camera.position.z / MTS;
  lifeSocket.send(JSON.stringify({
    message: "set position", name:shipName, lat:lat, lng:lng
  }));
}

function animate() {
  requestAnimationFrame(animate);

  for (const rock of scene.children) {
    rock.rotation.y += 0.01;
  }

  var direction = camera.getWorldDirection();
  camera.position.add( direction.multiplyScalar(4) );

  renderer.render(scene, camera);
}

function showCollition(data) {
  var data = JSON.parse(data);
  if (data.detect == 'roam') {
    camera.position.x = x0;
    camera.position.z = z0;
    var msg = "Ship" + shipName + " collision with rock " + data.nearby.id + "!";
    showMessage(msg);
    showMessage("Restarted");
  }
}

function showMessage(msg) {
  var msgBox = document.getElementsByClassName('log-history')[0];
  msgBox.innerHTML += new Date() + ": "+ msg + '
';
}

function showRocks(data) {
  var material = new THREE.MeshBasicMaterial({
    color: 0xF3E5F5,
    wireframe: true
  });

  for (const rock of data) {
    var name = rock[0];
    var coor = JSON.parse(rock[1]).coordinates;
    var lat = coor[0];
    var lng = coor[1];
    var geometry = new THREE.BoxGeometry(100, 400, 100);
    var mesh_rock  = new THREE.Mesh(geometry, material);
    mesh_rock.name = name;
    mesh_rock.position.x = lat * MTS;
    mesh_rock.position.z = lng * MTS;
    scene.add(mesh_rock);
  }
}

function show_ships(data) {
  var material = new THREE.MeshBasicMaterial({
    color: 0xFF0000,
    wireframe: true
  });

  for (const ship of data) {
    var name = ship[0];
    if ( name == shipName ) continue;
    var coor = JSON.parse(ship[1]).coordinates;
    var lat = coor[0] * MTS;
    var lng = coor[1] * MTS;
    var local_ship = scene.getObjectByName(name);
    if (local_ship) {
      local_ship.position.x = lat;
      local_ship.position.z = lng;
    } else {
      var geometry = new THREE.SphereGeometry(20, 10, 4);
      var mesh_ship  = new THREE.Mesh(geometry, material);
      mesh_ship.name = name;
      mesh_ship.position.x = lat;
      mesh_ship.position.z = lng;
      scene.add(mesh_ship);
    }
  }
}
<|endoftext|>