<commit_before>var time = 0; var started = 0; var running = 0;

function startTime(){
  if(running == 0){
    running = 1
    increment();
    document.getElementById(swButtonGo.innerHTML = "PAUSE");
    document.getElementById(swButtonGoModal.innerHTML = "PAUSE");
  } else{
    running = 0;
    document.getElementById(swButtonGo.innerHTML = "RESUME");
    document.getElementById(swButtonGoModal.innerHTML = "RESUME");
  }
};
function reset(){
  time = 0; running = 0;
  document.getElementById(swButtonGo.innerHTML = "START");
  document.getElementById(swButtonGoModal.innerHTML = "START");
  document.getElementById("swdisplay").innerHTML = '00:00:00';
  document.getElementById("swmodal").innerHTML =  '00:00:00';
};
function increment(){

  if(running == 1){  //runs Stopwatch
    setTimeout(function(){
      time++;
      var z = ":";var zs = ":0";var zm = ":0";var zh = "0";
      var seconds = Math.floor(time/10);
      var minutes = Math.floor(time/10/60);
      var hours = Math.floor(time/10/60/60);
      var mins = minutes;var secs = seconds;

      if(seconds > 59){secs = seconds - (Math.floor(seconds/60))* 60;
      } //keeps secs under 60
      if(minutes > 59){mins = minutes - (Math.floor(minutes/60))* 60;
      } // keeps mins under 60

      if (secs > 9){zs = ":";};if (mins > 9){zm = ":";};if (hours > 9){zh = ":";};
      document.getElementById("swdisplay").innerHTML = zh + hours + zm + mins + zs + secs;
      document.getElementById("swmodal").innerHTML = zh + hours + zm + mins + zs + secs;
      increment();
      }, 100);
    }
};

$( "#swButtonGo" ).click(startTime);
$("#swReset").click(reset);

//Stopwatch Modal
function modalOn(){
  $(".swmodal").css("display", "block");
};
function modalOff(){
  $(".swmodal").css("display", "none");
};

$("#fullBtnS").click(modalOn);  //open fullscreen

var modal = document.getElementById('#modal');

$("#modal").click(function() {
          modalOff();
  });

$( "#swButtonGoModal" ).click(startTime);
$("#swResetModal").click(reset);

//END Stop Watch/////////////////////////////////////

//Start Timer
var time = 0; var started = 0; var running = 0;
var timerTime = [0,0,0,0,0,0];
var tt = timerTime;
var tdisplay = tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
var test = tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
var pushed = 0;
var tReset = 0; //stops timer and resets
var run = 0; // for pausing
var tRunCount = 0; //to keep count when paused
var runTime = ""//kept time while paused
//For adding numbers manually
$('.numBtn').click(function(){
  tt.shift();
  tt.push(this.innerHTML);
  pushed++;
  tdisplay = tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
  });

function timerStart(){
  var h = ((tt[0] + tt[1]) *3600);
  var m = ((tt[2] +""+ tt[3]) * 60);
  var s = (tt[4] + "" + tt[5]);
  var countDownTime = (Number(h) + Number(m) + Number(s))-1;
  tReset = 0;
  if(run == 0 && tRunCount == 0){ //first run
    run = 1;
    countDown(countDownTime);
    document.getElementById(timerSbtn.innerHTML = "Pause");
    document.getElementById(tmStartBtnModal.innerHTML = "Pause");
  } else if (run == 1 && tRunCount == 0) { //first pause
    run = 0;
    tRunCount = 1;
    document.getElementById(timerSbtn.innerHTML = "Resume");
    document.getElementById(tmStartBtnModal.innerHTML = "Resume");
  } else if (run == 0 && tRunCount == 1){ //continues timer where left off at pause
    run = 1;
    countDown(runTime);
    document.getElementById(timerSbtn.innerHTML = "Pause");
    document.getElementById(tmStartBtnModal.innerHTML = "Pause");
  } else { //secondary pause
    run = 0;
    document.getElementById(timerSbtn.innerHTML = "Resume");
    document.getElementById(tmStartBtnModal.innerHTML = "Resume");
  };
}
//Timer countdown
function countDown(count){
   setTimeout(function(){
     if (count == 0){         //rings bell at zero
       $("#bell").get(0).play();
       timerReset();

     };//bell

     if(count>-1 && tReset == 0  && run == 1){      //cycles timer
       var hr = Math.floor(count/3600);
       var mn = Math.floor((count%3600)/60);
       var sec = Math.floor(count -hr*3600 - mn*60);

       if (hr<10){hr = "0" + hr;} else {hr=hr};
       if (mn<10){mn = "0" + mn;} else{mn = mn};
       if (sec<10){sec = "0" + sec;}else {sec = sec};
       count --;
       document.getElementById("tmDisplay").innerHTML = hr + ":" + mn + ":" + sec;
       document.getElementById("tmModal").innerHTML = hr + ":" + mn + ":" + sec;
       countDown(count);
       runTime = count;

     } //end timer count

   }, 1000);
  if(count == 0 && tReset == 0){
       tt=[0,0,0,0,0,0];
     }; //resets timer at zero
};
function timerReset(){
  pushed = 0
   tt = [0,0,0,0,0,0];
  document.getElementById("tmDisplay").innerHTML = "00:00:00";
  document.getElementById("tmModal").innerHTML = "00:00:00";
  tRunCount = 0;
  tReset = 1;
  tRunCount == 0;
  document.getElementById(timerSbtn.innerHTML = "Start");
  document.getElementById(tmStartBtnModal.innerHTML = "Start");
  run = 0
}
//timer start BTN
$("#timerSbtn").click(function(){
  if($("#tmModalCheck").prop("checked")){
    timerStart();
    $(".tmModal").css("display", "block");
    console.log("here");
  }else{
    timerStart();
  }
});
//Reset Button
$("#timerRbtn").click(timerReset);
$("#tmResetBtnModal").click(timerReset);

//Shortcut buttons
$("#min5").click(function(){
  tt = [0,0,0,5,0,0];
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
})

$("#min10").click(function(){
  tt = [0,0,1,0,0,0];
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
})

$("#min15").click(function(){
  tt = [0,0,1,5,0,0];
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
})

$("#min20").click(function(){
  tt = [0,0,2,0,0,0];
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
})

$("#min30").click(function(){
  tt = [0,0,3,0,0,0];
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
})

$("#min60").click(function(){
  tt = [0,1,0,0,0,0];
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
})

//End Timer

//Timer Modal

//Stopwatch Modal
function tmModalOff(){
  $(".tmModal").css("display", "none");
};

function tmModalOn(){
  $(".tmModal").css("display", "block");
};

$("#tmModalBG").click(tmModalOff); //closes Timer Modal

$("#fullBtnT").click(tmModalOn); // opens timer Modal

$("#tmStartBtnModal").click(function(){

  if($("#tmModalCheck").prop("checked")){
    timerStart();
    $(".tmModal").css("display", "block");
  }else{
    timerStart();
  }
});
$("#tmResetBtnModal").click(reset);

//Turn///////////////////////////////////////////////////////////
$(document).ready(function(){

//when textbox is focused
  function clear(){
    $(this).val("");
    y=1; //resets id counter for li
  }
  $("#textbox").focus(clear);

 //BUTTON FUNCTION
  var y = 1; //count of id for li
  //pull random number from array

  function $getNum(){
    // clears ul
    $("#display").empty();
    //clear inout field

      //create array with numbers up to input
var num = $("#textbox").val();
var array1 = [];
for(i = 1; i <= num; i++ ){
  array1.push(i);

};// end for loop

    for(var x = array1.length ; x > 0; x--){
      // create random number <= array length
    var pos = Math.floor((Math.random() * x));
      // pull position in array
    var newNum = array1[pos];

    var newLi = "";
      //create the html
      newLi += "
" + newNum + "
";

      y+=1; //adjusts id for li

      //adds new html to ul
      $("#display").append(newLi);

    //delete number from array
      array1.splice(pos,1);
    }//end
    $("#textbox").val("Submit new number please");
  };// end button

    $("button").click($getNum);

  function handle(){
    console.log(event.which)
    if(event.which == 13){

      $getNum();
      $("#textbox").val("");

    }
  };
  document.getElementById("textbox").addEventListener("keypress", handle)

  //boxes disappear when clicked
  $("#display").click(function(){
    $( "ul li:nth-child(1)" ).remove();
    console.log($("#bx1.text"));
  });
  });//end document

  //when textbox is focusout
  /**
  $("#textbox").focusout(function(){
    $(this).val("Total number of students");
  })
  This seems to take priority**/

<commit_msg>timer shorcut button resets timer on click<commit_after>var time = 0; var started = 0; var running = 0;

function startTime(){
  if(running == 0){
    running = 1
    increment();
    document.getElementById(swButtonGo.innerHTML = "PAUSE");
    document.getElementById(swButtonGoModal.innerHTML = "PAUSE");
  } else{
    running = 0;
    document.getElementById(swButtonGo.innerHTML = "RESUME");
    document.getElementById(swButtonGoModal.innerHTML = "RESUME");
  }
};
function reset(){
  time = 0; running = 0;
  document.getElementById(swButtonGo.innerHTML = "START");
  document.getElementById(swButtonGoModal.innerHTML = "START");
  document.getElementById("swdisplay").innerHTML = '00:00:00';
  document.getElementById("swmodal").innerHTML =  '00:00:00';
};
function increment(){

  if(running == 1){  //runs Stopwatch
    setTimeout(function(){
      time++;
      var z = ":";var zs = ":0";var zm = ":0";var zh = "0";
      var seconds = Math.floor(time/10);
      var minutes = Math.floor(time/10/60);
      var hours = Math.floor(time/10/60/60);
      var mins = minutes;var secs = seconds;

      if(seconds > 59){secs = seconds - (Math.floor(seconds/60))* 60;
      } //keeps secs under 60
      if(minutes > 59){mins = minutes - (Math.floor(minutes/60))* 60;
      } // keeps mins under 60

      if (secs > 9){zs = ":";};if (mins > 9){zm = ":";};if (hours > 9){zh = ":";};
      document.getElementById("swdisplay").innerHTML = zh + hours + zm + mins + zs + secs;
      document.getElementById("swmodal").innerHTML = zh + hours + zm + mins + zs + secs;
      increment();
      }, 100);
    }
};

$( "#swButtonGo" ).click(startTime);
$("#swReset").click(reset);

//Stopwatch Modal
function modalOn(){
  $(".swmodal").css("display", "block");
};
function modalOff(){
  $(".swmodal").css("display", "none");
};

$("#fullBtnS").click(modalOn);  //open fullscreen

var modal = document.getElementById('#modal');

$("#modal").click(function() {
          modalOff();
  });

$( "#swButtonGoModal" ).click(startTime);
$("#swResetModal").click(reset);

//END Stop Watch/////////////////////////////////////

//Start Timer
var time = 0; var started = 0; var running = 0;
var timerTime = [0,0,0,0,0,0];
var tt = timerTime;
var tdisplay = tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
var test = tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
var pushed = 0;
var tReset = 0; //stops timer and resets
var run = 0; // for pausing
var tRunCount = 0; //to keep count when paused
var runTime = ""//kept time while paused
//For adding numbers manually
$('.numBtn').click(function(){
  tt.shift();
  tt.push(this.innerHTML);
  pushed++;
  tdisplay = tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
  });

function timerStart(){
  var h = ((tt[0] + tt[1]) *3600);
  var m = ((tt[2] +""+ tt[3]) * 60);
  var s = (tt[4] + "" + tt[5]);
  var countDownTime = (Number(h) + Number(m) + Number(s))-1;
  tReset = 0;
  if(run == 0 && tRunCount == 0){ //first run
    run = 1;
    countDown(countDownTime);
    document.getElementById(timerSbtn.innerHTML = "Pause");
    document.getElementById(tmStartBtnModal.innerHTML = "Pause");
  } else if (run == 1 && tRunCount == 0) { //first pause
    run = 0;
    tRunCount = 1;
    document.getElementById(timerSbtn.innerHTML = "Resume");
    document.getElementById(tmStartBtnModal.innerHTML = "Resume");
  } else if (run == 0 && tRunCount == 1){ //continues timer where left off at pause
    run = 1;
    countDown(runTime);
    document.getElementById(timerSbtn.innerHTML = "Pause");
    document.getElementById(tmStartBtnModal.innerHTML = "Pause");
  } else { //secondary pause
    run = 0;
    document.getElementById(timerSbtn.innerHTML = "Resume");
    document.getElementById(tmStartBtnModal.innerHTML = "Resume");
  };
}
//Timer countdown
function countDown(count){
   setTimeout(function(){
     if (count == 0){         //rings bell at zero
       $("#bell").get(0).play();
       timerReset();

     };//bell

     if(count>-1 && tReset == 0  && run == 1){      //cycles timer
       var hr = Math.floor(count/3600);
       var mn = Math.floor((count%3600)/60);
       var sec = Math.floor(count -hr*3600 - mn*60);

       if (hr<10){hr = "0" + hr;} else {hr=hr};
       if (mn<10){mn = "0" + mn;} else{mn = mn};
       if (sec<10){sec = "0" + sec;}else {sec = sec};
       count --;
       document.getElementById("tmDisplay").innerHTML = hr + ":" + mn + ":" + sec;
       document.getElementById("tmModal").innerHTML = hr + ":" + mn + ":" + sec;
       countDown(count);
       runTime = count;

     } //end timer count

   }, 1000);
  if(count == 0 && tReset == 0){
       tt=[0,0,0,0,0,0];
     }; //resets timer at zero
};
function timerReset(){
  pushed = 0
   tt = [0,0,0,0,0,0];
  document.getElementById("tmDisplay").innerHTML = "00:00:00";
  document.getElementById("tmModal").innerHTML = "00:00:00";
  tRunCount = 0;
  tReset = 1;
  tRunCount == 0;
  document.getElementById(timerSbtn.innerHTML = "Start");
  document.getElementById(tmStartBtnModal.innerHTML = "Start");
  run = 0
}
//timer start BTN
$("#timerSbtn").click(function(){
  if($("#tmModalCheck").prop("checked")){
    timerStart();
    $(".tmModal").css("display", "block");
    console.log("here");
  }else{
    timerStart();
  }
});
//Reset Button
$("#timerRbtn").click(timerReset);
$("#tmResetBtnModal").click(timerReset);

//Shortcut buttons
function btnReset(){ //shortcut button resets timer display
  tdisplay= tt[0] + "" + tt[1] + ":" + tt[2] + tt[3] + ":" + tt[4] + tt[5];
  document.getElementById("tmDisplay").innerHTML = tdisplay;
  document.getElementById("tmModal").innerHTML = tdisplay;
};

$("#min5").click(function(){
  timerReset();
  tt = [0,0,0,5,0,0];
  btnReset();
})

$("#min10").click(function(){
  timerReset();
  tt = [0,0,1,0,0,0];
  btnReset();
})

$("#min15").click(function(){
  timerReset();
  tt = [0,0,1,5,0,0];
  btnReset();;
})

$("#min20").click(function(){
  timerReset();
  tt = [0,0,2,0,0,0];
  btnReset();
})

$("#min30").click(function(){
  timerReset();
  tt = [0,0,3,0,0,0];
  btnReset();
})

$("#min60").click(function(){
  timerReset();
  tt = [0,1,0,0,0,0];
  btnReset();
})

//End Timer

//Timer Modal

//Stopwatch Modal
function tmModalOff(){
  $(".tmModal").css("display", "none");
};

function tmModalOn(){
  $(".tmModal").css("display", "block");
};

$("#tmModalBG").click(tmModalOff); //closes Timer Modal

$("#fullBtnT").click(tmModalOn); // opens timer Modal

$("#tmStartBtnModal").click(function(){

  if($("#tmModalCheck").prop("checked")){
    timerStart();
    $(".tmModal").css("display", "block");
  }else{
    timerStart();
  }
});
$("#tmResetBtnModal").click(reset);

//Turn///////////////////////////////////////////////////////////
$(document).ready(function(){

//when textbox is focused
  function clear(){
    $(this).val("");
    y=1; //resets id counter for li
  }
  $("#textbox").focus(clear);

 //BUTTON FUNCTION
  var y = 1; //count of id for li
  //pull random number from array

  function $getNum(){
    // clears ul
    $("#display").empty();
    //clear inout field

      //create array with numbers up to input
var num = $("#textbox").val();
var array1 = [];
for(i = 1; i <= num; i++ ){
  array1.push(i);

};// end for loop

    for(var x = array1.length ; x > 0; x--){
      // create random number <= array length
    var pos = Math.floor((Math.random() * x));
      // pull position in array
    var newNum = array1[pos];

    var newLi = "";
      //create the html
      newLi += "
" + newNum + "
";

      y+=1; //adjusts id for li

      //adds new html to ul
      $("#display").append(newLi);

    //delete number from array
      array1.splice(pos,1);
    }//end
    $("#textbox").val("Submit new number please");
  };// end button

    $("button").click($getNum);

  function handle(){
    console.log(event.which)
    if(event.which == 13){

      $getNum();
      $("#textbox").val("");

    }
  };
  document.getElementById("textbox").addEventListener("keypress", handle)

  //boxes disappear when clicked
  $("#display").click(function(){
    $( "ul li:nth-child(1)" ).remove();
    console.log($("#bx1.text"));
  });
  });//end document

  //when textbox is focusout
  /**
  $("#textbox").focusout(function(){
    $(this).val("Total number of students");
  })
  This seems to take priority**/

<|endoftext|>


<commit_before>$(function() {

	var todos = '';
	function standUp() {
		// get entries from localstorage if they exist.
		// populate the list with entries and ids.

		if(localStorage && localStorage.length > 0) {

			// run populateList to insert all the entries
			// populateList();
		} else {
			var a = [];
			localStorage.setItem('todos',JSON.stringify(a));
		}

		// setListners after the list has been built.
		populateList();
		setListeners();
	}
	function setListeners() {
		//listen for keypresses
		$('#new-todo').keyup(function(e) {
			// check which key has been pressed.
			checkKeyPress(e);
		})
	}

	function checkKeyPress(e) {
		// if the key is the 'enter' key
		if(e.keyCode == 13) {
			//save the entry to localStorage
			saveEntry();
		}
	}

	function checkEditPress(e) {
		if(e.keyCode == 13) {
			updateEntry();
		} else if(e.keyCode == 27) {
			abortEditing();
		}
	}

	// build the entire list based on the contents of localStorage
	function populateList() {
		todos = JSON.parse(localStorage.getItem('todos'));
		if(todos.length > 0) {
			for (var i = 0; i <= todos.length -1 ; i++) {
				insertEntry(todos[i]['name'],todos[i]['id'],todos[i]['completed']);
			};
		}
	}

	function insertEntry(entry, id,status) {
		$('.template li').clone().appendTo('#todo-list');
		$('#todo-list li:last-child label').text(entry);
		$('#todo-list li:last-child').attr('data-id',id);
		if(status) {
			$('#todo-list li:last-child').addClass('completed');
			$('#todo-list li:last-child .toggle').attr('checked', true)
		}
		$('#new-todo').val('');
		addListItemListener(id);
	}

	function uuid() {
		/*jshint bitwise:false */
		var i, random;
		var uuid = '';

		for (i = 0; i < 32; i++) {
			random = Math.random() * 16 | 0;
			if (i === 8 || i === 12 || i === 16 || i === 20) {
				uuid += '-';
			}
			uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16);
		}

		return uuid;
	}

	function saveEntry(entry) {
		var entry = $('#new-todo').val();
		var id = uuid();
		var todoEntry = {
			'id':id,
			'name':entry,
			'completed':false
		}

		var todos = [];
			if (localStorage.getItem('todos') === null) {
		        todos = [];
		    } else {
		        // Parse the serialized data back into an array of objects
		        todos = JSON.parse(localStorage.getItem('todos'));
		    }

	    // Push the new data (whether it be an object or anything else) onto the array
	    todos.push(todoEntry);
	    // Re-serialize the array back into a string and store it in localStorage
	    localStorage.setItem('todos', JSON.stringify(todos));

		// localStorage.setItem('Todos', JSON.stringify(todoEntry));

		insertEntry(entry,id);
	}

	function addListItemListener(id) {
		$("li[data-id *= '" + id + "']").dblclick(function(event) {
			// if dblclick was on a label and the parent isn't marked completed.
			if(event.target.nodeName == "LABEL" && (!$(event.target).closest('li').hasClass('completed'))) {
				// remove the 'editing' class from any other todo items and remove any other editor listeners
				$('.editing').removeClass('editing');
				$('.edit').off('keyup');
				var input = $(event.target);
				var text = input.text();
				input.closest('li').addClass('editing');
				input.closest('li').find('.edit').val(text).focus();
				addEditorListener();
			}
		});
		$("li[data-id *= '" + id + "']").click(function(event) {
			if(event.target.nodeName == 'INPUT') {
				var item = $(event.target).closest('li');
				if(item.hasClass('completed')){
					item.removeClass('completed');
					updateCompleted(id, false)
				} else {
					item.addClass('completed');
					updateCompleted(id, true)
				}
			}
		});
	}

	function addEditorListener() {
		$('.editing .edit').on('keyup', function(e) {
			checkEditPress(e);
		})

	}

	function updateEntry() {
		var id = $('.editing').attr('data-id');
		for(i=0; i <= todos.length-1; i++) {
			if(todos[i]['id'] == id) {
				todos[i]['name'] = $('.editing .edit').val();
			}
		}
		localStorage.setItem('todos', JSON.stringify(todos));
		$('.editing label').text($('.editing .edit').val());
		$('.editing').removeClass('editing').find('.edit').val('');
	}

	function updateCompleted(id, status) {
		for(i=0; i <= todos.length-1; i++) {
			if(todos[i]['id'] == id) {
				todos[i]['completed'] = status;
			}
			localStorage.setItem('todos', JSON.stringify(todos));
		}
	}

	function abortEditing() {
		$('.editing').removeClass('editing');
		$('.edit').val('');
	}

	// refresh count of todos to be completed.

	// add destroy function

	// add complete all function

	// show footer when todos are in list.

	// add filter functions.

	//a

<<<<<<< HEAD
	setListeners();
});
=======
	standUp();
});
>>>>>>> FETCH_HEAD
<commit_msg>working on some js stuff<commit_after>$(function() {

	var todos = '';
	function standUp() {
		// get entries from localstorage if they exist.
		// populate the list with entries and ids.

		if(localStorage && localStorage.length > 0) {

			// run populateList to insert all the entries
			// populateList();
		} else {
			var a = [];
			localStorage.setItem('todos',JSON.stringify(a));
		}

		// setListners after the list has been built.
		populateList();
		setListeners();
	}
	function setListeners() {
		//listen for keypresses
		$('#new-todo').keyup(function(e) {
			// check which key has been pressed.
			checkKeyPress(e);
		})
	}

	function checkKeyPress(e) {
		// if the key is the 'enter' key
		if(e.keyCode == 13) {
			//save the entry to localStorage
			saveEntry();
		}
	}

	function checkEditPress(e) {
		if(e.keyCode == 13) {
			updateEntry();
		} else if(e.keyCode == 27) {
			abortEditing();
		}
	}

	// build the entire list based on the contents of localStorage
	function populateList() {
		todos = JSON.parse(localStorage.getItem('todos'));
		if(todos.length > 0) {
			for (var i = 0; i <= todos.length -1 ; i++) {
				insertEntry(todos[i]['name'],todos[i]['id'],todos[i]['completed']);
			};
		}
	}

	function insertEntry(entry, id,status) {
		$('.template li').clone().appendTo('#todo-list');
		$('#todo-list li:last-child label').text(entry);
		$('#todo-list li:last-child').attr('data-id',id);
		if(status) {
			$('#todo-list li:last-child').addClass('completed');
			$('#todo-list li:last-child .toggle').attr('checked', true)
		}
		$('#new-todo').val('');
		addListItemListener(id);
	}

	function uuid() {
		/*jshint bitwise:false */
		var i, random;
		var uuid = '';

		for (i = 0; i < 32; i++) {
			random = Math.random() * 16 | 0;
			if (i === 8 || i === 12 || i === 16 || i === 20) {
				uuid += '-';
			}
			uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16);
		}

		return uuid;
	}

	function saveEntry(entry) {
		var entry = $('#new-todo').val();
		var id = uuid();
		var todoEntry = {
			'id':id,
			'name':entry,
			'completed':false
		}

		var todos = [];
			if (localStorage.getItem('todos') === null) {
		        todos = [];
		    } else {
		        // Parse the serialized data back into an array of objects
		        todos = JSON.parse(localStorage.getItem('todos'));
		    }

	    // Push the new data (whether it be an object or anything else) onto the array
	    todos.push(todoEntry);
	    // Re-serialize the array back into a string and store it in localStorage
	    localStorage.setItem('todos', JSON.stringify(todos));

		// localStorage.setItem('Todos', JSON.stringify(todoEntry));

		insertEntry(entry,id);
	}

	function addListItemListener(id) {
		$("li[data-id *= '" + id + "']").dblclick(function(event) {
			// if dblclick was on a label and the parent isn't marked completed.
			if(event.target.nodeName == "LABEL" && (!$(event.target).closest('li').hasClass('completed'))) {
				// remove the 'editing' class from any other todo items and remove any other editor listeners
				$('.editing').removeClass('editing');
				$('.edit').off('keyup');
				var input = $(event.target);
				var text = input.text();
				input.closest('li').addClass('editing');
				input.closest('li').find('.edit').val(text).focus();
				addEditorListener();
			}
		});
		$("li[data-id *= '" + id + "']").click(function(event) {
			if(event.target.nodeName == 'INPUT') {
				var item = $(event.target).closest('li');
				if(item.hasClass('completed')){
					item.removeClass('completed');
					updateCompleted(id, false)
				} else {
					item.addClass('completed');
					updateCompleted(id, true)
				}
			}
		});
	}

	function addEditorListener() {
		$('.editing .edit').on('keyup', function(e) {
			checkEditPress(e);
		})

	}

	function updateEntry() {
		var id = $('.editing').attr('data-id');
		for(i=0; i <= todos.length-1; i++) {
			if(todos[i]['id'] == id) {
				todos[i]['name'] = $('.editing .edit').val();
			}
		}
		localStorage.setItem('todos', JSON.stringify(todos));
		$('.editing label').text($('.editing .edit').val());
		$('.editing').removeClass('editing').find('.edit').val('');
	}

	function updateCompleted(id, status) {
		for(i=0; i <= todos.length-1; i++) {
			if(todos[i]['id'] == id) {
				todos[i]['completed'] = status;
			}
			localStorage.setItem('todos', JSON.stringify(todos));
		}
	}

	function abortEditing() {
		$('.editing').removeClass('editing');
		$('.edit').val('');
	}

	// refresh count of todos to be completed.

function refreshCount(){
	console.log('f');
	var n = $('#todo-list li').length;
	$('span#todo-count').text(n + "items left");
	console.log(n);
}

	// add destroy function

	// add complete all function

	// show footer when todos are in list.

	// add filter functions.

	setListeners();
});

<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
},

module.exports = new Script({
processing: {
//: (bot) => bot.say('...'),
receive: () => 'processing'
},

start: {
receive: (bot,message) => {
const inh = message.text;
return bot.setProp('inh', inh)
.then(() =>bot.say(`${groet} - ${inh} welkom bij Independer.`))
.then(() => 'askName');
}
},

bye: {
prompt: (bot) => bot.say('Geen probleem.'),
receive: () => 'processing'
},

/*
askName: {
prompt: (bot) => bot.say('Hoe heet je?'),
receive: (bot,message) => {
const name = message.text;
return bot.setProp('name', name)
.then(() => bot.say(`Ok ${name}, hoe kan ik je helpen? \n
%[Heb je schade](postback:schade) %[Zoek je een verzekering](postback:zoek)`))
.then(() => 'processing');
},
},
*/

askName: {
    prompt: (bot) => bot.say('Postback is working. What\'s your name?'),
    receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
            .then(() => bot.say(`Great! I\'ll call you ${name}`))
            .then(()=> bot.say('Is that OK? %[Yes](postback:yes) %[No](postback:nee)'))
            .then(() => 'speak');
    }
},

error: {
prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
receive: () => ''
},

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>script<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
},

module.exports = new Script({
processing: {
//: (bot) => bot.say('...'),
receive: () => 'processing'
},

start: {
receive: (bot,message) => {
const inh = message.text;
return bot.setProp('inh', inh)
.then(() =>bot.say(`${groet} - ${inh} welkom bij Independer.`))
.then(() => 'askName');
}
}

bye: {
prompt: (bot) => bot.say('Geen probleem.'),
receive: () => 'processing'
},

/*
askName: {
prompt: (bot) => bot.say('Hoe heet je?'),
receive: (bot,message) => {
const name = message.text;
return bot.setProp('name', name)
.then(() => bot.say(`Ok ${name}, hoe kan ik je helpen? \n
%[Heb je schade](postback:schade) %[Zoek je een verzekering](postback:zoek)`))
.then(() => 'processing');
},
},
*/

askName: {
    prompt: (bot) => bot.say('Postback is working. What\'s your name?'),
    receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
            .then(() => bot.say(`Great! I\'ll call you ${name}`))
            .then(()=> bot.say('Is that OK? %[Yes](postback:yes) %[No](postback:nee)'))
            .then(() => 'speak');
    }
},

error: {
prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
receive: () => ''
},

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>


<commit_before>import { isString, isUndefined, toNode } from '../util/index';

var supportsMultiple, supportsForce;

export default function (UIkit) {

    UIkit.prototype.$addClass = function (...args) {
        apply(this.$el, args, 'add');
    };

    UIkit.prototype.$removeClass = function (...args) {
        apply(this.$el, args, 'remove');
    };

    UIkit.prototype.$hasClass = function (...args) {
        return (args = getArgs(args, this.$el)) && args[0].contains(args[1]);
    };

    UIkit.prototype.$toggleClass = function (...args) {
        args = getArgs(args, this.$el);

        var force = args && !isString(args[args.length - 1]) ? args.pop() : undefined;

        for (var i = 1; i < args.length; i++) {
            args[0] && supportsForce
                ? args[0].toggle(args[i], force)
                : (args[0][(!isUndefined(force) ? force : !args[0].contains(args[i])) ? 'add' : 'remove'](args[i]));
        }
    };

}

function apply(el, args, fn) {
    (args = getArgs(args, el)) && (supportsMultiple
        ? args[0][fn].apply(args[0], args.slice(1))
        : args.slice(1).forEach(cls => args[0][fn](cls)));
}

function getArgs(args, el) {

    isString(args[0]) && args.unshift(el);
    args[0] = toNode(args[0]).classList;

    if (args[1] && ~args[1].indexOf(' ')) {
        args = [args[0]].concat(args[1].split(' '), args.slice(2));
    }

    return args[1] && args.length > 1 ? args : false;
}

(function() {

    var el = document.createElement('_');
    el.classList.add('c1', 'c2');
    supportsMultiple = el.classList.contains('c2');
    el.classList.toggle('c3', false);
    supportsForce = el.classList.contains('c3');
    el = null;

})();
<commit_msg>cleanup<commit_after>import { isString, isUndefined, toNode } from '../util/index';

var supportsMultiple, supportsForce;

export default function (UIkit) {

    UIkit.prototype.$addClass = function (...args) {
        apply(this.$el, args, 'add');
    };

    UIkit.prototype.$removeClass = function (...args) {
        apply(this.$el, args, 'remove');
    };

    UIkit.prototype.$hasClass = function (...args) {
        return (args = getArgs(args, this.$el)) && args[0].contains(args[1]);
    };

    UIkit.prototype.$toggleClass = function (...args) {
        args = getArgs(args, this.$el);

        var force = args && !isString(args[args.length - 1]) ? args.pop() : undefined;

        for (var i = 1; i < args.length; i++) {
            args[0] && supportsForce
                ? args[0].toggle(args[i], force)
                : (args[0][(!isUndefined(force) ? force : !args[0].contains(args[i])) ? 'add' : 'remove'](args[i]));
        }
    };

}

function apply(el, args, fn) {
    (args = getArgs(args, el)) && (supportsMultiple
        ? args[0][fn].apply(args[0], args.slice(1))
        : args.slice(1).forEach(cls => args[0][fn](cls)));
}

function getArgs(args, el) {

    isString(args[0]) && args.unshift(el);
    args[0] = toNode(args[0]).classList;

    if (args[1] && ~args[1].indexOf(' ')) {
        args = [args[0]].concat(args[1].split(' '), args.slice(2));
    }

    return args[1] && args.length > 1 ? args : false;
}

(function() {

    var list = document.createElement('_').classList;
    list.add('a', 'b');
    list.toggle('c', false);
    supportsMultiple = list.contains('b');
    supportsForce = !list.contains('c');
    list = null;

})();
<|endoftext|>


<commit_before>const $ = require('jquery');

export default function(opts) {

    var input = new oTinput({
        element: '.file-input-outer',
        onFileChange: function(file){
            opts.create(file);
            saveFileDetails(file.name);
            hide();
        },
        onFileError: function(err, file){
            var msg = document.webL10n.get('format-warn');
            msg = msg.replace('[file-format]',file.type.split("/")[1]);
            $('#formats').html(msg).addClass('warning');
        },
        onURLSubmit: function(url){
            input.showURLInput();
            opts.createFromURL(url);
            hide();
        },
        onURLError: function(error){
            var msg = document.webL10n.get('youtube-error');
            $('.ext-input-warning').text(msg).show();
        },
        onDragover: function(){
            $('.file-input-wrapper').addClass('hover');
        },
        onDragleave: function(){
            $('.file-input-wrapper').removeClass('hover');
        },
        text: {
            button: ''+document.webL10n.get('choose-file'),
            altButton: document.webL10n.get('choose-youtube'),
            altInputText: document.webL10n.get('youtube-instrux'),
            closeAlt: ''
        }
    });

    setFormatsMessage( oTinput.getSupportedFormats() );
    show();

    return function reset() {
        loadPreviousFileDetails();
        show();
    }

}

function setFormatsMessage(formats){
    var text = document.webL10n.get('formats');
    text = text.replace("[xxx]", formats.audio.join('/') );
    text = text.replace("[yyy]", formats.video.join('/') );
    document.getElementById("formats").innerHTML = text;
}

function loadPreviousFileDetails(){
    if ( localStorageManager.getItem("oT-lastfile") ) {
        var lastFile = JSON.parse( localStorageManager.getItem("oT-lastfile") );
        var lastfileText = document.webL10n.get('last-file');
        if (lastFile.name === undefined) {
            document.getElementById("lastfile").innerHTML = lastfileText+' '+lastFile;
        } else if (lastFile.source === '') {
            document.getElementById("lastfile").innerHTML = lastfileText+' '+lastFile.name;
        } else {
            var el = document.getElementById("lastfile");
            el.innerHTML = lastfileText+' '+lastFile.name+'';
            el.addEventListener('click',function(){
                processYoutube( lastFile.source );
            });
        }
    }
}

function saveFileDetails(fileDetails){
    var obj = fileDetails;
    if (typeof file === 'string') {
        obj = {
            name: fileDetails,
            source: ''
        }
    }
    localStorageManager.setItem("oT-lastfile", JSON.stringify( obj ));
}

function show(){
    $('.topbar').addClass('inputting');
    $('.input').addClass('active');
    $('.sbutton.time').removeClass('active');
    $('.text-panel').removeClass('editing');

}

function hide(){
    $('.topbar').removeClass('inputting');
    $('.input').removeClass('active');
    $('.sbutton.time').addClass('active');
    $('.text-panel').addClass('editing');
    $('.ext-input-field').hide();
    $('.file-input-outer').removeClass('ext-input-active');
};

// oTinput module

!function(){"use strict";function a(a){var b=this;this._text=a.text||{},this._onFileChange=a.onFileChange||function(){},this._onFileError=a.onFileError||function(){},this._onURLSubmit=a.onURLSubmit||function(){},this._onURLError=a.onURLError||function(){},this._dragover=a.onDragover||function(){},this._dragleave=a.onDragleave||function(){},this.element=this._setupElement(a.element),this._setupMouseEvents(),$(this.element).find('input[type="file"]').change(function(){b._reactToFile(this)}),$(this.element).find(".ext-input-field input").on("submit",function(){b._reactToURL($(this).val())}).keypress(function(a){return 13===a.which?(b._reactToURL($(this).val()),!1):void 0})}a.prototype.getSupportedFormats=function(){var b=["mp3","ogg","webm","wav"],c=["mp4","ogg","webm"],d=this.isFormatSupported||a.isFormatSupported,e=$.map(b,function(a,b){return d(a)?a:void 0}),f=$.map(c,function(a,b){return d(a)?a:void 0});return{audio:e,video:f}},a.prototype.isFormatSupported=function(a){var b;if("string"!=typeof a){var c=a.type.split("/")[0];return b=document.createElement(c),!(!b.canPlayType||!b.canPlayType(a.type).replace(/no/,""))}return b=document.createElement("audio"),!(!b.canPlayType||!b.canPlayType("audio/"+a+";").replace(/no/,""))},a.getSupportedFormats=a.prototype.getSupportedFormats,a.isFormatSupported=a.prototype.isFormatSupported,a.prototype.parseYoutubeURL=function(a){if(a.match){var b=/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/,c=a.match(b);if(c&&11===c[2].length)return c[2]}return!1},a.parseYoutubeURL=a.prototype.parseYoutubeURL,window.oTinput=a,a.prototype._setupElement=function(a){if("undefined"==typeof a)throw"must specify container element";var b=this._text.button||"Choose audio (or video) file",c='<button class="btn-file-input" style="width: 100%;">'+b+"</button>",d=["position: absolute","top: 0","left: 0","opacity: 0","width: 100%"].join(";"),e='<input type="file" accept="audio/*, video/*" style="'+d+'">',f="position: relative; overflow: hidden;",g='
'+c+e+"
",h=this._text.altButton||"Enter file URL",i='<button class="alt-input-button">'+h+"</button>",j=this._text.altInputText||"Enter URL of audio or video file, or YouTube video:",k=this._text.closeAlt||"close",l='

'+k+"
"+j+'<input type="text">

';return $(a).html(g+i+l),$(a)[0]},a.prototype._setupMouseEvents=function(){var a=this,b=this.element,c=$(b).find(".file-input-wrapper")[0];c.addEventListener("dragover",function(){a._dragover()},!1),c.addEventListener("dragleave",function(){a._dragleave()},!1),$(b).find(".alt-input-button").click(function(){a.showURLInput()}),$(b).find(".close-ext-input").click(function(){a.showFileInput()})},a.prototype._reactToFile=function(a){var b=a.files[0];if(this.isFormatSupported(b))this._onFileChange(b);else{var c=new Error("Filetype "+b.type+" not supported by this browser");this._onFileError(c,b)}},a.prototype._reactToURL=function(a){var b=a.replace(/\s/g,"");if(this.parseYoutubeURL(b))return this._onURLSubmit(b);var c=b.split("."),d=c[c.length-1];if(this.isFormatSupported(d))this._onURLSubmit(b);else{var e=new Error("Filetype "+d+" not supported by this browser");this._onURLError(e,a)}},a.prototype.showURLInput=function(){$(this.element).find(".ext-input-field").show().find("input").focus(),$(this.element).addClass("ext-input-active")},a.prototype.showFileInput=function(){$(this.element).find(".ext-input-field").hide(),$(this.element).removeClass("ext-input-active")}}();

/* localStorageManager v0.2.1 */
;(function(){
'use strict';

var localStorageManager = {
    identifier: 'localStorageManager',
    setItem: function(key,value){
        var that = this;
        var now = new Date().getTime();
        var valueWithMetadata = {
            value: value,
            timestamp: now
        };
        try {
            localStorage.setItem(
                this.identifier+'_'+key,
                JSON.stringify(valueWithMetadata)
            );
            this.full = false;
        } catch (err) {
            var error = err.name;
            // Possible error names:
            // NS_ERROR_DOM_QUOTA_REACHED
            // QuotaExceededError
            this.full = true;
        }
        if (this.full) {
            if (
                !this._lastRanOnFull && this.onFull &&
                !((now - this._lastRanOnFull) < 1000)
            ) {
                this.onFull();
                this._lastRanOnFull = now;
            }
            this.clearOldest( function(){
                that.setItem(key, value);
            } );
        }
    },
    getItem: function(key, prefix){
        prefix = prefix || this.identifier+'_';
        var parsed = this.getItemMetadata(key, prefix);
        if (parsed && parsed.value) {
            return parsed.value;
        } else {
            return null;
        }
    },
    getItemMetadata: function(key, prefix){
        if (prefix === undefined) {
            prefix = this.identifier+'_';
        }
        var raw = localStorage.getItem(prefix+key);
        if ((raw === null) || (raw === undefined)) {
            return null;
        }
        var parsed = JSON.parse(raw);
        parsed.key = key;
        if (parsed && parsed.value) {
            return parsed;
        }
        return null;

    },
    removeItem: function(key){
        localStorage.removeItem(this.identifier+'_'+key);
    },
    getAll: function(opts){
        opts = opts || {};
        var result_obj = {};
        var result_arr = [];
        for (var i = 0; i < localStorage.length; i++) {
            var item = undefined;
            var key = localStorage.key(i);
            if (opts.all === true) {
                item = this.getItemMetadata(key,'');
            } else if (key.indexOf(this.identifier) > -1) {
                item = this.getItemMetadata(key,'');
            }
            key = key.replace(this.identifier+'_','');
            if (item) {
                result_obj[key] = item.value || item;
                result_arr.push({
                    key: key,
                    value: item.value || item,
                    timestamp: item.timestamp || null,
                    index: i
                });
            }
        }
        result_arr.sort(function(a,b){
            if (a.timestamp !== b.timestamp) {
                return a.timestamp - b.timestamp;
            } else {
                return a.index - b.index;
            }
        })
        if (opts.format === 'array') {
            return result_arr;
        } else {
            return result_obj;
        }
    },
    getArray: function(opts){
        opts = opts || {};
        opts.format = 'array';
        return this.getAll(opts);
    },
    getFirst: function(){
        var arr = this.getArray();
        return arr[0];
    },
    clearOldest: function(callback){
        if (this.full !== true) {
            return;
        }
        var array = this.getArray();
        for (var i = 0; i < 3; i++) {
            if (array[i]) {
                localStorageManager.removeItem( array[i].key );
            }
        }
        var testKey = this.identifier+'__test_'+new Date().getTime();
        try {
            localStorage.setItem(testKey,'A');
            // assumes test passes...
            this.full = false;
            this.saveAttempts = 0;
            if (callback) { callback(); }
        } catch (err) {
            this.saveAttempts += 1;
            if (this.saveAttempts < 10) {
                this.clearOldest(callback);
            } else if (this.onSaveFailure) {
                this.onSaveFailure();
            }
        }
        localStorage.removeItem(testKey);
    },
    saveAttempts: 0
}

window.localStorageManager = localStorageManager;

}());<commit_msg>iOS file accept bug<commit_after>const $ = require('jquery');

export default function(opts) {

    var input = new oTinput({
        element: '.file-input-outer',
        onFileChange: function(file){
            opts.create(file);
            saveFileDetails(file.name);
            hide();
        },
        onFileError: function(err, file){
            var msg = document.webL10n.get('format-warn');
            msg = msg.replace('[file-format]',file.type.split("/")[1]);
            $('#formats').html(msg).addClass('warning');
        },
        onURLSubmit: function(url){
            input.showURLInput();
            opts.createFromURL(url);
            hide();
        },
        onURLError: function(error){
            var msg = document.webL10n.get('youtube-error');
            $('.ext-input-warning').text(msg).show();
        },
        onDragover: function(){
            $('.file-input-wrapper').addClass('hover');
        },
        onDragleave: function(){
            $('.file-input-wrapper').removeClass('hover');
        },
        text: {
            button: ''+document.webL10n.get('choose-file'),
            altButton: document.webL10n.get('choose-youtube'),
            altInputText: document.webL10n.get('youtube-instrux'),
            closeAlt: ''
        }
    });

    // this is a workaround for an iOS bug
    if (is_iOS()) {
        document
            .querySelector('.file-input-outer input[type="file"]')
            .removeAttribute('accept');
    }
    setFormatsMessage( oTinput.getSupportedFormats() );
    show();

    return function reset() {
        loadPreviousFileDetails();
        show();
    }

}

function is_iOS() {
    return (
        window.navigator.userAgent.indexOf('iPad') > -1 ||
        window.navigator.userAgent.indexOf('iPhone') > -1
    );
}

function setFormatsMessage(formats){
    var text = document.webL10n.get('formats');
    text = text.replace("[xxx]", formats.audio.join('/') );
    text = text.replace("[yyy]", formats.video.join('/') );
    document.getElementById("formats").innerHTML = text;
}

function loadPreviousFileDetails(){
    if ( localStorageManager.getItem("oT-lastfile") ) {
        var lastFile = JSON.parse( localStorageManager.getItem("oT-lastfile") );
        var lastfileText = document.webL10n.get('last-file');
        if (lastFile.name === undefined) {
            document.getElementById("lastfile").innerHTML = lastfileText+' '+lastFile;
        } else if (lastFile.source === '') {
            document.getElementById("lastfile").innerHTML = lastfileText+' '+lastFile.name;
        } else {
            var el = document.getElementById("lastfile");
            el.innerHTML = lastfileText+' '+lastFile.name+'';
            el.addEventListener('click',function(){
                processYoutube( lastFile.source );
            });
        }
    }
}

function saveFileDetails(fileDetails){
    var obj = fileDetails;
    if (typeof file === 'string') {
        obj = {
            name: fileDetails,
            source: ''
        }
    }
    localStorageManager.setItem("oT-lastfile", JSON.stringify( obj ));
}

function show(){
    $('.topbar').addClass('inputting');
    $('.input').addClass('active');
    $('.sbutton.time').removeClass('active');
    $('.text-panel').removeClass('editing');

}

function hide(){
    $('.topbar').removeClass('inputting');
    $('.input').removeClass('active');
    $('.sbutton.time').addClass('active');
    $('.text-panel').addClass('editing');
    $('.ext-input-field').hide();
    $('.file-input-outer').removeClass('ext-input-active');
};

// oTinput module

!function(){"use strict";function a(a){var b=this;this._text=a.text||{},this._onFileChange=a.onFileChange||function(){},this._onFileError=a.onFileError||function(){},this._onURLSubmit=a.onURLSubmit||function(){},this._onURLError=a.onURLError||function(){},this._dragover=a.onDragover||function(){},this._dragleave=a.onDragleave||function(){},this.element=this._setupElement(a.element),this._setupMouseEvents(),$(this.element).find('input[type="file"]').change(function(){b._reactToFile(this)}),$(this.element).find(".ext-input-field input").on("submit",function(){b._reactToURL($(this).val())}).keypress(function(a){return 13===a.which?(b._reactToURL($(this).val()),!1):void 0})}a.prototype.getSupportedFormats=function(){var b=["mp3","ogg","webm","wav"],c=["mp4","ogg","webm"],d=this.isFormatSupported||a.isFormatSupported,e=$.map(b,function(a,b){return d(a)?a:void 0}),f=$.map(c,function(a,b){return d(a)?a:void 0});return{audio:e,video:f}},a.prototype.isFormatSupported=function(a){var b;if("string"!=typeof a){var c=a.type.split("/")[0];return b=document.createElement(c),!(!b.canPlayType||!b.canPlayType(a.type).replace(/no/,""))}return b=document.createElement("audio"),!(!b.canPlayType||!b.canPlayType("audio/"+a+";").replace(/no/,""))},a.getSupportedFormats=a.prototype.getSupportedFormats,a.isFormatSupported=a.prototype.isFormatSupported,a.prototype.parseYoutubeURL=function(a){if(a.match){var b=/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/,c=a.match(b);if(c&&11===c[2].length)return c[2]}return!1},a.parseYoutubeURL=a.prototype.parseYoutubeURL,window.oTinput=a,a.prototype._setupElement=function(a){if("undefined"==typeof a)throw"must specify container element";var b=this._text.button||"Choose audio (or video) file",c='<button class="btn-file-input" style="width: 100%;">'+b+"</button>",d=["position: absolute","top: 0","left: 0","opacity: 0","width: 100%"].join(";"),e='<input type="file" accept="audio/*, video/*" style="'+d+'">',f="position: relative; overflow: hidden;",g='
'+c+e+"
",h=this._text.altButton||"Enter file URL",i='<button class="alt-input-button">'+h+"</button>",j=this._text.altInputText||"Enter URL of audio or video file, or YouTube video:",k=this._text.closeAlt||"close",l='

'+k+"
"+j+'<input type="text">

';return $(a).html(g+i+l),$(a)[0]},a.prototype._setupMouseEvents=function(){var a=this,b=this.element,c=$(b).find(".file-input-wrapper")[0];c.addEventListener("dragover",function(){a._dragover()},!1),c.addEventListener("dragleave",function(){a._dragleave()},!1),$(b).find(".alt-input-button").click(function(){a.showURLInput()}),$(b).find(".close-ext-input").click(function(){a.showFileInput()})},a.prototype._reactToFile=function(a){var b=a.files[0];if(this.isFormatSupported(b))this._onFileChange(b);else{var c=new Error("Filetype "+b.type+" not supported by this browser");this._onFileError(c,b)}},a.prototype._reactToURL=function(a){var b=a.replace(/\s/g,"");if(this.parseYoutubeURL(b))return this._onURLSubmit(b);var c=b.split("."),d=c[c.length-1];if(this.isFormatSupported(d))this._onURLSubmit(b);else{var e=new Error("Filetype "+d+" not supported by this browser");this._onURLError(e,a)}},a.prototype.showURLInput=function(){$(this.element).find(".ext-input-field").show().find("input").focus(),$(this.element).addClass("ext-input-active")},a.prototype.showFileInput=function(){$(this.element).find(".ext-input-field").hide(),$(this.element).removeClass("ext-input-active")}}();

/* localStorageManager v0.2.1 */
;(function(){
'use strict';

var localStorageManager = {
    identifier: 'localStorageManager',
    setItem: function(key,value){
        var that = this;
        var now = new Date().getTime();
        var valueWithMetadata = {
            value: value,
            timestamp: now
        };
        try {
            localStorage.setItem(
                this.identifier+'_'+key,
                JSON.stringify(valueWithMetadata)
            );
            this.full = false;
        } catch (err) {
            var error = err.name;
            // Possible error names:
            // NS_ERROR_DOM_QUOTA_REACHED
            // QuotaExceededError
            this.full = true;
        }
        if (this.full) {
            if (
                !this._lastRanOnFull && this.onFull &&
                !((now - this._lastRanOnFull) < 1000)
            ) {
                this.onFull();
                this._lastRanOnFull = now;
            }
            this.clearOldest( function(){
                that.setItem(key, value);
            } );
        }
    },
    getItem: function(key, prefix){
        prefix = prefix || this.identifier+'_';
        var parsed = this.getItemMetadata(key, prefix);
        if (parsed && parsed.value) {
            return parsed.value;
        } else {
            return null;
        }
    },
    getItemMetadata: function(key, prefix){
        if (prefix === undefined) {
            prefix = this.identifier+'_';
        }
        var raw = localStorage.getItem(prefix+key);
        if ((raw === null) || (raw === undefined)) {
            return null;
        }
        var parsed = JSON.parse(raw);
        parsed.key = key;
        if (parsed && parsed.value) {
            return parsed;
        }
        return null;

    },
    removeItem: function(key){
        localStorage.removeItem(this.identifier+'_'+key);
    },
    getAll: function(opts){
        opts = opts || {};
        var result_obj = {};
        var result_arr = [];
        for (var i = 0; i < localStorage.length; i++) {
            var item = undefined;
            var key = localStorage.key(i);
            if (opts.all === true) {
                item = this.getItemMetadata(key,'');
            } else if (key.indexOf(this.identifier) > -1) {
                item = this.getItemMetadata(key,'');
            }
            key = key.replace(this.identifier+'_','');
            if (item) {
                result_obj[key] = item.value || item;
                result_arr.push({
                    key: key,
                    value: item.value || item,
                    timestamp: item.timestamp || null,
                    index: i
                });
            }
        }
        result_arr.sort(function(a,b){
            if (a.timestamp !== b.timestamp) {
                return a.timestamp - b.timestamp;
            } else {
                return a.index - b.index;
            }
        })
        if (opts.format === 'array') {
            return result_arr;
        } else {
            return result_obj;
        }
    },
    getArray: function(opts){
        opts = opts || {};
        opts.format = 'array';
        return this.getAll(opts);
    },
    getFirst: function(){
        var arr = this.getArray();
        return arr[0];
    },
    clearOldest: function(callback){
        if (this.full !== true) {
            return;
        }
        var array = this.getArray();
        for (var i = 0; i < 3; i++) {
            if (array[i]) {
                localStorageManager.removeItem( array[i].key );
            }
        }
        var testKey = this.identifier+'__test_'+new Date().getTime();
        try {
            localStorage.setItem(testKey,'A');
            // assumes test passes...
            this.full = false;
            this.saveAttempts = 0;
            if (callback) { callback(); }
        } catch (err) {
            this.saveAttempts += 1;
            if (this.saveAttempts < 10) {
                this.clearOldest(callback);
            } else if (this.onSaveFailure) {
                this.onSaveFailure();
            }
        }
        localStorage.removeItem(testKey);
    },
    saveAttempts: 0
}

window.localStorageManager = localStorageManager;

}());<|endoftext|>


<commit_before>import {css, fastdom, getEventPos, inBrowser, isTouch, on, once, pointerCancel, pointerDown, pointerUp, ready, toMs, trigger} from 'uikit-util';

export default function (UIkit) {

    inBrowser && ready(() => {

        UIkit.update();

        // throttle 'resize'
        let pendingResize;
        const handleResize = () => {
            if (pendingResize) {
                return;
            }
            pendingResize = true;
            fastdom.write(() => pendingResize = false);
            UIkit.update(null, 'resize');
        };

        on(window, 'load resize', handleResize);
        on(document, 'loadedmetadata load', handleResize, true);

        if ('ResizeObserver' in window) {
            (new ResizeObserver(handleResize)).observe(document.documentElement);
        }

        // throttle `scroll` event (Safari triggers multiple `scroll` events per frame)
        let pending;
        on(window, 'scroll', e => {

            if (pending) {
                return;
            }
            pending = true;
            fastdom.write(() => pending = false);

            UIkit.update(null, e.type);

        }, {passive: true, capture: true});

        let started = 0;
        on(document, 'animationstart', ({target}) => {
            if ((css(target, 'animationName') || '').match(/^uk-.*(left|right)/)) {

                started++;
                css(document.body, 'overflowX', 'hidden');
                setTimeout(() => {
                    if (!--started) {
                        css(document.body, 'overflowX', '');
                    }
                }, toMs(css(target, 'animationDuration')) + 100);
            }
        }, true);

        let off;
        on(document, pointerDown, e => {

            off && off();

            if (!isTouch(e)) {
                return;
            }

            // Handle Swipe Gesture
            const pos = getEventPos(e);
            const target = 'tagName' in e.target ? e.target : e.target.parentNode;
            off = once(document, `${pointerUp} ${pointerCancel}`, e => {

                const {x, y} = getEventPos(e);

                // swipe
                if (target && x && Math.abs(pos.x - x) > 100 || y && Math.abs(pos.y - y) > 100) {

                    setTimeout(() => {
                        trigger(target, 'swipe');
                        trigger(target, `swipe${swipeDirection(pos.x, pos.y, x, y)}`);
                    });

                }

            });

        }, {passive: true});

    });

}

function swipeDirection(x1, y1, x2, y2) {
    return Math.abs(x1 - x2) >= Math.abs(y1 - y2)
        ? x1 - x2 > 0
            ? 'Left'
            : 'Right'
        : y1 - y2 > 0
            ? 'Up'
            : 'Down';
}
<commit_msg>refactor: set overflow on html element<commit_after>import {css, fastdom, getEventPos, inBrowser, isTouch, on, once, pointerCancel, pointerDown, pointerUp, ready, toMs, trigger} from 'uikit-util';

export default function (UIkit) {

    inBrowser && ready(() => {

        UIkit.update();

        // throttle 'resize'
        let pendingResize;
        const handleResize = () => {
            if (pendingResize) {
                return;
            }
            pendingResize = true;
            fastdom.write(() => pendingResize = false);
            UIkit.update(null, 'resize');
        };

        on(window, 'load resize', handleResize);
        on(document, 'loadedmetadata load', handleResize, true);

        if ('ResizeObserver' in window) {
            (new ResizeObserver(handleResize)).observe(document.documentElement);
        }

        // throttle `scroll` event (Safari triggers multiple `scroll` events per frame)
        let pending;
        on(window, 'scroll', e => {

            if (pending) {
                return;
            }
            pending = true;
            fastdom.write(() => pending = false);

            UIkit.update(null, e.type);

        }, {passive: true, capture: true});

        let started = 0;
        on(document, 'animationstart', ({target}) => {
            if ((css(target, 'animationName') || '').match(/^uk-.*(left|right)/)) {

                started++;
                css(document.documentElement, 'overflowX', 'hidden');
                setTimeout(() => {
                    if (!--started) {
                        css(document.documentElement, 'overflowX', '');
                    }
                }, toMs(css(target, 'animationDuration')) + 100);
            }
        }, true);

        let off;
        on(document, pointerDown, e => {

            off && off();

            if (!isTouch(e)) {
                return;
            }

            // Handle Swipe Gesture
            const pos = getEventPos(e);
            const target = 'tagName' in e.target ? e.target : e.target.parentNode;
            off = once(document, `${pointerUp} ${pointerCancel}`, e => {

                const {x, y} = getEventPos(e);

                // swipe
                if (target && x && Math.abs(pos.x - x) > 100 || y && Math.abs(pos.y - y) > 100) {

                    setTimeout(() => {
                        trigger(target, 'swipe');
                        trigger(target, `swipe${swipeDirection(pos.x, pos.y, x, y)}`);
                    });

                }

            });

        }, {passive: true});

    });

}

function swipeDirection(x1, y1, x2, y2) {
    return Math.abs(x1 - x2) >= Math.abs(y1 - y2)
        ? x1 - x2 > 0
            ? 'Left'
            : 'Right'
        : y1 - y2 > 0
            ? 'Up'
            : 'Down';
}
<|endoftext|>


<commit_before>(function(core) {

    if (typeof define == "function" && define.amd) { // AMD
        define("uikit", function(){

            var uikit = core(window, window.jQuery, window.document);

            uikit.load = function(res, req, onload, config) {

                var resources = res.split(','), load = [], i, base = (config.config && config.config.uikit && config.config.uikit.base ? config.config.uikit.base : "").replace(/\/+$/g, "");

                if (!base) {
                    throw new Error( "Please define base path to UIkit in the requirejs config." );
                }

                for (i = 0; i < resources.length; i += 1) {
                    var resource = resources[i].replace(/\./g, '/');
                    load.push(base+'/components/'+resource);
                }

                req(load, function() {
                    onload(uikit);
                });
            };

            return uikit;
        });
    }

    if (!window.jQuery) {
        throw new Error( "UIkit requires jQuery" );
    }

    if (window && window.jQuery) {
        core(window, window.jQuery, window.document);
    }

})(function(global, $, doc) {

    "use strict";

    var UI = $.UIkit || {}, $html = $("html"), $win = $(window), $doc = $(document);

    if (UI.fn) {
        return UI;
    }

    UI.version = '2.11.1';
    UI.$doc    = $doc;
    UI.$win    = $win;
    UI.$html   = $html;

    UI.fn = function(command, options) {

        var args = arguments, cmd = command.match(/^([a-z\-]+)(?:\.([a-z]+))?/i), component = cmd[1], method = cmd[2];

        if (!UI[component]) {
            $.error("UIkit component [" + component + "] does not exist.");
            return this;
        }

        return this.each(function() {
            var $this = $(this), data = $this.data(component);
            if (!data) $this.data(component, (data = UI[component](this, method ? undefined : options)));
            if (method) data[method].apply(data, Array.prototype.slice.call(args, 1));
        });
    };

    UI.support = {};
    UI.support.transition = (function() {

        var transitionEnd = (function() {

            var element = doc.body || doc.documentElement,
                transEndEventNames = {
                    WebkitTransition: 'webkitTransitionEnd',
                    MozTransition: 'transitionend',
                    OTransition: 'oTransitionEnd otransitionend',
                    transition: 'transitionend'
                }, name;

            for (name in transEndEventNames) {
                if (element.style[name] !== undefined) return transEndEventNames[name];
            }
        }());

        return transitionEnd && { end: transitionEnd };
    })();

    UI.support.animation = (function() {

        var animationEnd = (function() {

            var element = doc.body || doc.documentElement,
                animEndEventNames = {
                    WebkitAnimation: 'webkitAnimationEnd',
                    MozAnimation: 'animationend',
                    OAnimation: 'oAnimationEnd oanimationend',
                    animation: 'animationend'
                }, name;

            for (name in animEndEventNames) {
                if (element.style[name] !== undefined) return animEndEventNames[name];
            }
        }());

        return animationEnd && { end: animationEnd };
    })();

    UI.support.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback){ setTimeout(callback, 1000/60); };
    UI.support.touch                 = (
        ('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
        (global.DocumentTouch && document instanceof global.DocumentTouch)  ||
        (global.navigator['msPointerEnabled'] && global.navigator['msMaxTouchPoints'] > 0) || //IE 10
        (global.navigator['pointerEnabled'] && global.navigator['maxTouchPoints'] > 0) || //IE >=11
        false
    );
    UI.support.mutationobserver = (global.MutationObserver || global.WebKitMutationObserver || null);

    UI.Utils = {};

    UI.Utils.debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    UI.Utils.removeCssRules = function(selectorRegEx) {
        var idx, idxs, stylesheet, _i, _j, _k, _len, _len1, _len2, _ref;

        if(!selectorRegEx) return;

        setTimeout(function(){
            try {
              _ref = document.styleSheets;
              for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                stylesheet = _ref[_i];
                idxs = [];
                stylesheet.cssRules = stylesheet.cssRules;
                for (idx = _j = 0, _len1 = stylesheet.cssRules.length; _j < _len1; idx = ++_j) {
                  if (stylesheet.cssRules[idx].type === CSSRule.STYLE_RULE && selectorRegEx.test(stylesheet.cssRules[idx].selectorText)) {
                    idxs.unshift(idx);
                  }
                }
                for (_k = 0, _len2 = idxs.length; _k < _len2; _k++) {
                  stylesheet.deleteRule(idxs[_k]);
                }
              }
            } catch (_error) {}
        }, 0);
    };

    UI.Utils.isInView = function(element, options) {

        var $element = $(element);

        if (!$element.is(':visible')) {
            return false;
        }

        var window_left = $win.scrollLeft(), window_top = $win.scrollTop(), offset = $element.offset(), left = offset.left, top = offset.top;

        options = $.extend({topoffset:0, leftoffset:0}, options);

        if (top + $element.height() >= window_top && top - options.topoffset <= window_top + $win.height() &&
            left + $element.width() >= window_left && left - options.leftoffset <= window_left + $win.width()) {
          return true;
        } else {
          return false;
        }
    };

    UI.Utils.checkDisplay = function(context) {
        $('[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]', context || document).trigger('uk.check.display');
    };

    UI.Utils.options = function(string) {

        if ($.isPlainObject(string)) return string;

        var start = (string ? string.indexOf("{") : -1), options = {};

        if (start != -1) {
            try {
                options = (new Function("", "var json = " + string.substr(start) + "; return JSON.parse(JSON.stringify(json));"))();
            } catch (e) {}
        }

        return options;
    };

    UI.Utils.template = function(str, data) {

        var tokens = str.replace(/\n/g, '\\n').replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),
            i=0, toc, cmd, prop, val, fn, output = [], openblocks = 0;

        while(i < tokens.length) {

            toc = tokens[i];

            if(toc.match(/\{\{\s*(.+?)\s*\}\}/)) {
                i = i + 1;
                toc  = tokens[i];
                cmd  = toc[0];
                prop = toc.substring(toc.match(/^(\^|\#|\!|\~|\:)/) ? 1:0);

                switch(cmd) {
                    case '~':
                        output.push("for(var $i=0;$i<"+prop+".length;$i++) { var $item = "+prop+"[$i];");
                        openblocks++;
                        break;
                    case ':':
                        output.push("for(var $key in "+prop+") { var $val = "+prop+"[$key];");
                        openblocks++;
                        break;
                    case '#':
                        output.push("if("+prop+") {");
                        openblocks++;
                        break;
                    case '^':
                        output.push("if(!"+prop+") {");
                        openblocks++;
                        break;
                    case '/':
                        output.push("}");
                        openblocks--;
                        break;
                    case '!':
                        output.push("__ret.push("+prop+");");
                        break;
                    default:
                        output.push("__ret.push(escape("+prop+"));");
                        break;
                }
            } else {
                output.push("__ret.push('"+toc.replace(/\'/g, "\\'")+"');");
            }
            i = i + 1;
        }

        fn  = [
            'var __ret = [];',
            'try {',
            'with($data){', (!openblocks ? output.join('') : '__ret = ["Not all blocks are closed correctly."]'), '};',
            '}catch(e){__ret = [e.message];}',
            'return __ret.join("").replace(/\\n\\n/g, "\\n");',
            "function escape(html) { return String(html).replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');}"
        ].join("\n");

        var func = new Function('$data', fn);
        return data ? func(data) : func;
    };

    UI.Utils.events       = {};
    UI.Utils.events.click = UI.support.touch ? 'tap' : 'click';

    $.UIkit = UI;
    $.fn.uk = UI.fn;

    $.UIkit.langdirection = $html.attr("dir") == "rtl" ? "right" : "left";

    // DOM mutation save ready helper function

    UI.domObservers = [];

    UI.domObserve = function(selector, fn) {

        if(!UI.support.mutationobserver) return;

        $(selector).each(function() {

            var element = this;

            try {

                var observer = new UI.support.mutationobserver(UI.Utils.debounce(function(mutations) {
                    fn.apply(element, []);
                    $(element).trigger('uk.dom.changed');
                }, 50));

                // pass in the target node, as well as the observer options
                observer.observe(element, { childList: true, subtree: true });

            } catch(e) {}
        });
    };

    UI.ready = function(fn) {
        $(function() { fn(document); });
        UI.domObservers.push(fn);
    };

    UI.components = {};

    UI.component = function(name, def) {

        var fn = function(element, options) {

            var $this = this;

            this.element = element ? $(element) : null;
            this.options = $.extend(true, {}, this.defaults, options);
            this.plugins = {};

            if (this.element) {
                this.element.data(name, this);
            }

            this.init();

            (this.options.plugins.length ? this.options.plugins : Object.keys(fn.plugins)).forEach(function(plugin) {

                if (fn.plugins[plugin].init) {
                    fn.plugins[plugin].init($this);
                    $this.plugins[plugin] = true;
                }

            });

            this.trigger('init', [this]);
        };

        fn.plugins = {};

        $.extend(true, fn.prototype, {

            defaults : {plugins: []},

            init: function(){},

            on: function(){
                return $(this.element || this).on.apply(this.element || this, arguments);
            },

            one: function(){
                return $(this.element || this).one.apply(this.element || this, arguments);
            },

            off: function(evt){
                return $(this.element || this).off(evt);
            },

            trigger: function(evt, params) {
                return $(this.element || this).trigger(evt, params);
            },

            find: function(selector) {
                return this.element ? this.element.find(selector) : $([]);
            },

            proxy: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = function() { return obj[method].apply(obj, arguments); };
                });
            },

            mixin: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = obj[method].bind($this);
                });
            }

        }, def);

        this.components[name] = fn;

        this[name] = function() {

            var element, options;

            if(arguments.length) {
                switch(arguments.length) {
                    case 1:

                        if (typeof arguments[0] === "string" || arguments[0].nodeType || arguments[0] instanceof jQuery) {
                            element = $(arguments[0]);
                        } else {
                            options = arguments[0];
                        }

                        break;
                    case 2:

                        element = $(arguments[0]);
                        options = arguments[1];
                        break;
                }
            }

            if (element && element.data(name)) {
                return element.data(name);
            }

            return (new UI.components[name](element, options));
        };

        return fn;
    };

    UI.plugin = function(component, name, def) {
        this.components[component].plugins[name] = def;
    };

    $doc.on('uk.domready', function(){
        UI.domObservers.forEach(function(fn){
            fn(document);
        });
        $doc.trigger('uk.dom.changed');
    });

    $(function(){

        // custom scroll observer
        setInterval((function(){

            var memory = {x: window.pageXOffset, y:window.pageYOffset};

            var fn = function(){

                if (memory.x != window.pageXOffset || memory.y != window.pageYOffset) {
                    memory = {x: window.pageXOffset, y:window.pageYOffset};
                    $doc.trigger('uk-scroll', [memory]);
                }
            };

            if ($.UIkit.support.touch) {
                $doc.on('touchmove touchend MSPointerMove MSPointerUp', fn);
            }

            if(memory.x || memory.y) fn();

            return fn;

        })(), 15);

        // Check for dom modifications
        UI.domObserve('[data-uk-observe]', function() {

            var ele = this;

            UI.domObservers.forEach(function(fn){
                fn(ele);
            });
        });

        if (UI.support.touch) {

            // remove css hover rules for touch devices
            // UI.Utils.removeCssRules(/\.uk-(?!navbar).*:hover/);

            // viewport unit fix for uk-height-viewport - should be fixed in iOS 8
            if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {

                UI.$win.on('load orientationchange resize', UI.Utils.debounce((function(){

                    var fn = function() {
                        $('.uk-height-viewport').css('height', window.innerHeight);
                        return fn;
                    };

                    return fn();

                })(), 100));
            }
        }
    });

    // add touch identifier class
    $html.addClass(UI.support.touch ? "uk-touch" : "uk-notouch");

    // add uk-hover class on tap to support overlays on touch devices
    if (UI.support.touch) {

        var hoverset = false, selector = '.uk-overlay, .uk-overlay-toggle, .uk-has-hover', exclude;

        $html.on('touchstart MSPointerDown', selector, function() {

            if(hoverset) $('.uk-hover').removeClass('uk-hover');

            hoverset = $(this).addClass('uk-hover');

        }).on('touchend MSPointerUp', function(e) {

            exclude = $(e.target).parents(selector);

            if (hoverset) hoverset.not(exclude).removeClass('uk-hover');
        });
    }

    return UI;
});
<commit_msg>some work on checkDisplay api<commit_after>(function(core) {

    if (typeof define == "function" && define.amd) { // AMD
        define("uikit", function(){

            var uikit = core(window, window.jQuery, window.document);

            uikit.load = function(res, req, onload, config) {

                var resources = res.split(','), load = [], i, base = (config.config && config.config.uikit && config.config.uikit.base ? config.config.uikit.base : "").replace(/\/+$/g, "");

                if (!base) {
                    throw new Error( "Please define base path to UIkit in the requirejs config." );
                }

                for (i = 0; i < resources.length; i += 1) {
                    var resource = resources[i].replace(/\./g, '/');
                    load.push(base+'/components/'+resource);
                }

                req(load, function() {
                    onload(uikit);
                });
            };

            return uikit;
        });
    }

    if (!window.jQuery) {
        throw new Error( "UIkit requires jQuery" );
    }

    if (window && window.jQuery) {
        core(window, window.jQuery, window.document);
    }

})(function(global, $, doc) {

    "use strict";

    var UI = $.UIkit || {}, $html = $("html"), $win = $(window), $doc = $(document);

    if (UI.fn) {
        return UI;
    }

    UI.version = '2.11.1';
    UI.$doc    = $doc;
    UI.$win    = $win;
    UI.$html   = $html;

    UI.fn = function(command, options) {

        var args = arguments, cmd = command.match(/^([a-z\-]+)(?:\.([a-z]+))?/i), component = cmd[1], method = cmd[2];

        if (!UI[component]) {
            $.error("UIkit component [" + component + "] does not exist.");
            return this;
        }

        return this.each(function() {
            var $this = $(this), data = $this.data(component);
            if (!data) $this.data(component, (data = UI[component](this, method ? undefined : options)));
            if (method) data[method].apply(data, Array.prototype.slice.call(args, 1));
        });
    };

    UI.support = {};
    UI.support.transition = (function() {

        var transitionEnd = (function() {

            var element = doc.body || doc.documentElement,
                transEndEventNames = {
                    WebkitTransition: 'webkitTransitionEnd',
                    MozTransition: 'transitionend',
                    OTransition: 'oTransitionEnd otransitionend',
                    transition: 'transitionend'
                }, name;

            for (name in transEndEventNames) {
                if (element.style[name] !== undefined) return transEndEventNames[name];
            }
        }());

        return transitionEnd && { end: transitionEnd };
    })();

    UI.support.animation = (function() {

        var animationEnd = (function() {

            var element = doc.body || doc.documentElement,
                animEndEventNames = {
                    WebkitAnimation: 'webkitAnimationEnd',
                    MozAnimation: 'animationend',
                    OAnimation: 'oAnimationEnd oanimationend',
                    animation: 'animationend'
                }, name;

            for (name in animEndEventNames) {
                if (element.style[name] !== undefined) return animEndEventNames[name];
            }
        }());

        return animationEnd && { end: animationEnd };
    })();

    UI.support.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback){ setTimeout(callback, 1000/60); };
    UI.support.touch                 = (
        ('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
        (global.DocumentTouch && document instanceof global.DocumentTouch)  ||
        (global.navigator['msPointerEnabled'] && global.navigator['msMaxTouchPoints'] > 0) || //IE 10
        (global.navigator['pointerEnabled'] && global.navigator['maxTouchPoints'] > 0) || //IE >=11
        false
    );
    UI.support.mutationobserver = (global.MutationObserver || global.WebKitMutationObserver || null);

    UI.Utils = {};

    UI.Utils.debounce = function(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

    UI.Utils.removeCssRules = function(selectorRegEx) {
        var idx, idxs, stylesheet, _i, _j, _k, _len, _len1, _len2, _ref;

        if(!selectorRegEx) return;

        setTimeout(function(){
            try {
              _ref = document.styleSheets;
              for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                stylesheet = _ref[_i];
                idxs = [];
                stylesheet.cssRules = stylesheet.cssRules;
                for (idx = _j = 0, _len1 = stylesheet.cssRules.length; _j < _len1; idx = ++_j) {
                  if (stylesheet.cssRules[idx].type === CSSRule.STYLE_RULE && selectorRegEx.test(stylesheet.cssRules[idx].selectorText)) {
                    idxs.unshift(idx);
                  }
                }
                for (_k = 0, _len2 = idxs.length; _k < _len2; _k++) {
                  stylesheet.deleteRule(idxs[_k]);
                }
              }
            } catch (_error) {}
        }, 0);
    };

    UI.Utils.isInView = function(element, options) {

        var $element = $(element);

        if (!$element.is(':visible')) {
            return false;
        }

        var window_left = $win.scrollLeft(), window_top = $win.scrollTop(), offset = $element.offset(), left = offset.left, top = offset.top;

        options = $.extend({topoffset:0, leftoffset:0}, options);

        if (top + $element.height() >= window_top && top - options.topoffset <= window_top + $win.height() &&
            left + $element.width() >= window_left && left - options.leftoffset <= window_left + $win.width()) {
          return true;
        } else {
          return false;
        }
    };

    UI.Utils.checkDisplay = function(context) {

        var elements = $('[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]', context || document);

        if (context && !elements.length) {
            elements = $(context);
        }

        elements.trigger('uk.check.display');

        return elements;
    };

    UI.Utils.options = function(string) {

        if ($.isPlainObject(string)) return string;

        var start = (string ? string.indexOf("{") : -1), options = {};

        if (start != -1) {
            try {
                options = (new Function("", "var json = " + string.substr(start) + "; return JSON.parse(JSON.stringify(json));"))();
            } catch (e) {}
        }

        return options;
    };

    UI.Utils.template = function(str, data) {

        var tokens = str.replace(/\n/g, '\\n').replace(/\{\{\{\s*(.+?)\s*\}\}\}/g, "{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),
            i=0, toc, cmd, prop, val, fn, output = [], openblocks = 0;

        while(i < tokens.length) {

            toc = tokens[i];

            if(toc.match(/\{\{\s*(.+?)\s*\}\}/)) {
                i = i + 1;
                toc  = tokens[i];
                cmd  = toc[0];
                prop = toc.substring(toc.match(/^(\^|\#|\!|\~|\:)/) ? 1:0);

                switch(cmd) {
                    case '~':
                        output.push("for(var $i=0;$i<"+prop+".length;$i++) { var $item = "+prop+"[$i];");
                        openblocks++;
                        break;
                    case ':':
                        output.push("for(var $key in "+prop+") { var $val = "+prop+"[$key];");
                        openblocks++;
                        break;
                    case '#':
                        output.push("if("+prop+") {");
                        openblocks++;
                        break;
                    case '^':
                        output.push("if(!"+prop+") {");
                        openblocks++;
                        break;
                    case '/':
                        output.push("}");
                        openblocks--;
                        break;
                    case '!':
                        output.push("__ret.push("+prop+");");
                        break;
                    default:
                        output.push("__ret.push(escape("+prop+"));");
                        break;
                }
            } else {
                output.push("__ret.push('"+toc.replace(/\'/g, "\\'")+"');");
            }
            i = i + 1;
        }

        fn  = [
            'var __ret = [];',
            'try {',
            'with($data){', (!openblocks ? output.join('') : '__ret = ["Not all blocks are closed correctly."]'), '};',
            '}catch(e){__ret = [e.message];}',
            'return __ret.join("").replace(/\\n\\n/g, "\\n");',
            "function escape(html) { return String(html).replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>');}"
        ].join("\n");

        var func = new Function('$data', fn);
        return data ? func(data) : func;
    };

    UI.Utils.events       = {};
    UI.Utils.events.click = UI.support.touch ? 'tap' : 'click';

    $.UIkit = UI;
    $.fn.uk = UI.fn;

    $.UIkit.langdirection = $html.attr("dir") == "rtl" ? "right" : "left";

    // DOM mutation save ready helper function

    UI.domObservers = [];

    UI.domObserve = function(selector, fn) {

        if(!UI.support.mutationobserver) return;

        $(selector).each(function() {

            var element = this;

            try {

                var observer = new UI.support.mutationobserver(UI.Utils.debounce(function(mutations) {
                    fn.apply(element, []);
                    $(element).trigger('uk.dom.changed');
                }, 50));

                // pass in the target node, as well as the observer options
                observer.observe(element, { childList: true, subtree: true });

            } catch(e) {}
        });
    };

    UI.ready = function(fn) {
        $(function() { fn(document); });
        UI.domObservers.push(fn);
    };

    UI.components = {};

    UI.component = function(name, def) {

        var fn = function(element, options) {

            var $this = this;

            this.element = element ? $(element) : null;
            this.options = $.extend(true, {}, this.defaults, options);
            this.plugins = {};

            if (this.element) {
                this.element.data(name, this);
            }

            this.init();

            (this.options.plugins.length ? this.options.plugins : Object.keys(fn.plugins)).forEach(function(plugin) {

                if (fn.plugins[plugin].init) {
                    fn.plugins[plugin].init($this);
                    $this.plugins[plugin] = true;
                }

            });

            this.trigger('init', [this]);
        };

        fn.plugins = {};

        $.extend(true, fn.prototype, {

            defaults : {plugins: []},

            init: function(){},

            on: function(){
                return $(this.element || this).on.apply(this.element || this, arguments);
            },

            one: function(){
                return $(this.element || this).one.apply(this.element || this, arguments);
            },

            off: function(evt){
                return $(this.element || this).off(evt);
            },

            trigger: function(evt, params) {
                return $(this.element || this).trigger(evt, params);
            },

            find: function(selector) {
                return this.element ? this.element.find(selector) : $([]);
            },

            proxy: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = function() { return obj[method].apply(obj, arguments); };
                });
            },

            mixin: function(obj, methods) {

                var $this = this;

                methods.split(' ').forEach(function(method) {
                    if (!$this[method]) $this[method] = obj[method].bind($this);
                });
            }

        }, def);

        this.components[name] = fn;

        this[name] = function() {

            var element, options;

            if(arguments.length) {
                switch(arguments.length) {
                    case 1:

                        if (typeof arguments[0] === "string" || arguments[0].nodeType || arguments[0] instanceof jQuery) {
                            element = $(arguments[0]);
                        } else {
                            options = arguments[0];
                        }

                        break;
                    case 2:

                        element = $(arguments[0]);
                        options = arguments[1];
                        break;
                }
            }

            if (element && element.data(name)) {
                return element.data(name);
            }

            return (new UI.components[name](element, options));
        };

        return fn;
    };

    UI.plugin = function(component, name, def) {
        this.components[component].plugins[name] = def;
    };

    $doc.on('uk.domready', function(){
        UI.domObservers.forEach(function(fn){
            fn(document);
        });
        $doc.trigger('uk.dom.changed');
    });

    $(function(){

        // custom scroll observer
        setInterval((function(){

            var memory = {x: window.pageXOffset, y:window.pageYOffset};

            var fn = function(){

                if (memory.x != window.pageXOffset || memory.y != window.pageYOffset) {
                    memory = {x: window.pageXOffset, y:window.pageYOffset};
                    $doc.trigger('uk-scroll', [memory]);
                }
            };

            if ($.UIkit.support.touch) {
                $doc.on('touchmove touchend MSPointerMove MSPointerUp', fn);
            }

            if(memory.x || memory.y) fn();

            return fn;

        })(), 15);

        // Check for dom modifications
        UI.domObserve('[data-uk-observe]', function() {

            var ele = this;

            UI.domObservers.forEach(function(fn){
                fn(ele);
            });
        });

        if (UI.support.touch) {

            // remove css hover rules for touch devices
            // UI.Utils.removeCssRules(/\.uk-(?!navbar).*:hover/);

            // viewport unit fix for uk-height-viewport - should be fixed in iOS 8
            if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g)) {

                UI.$win.on('load orientationchange resize', UI.Utils.debounce((function(){

                    var fn = function() {
                        $('.uk-height-viewport').css('height', window.innerHeight);
                        return fn;
                    };

                    return fn();

                })(), 100));
            }
        }
    });

    // add touch identifier class
    $html.addClass(UI.support.touch ? "uk-touch" : "uk-notouch");

    // add uk-hover class on tap to support overlays on touch devices
    if (UI.support.touch) {

        var hoverset = false, selector = '.uk-overlay, .uk-overlay-toggle, .uk-has-hover', exclude;

        $html.on('touchstart MSPointerDown', selector, function() {

            if(hoverset) $('.uk-hover').removeClass('uk-hover');

            hoverset = $(this).addClass('uk-hover');

        }).on('touchend MSPointerUp', function(e) {

            exclude = $(e.target).parents(selector);

            if (hoverset) hoverset.not(exclude).removeClass('uk-hover');
        });
    }

    return UI;
});
<|endoftext|>