<commit_before>$( document ).ready(function() {
	$('audio#eel').trigger('load');
    var spotCounter = 1;
	var eelWidth=127;
	var eelHeight=127;

    $('#face-container').mousedown(function(event){
    	$(this).addClass('punching');
    	$(this).append($('#original-spot').clone().removeAttr('id').attr('id','spot-'+spotCounter).css('left', event.pageX - eelWidth).css('top', event.pageY - eelHeight));
    	$('audio#eel').trigger('play');
        spotCounter++;
    });
    $('#face-container').mouseup(function(){
    	$(this).removeClass('punching');
    });
});<commit_msg>preloading cursor images<commit_after>$( document ).ready(function() {
    preloadCursors();
    $('audio#eel').trigger('load');
    var spotCounter = 1;
	var eelWidth=127;
	var eelHeight=127;

    $('#face-container').mousedown(function(event){
    	$(this).addClass('punching');
    	$(this).append($('#original-spot').clone().removeAttr('id').attr('id','spot-'+spotCounter).css('left', event.pageX - eelWidth).css('top', event.pageY - eelHeight));
    	$('audio#eel').trigger('play');
        spotCounter++;
    });
    $('#face-container').mouseup(function(){
    	$(this).removeClass('punching');
    });

    function preloadCursors(){
         // counter
         var i = 0;

         // create object
         imageObj = new Image();

         // set image list
         images = new Array();
         images[0]='img/cursor_eel_rotated.png';

         // start preloading
         for(i=0; i<=(images.length-1); i++)
         {
              imageObj.src=images[i];
         }
    }
});<|endoftext|>


<commit_before>function submit() {
  // Firebase
  var ref = new Firebase("https://anti-bully.firebaseio.com");

  // Input value
  var nama = $('#nama').val(),
      kepala_sekolah = $('#kepala_sekolah').val(),
      no_telp = $('#no_telp').val(),
      alamat_sekolah = $('#alamat').val(),
      kelas = $('#kelas').val(),
      nisn = $("#nisn").val(),
      kode_pos = $('#kode_pos').val(),
      sekolah = $('#sekolah').val(),
      tingkat_sekolah = $('#tingkat').val(),
      masalah = $('#masalah').val();

  // Required input
  var input = $('.input').val();
  if (input == '') {
    // Input cannot be empty
    alert('Please insert input');
    return false;
  }
  else if (masalah.length < 50 ){
    // Textare content cannot be less than 50
    alert('Please write a sentence more than 50 characters')
    return false;
  }
  else {
    // Log input value for testing
    console.log('Nama: ' + nama);
    console.log('Kepala Sekolah: ' + kepala_sekolah);
    console.log('No Telp: ' + no_telp);
    console.log('Alamat: ' + alamat_sekolah);
    console.log('Kelas:' + kelas);
    console.log('NISN: ' + nisn);
    console.log('Kode Pos: ' + kode_pos);
    console.log('Sekolah: ' + sekolah);
    console.log('Tingkat Sekolah: ' + tingkat_sekolah);
    console.log('Masalah: ' + masalah);
    // Send data to firebase
    ref.push().set({
      nama: nama,
      kepala_sekolah: kepala_sekolah,
      no_telp: no_telp,
      alamat_sekolah: alamat_sekolah,
      kelas: kelas,
      nisn: nisn,
      kode_pos: kode_pos,
      sekolah: sekolah,
      tingkat_sekolah: tingkat_sekolah,
      masalah: masalah
    });
    alert('Terima kasih telah menjadi anti-bully hero. Kami akan menindaklanjuti laporanmu.');
    return true;
  }
}
<commit_msg>Fix textare to textarea<commit_after>function submit() {
  // Firebase
  var ref = new Firebase("https://anti-bully.firebaseio.com");

  // Input value
  var nama = $('#nama').val(),
      kepala_sekolah = $('#kepala_sekolah').val(),
      no_telp = $('#no_telp').val(),
      alamat_sekolah = $('#alamat').val(),
      kelas = $('#kelas').val(),
      nisn = $("#nisn").val(),
      kode_pos = $('#kode_pos').val(),
      sekolah = $('#sekolah').val(),
      tingkat_sekolah = $('#tingkat').val(),
      masalah = $('#masalah').val();

  // Required input
  var input = $('.input').val();
  if (input == '') {
    // Input cannot be empty
    alert('Please insert input');
    return false;
  }
  else if (masalah.length < 50 ){
    // Textarea content cannot be less than 50
    alert('Please write a sentence more than 50 characters')
    return false;
  }
  else {
    // Log input value for testing
    console.log('Nama: ' + nama);
    console.log('Kepala Sekolah: ' + kepala_sekolah);
    console.log('No Telp: ' + no_telp);
    console.log('Alamat: ' + alamat_sekolah);
    console.log('Kelas:' + kelas);
    console.log('NISN: ' + nisn);
    console.log('Kode Pos: ' + kode_pos);
    console.log('Sekolah: ' + sekolah);
    console.log('Tingkat Sekolah: ' + tingkat_sekolah);
    console.log('Masalah: ' + masalah);
    // Send data to firebase
    ref.push().set({
      nama: nama,
      kepala_sekolah: kepala_sekolah,
      no_telp: no_telp,
      alamat_sekolah: alamat_sekolah,
      kelas: kelas,
      nisn: nisn,
      kode_pos: kode_pos,
      sekolah: sekolah,
      tingkat_sekolah: tingkat_sekolah,
      masalah: masalah
    });
    alert('Terima kasih telah menjadi anti-bully hero. Kami akan menindaklanjuti laporanmu.');
    return true;
  }
}
<|endoftext|>


<commit_before>/*! viewportSize | Author: Tyson Matanich, 2013 | License: MIT */
(function(n){n.viewportSize={},n.viewportSize.getHeight=function(){return t("Height")},n.viewportSize.getWidth=function(){return t("Width")};var t=function(t){var f,o=t.toLowerCase(),e=n.document,i=e.documentElement,r,u;return n["inner"+t]===undefined?f=i["client"+t]:n["inner"+t]!=i["client"+t]?(r=e.createElement("body"),r.id="vpw-test-b",r.style.cssText="overflow:scroll",u=e.createElement("div"),u.id="vpw-test-d",u.style.cssText="position:absolute;top:-1000px",u.innerHTML="


<commit_before>
function changeImage(picture) {
	$(".active").css("opacity", "0");
	if (picture == buckingham) {
		$(".active-img").attr("src", "img/buckingham.jpg");
		$(".active-caption").html("
Buckingham Palace
");
		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		})
		$("#buckingham").removeClass("inactive");
	}
	if (picture == tower) {
		$(".active-img").attr("src", "img/tower.jpg");

		$(".active-caption").html("
The Tower of London
");

		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		});
		$("#tower").removeClass("inactive");
	}
	if (picture == market) {
		$(".active-img").attr("src", "img/market.jpg");
		$(".active-caption").html("
The Portobello Market
");
		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		});
		$("#market").removeClass("inactive");
	}
	if (picture == bridge) {
		$(".active-img").attr("src", "img/bridge.jpg");
		$(".active-caption").html("
Tower Bridge
");
		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		})
		$("#bridge").removeClass("inactive");
	}
	$(".active").animate({opacity: "1"}, 1000);
}

$(document).ready(function() {
	$("#bridge").click(function(){changeImage(bridge)});
	$("#buckingham").click(function(){changeImage(buckingham)});
	$("#tower").click(function(){changeImage(tower)});
	$("#market").click(function(){changeImage(market)});
});

var headerColor = "rgba(240, 240, 240,";

var mq = window.matchMedia( "(min-width: 593px)" );
if (mq.matches) {
	checkScroll();

	$(window).scroll(checkScroll);
	function checkScroll() {
		var top = $(window).scrollTop();
		if(top > 0) {
			$("nav").css("backgroundColor", headerColor + "0)", 500);
		}
		if(top > 80) {
			$("nav").css("backgroundColor", headerColor + ".05", 500);
		}
		if(top > 100) {
			$("nav").css("backgroundColor", headerColor + ".1", 500);
		}
		if(top > 110) {
			$("nav").css("backgroundColor", headerColor + ".15", 500);
		}
		if(top > 120) {
			$("nav").css("backgroundColor", headerColor + ".3", 500);
		}
		if(top > 130) {
			$("nav").css("backgroundColor", headerColor + ".35", 500);
		}
		if(top > 140) {
			$("nav").css("backgroundColor", headerColor + ".4", 500);
		}
		if(top > 150) {
			$("nav").css("backgroundColor", headerColor + ".45", 500);
		}
		if(top > 160) {
			$("nav").css("backgroundColor", headerColor + ".5", 500);
		}
		if(top > 170) {
			$("nav").css("backgroundColor", headerColor + ".55", 500);
		}
		if(top > 180) {
			$("nav").css("backgroundColor", headerColor + ".6", 500);
		}
		if(top > 190) {
			$("nav").css("backgroundColor", headerColor + ".65", 500);
		}
		if(top > 200) {
			$("nav").css("backgroundColor", headerColor + ".7", 500);
		}
		if(top > 210) {
			$("nav").css("backgroundColor", headerColor + ".75", 500);
		}
		if(top > 220) {
			$("nav").css("backgroundColor", headerColor + ".8", 500);
		}
		if(top > 230) {
			$("nav").css("backgroundColor", headerColor + ".85", 500);
		}
		if(top > 240) {
			$("nav").css("backgroundColor", headerColor + ".9", 500);
		}
		if(top > 250) {
			$("nav").css("backgroundColor", headerColor + ".95", 500);
		}
		if(top > 260) {
			$("nav").css("backgroundColor", headerColor + "1", 500);
		}
	}
}
else {
	$("nav").css("backgroundColor", "rgba(240,240,240,1)");
}

function initMap() {
		var twr = {lat:51.508293, lng: -0.075992};
        var centr = {lat: 51.510042, lng: -0.128070};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: centr
        });
        var marker = new google.maps.Marker({
          position: twr,
          map: map
        });
        var bigben = new google.maps.Marker({
        	position: {lat:51.500896, lng:-0.124615},
        	map: map
        });
        var buck = new google.maps.Marker({
        	position: {lat:51.501564, lng:-0.141954},
        	map: map
        });
        var portobello = new google.maps.Marker({
        	position: {lat:51.516072, lng:-0.205036},
        	map: map
        });
        var twrbridge = new google.maps.Marker({
        	position: {lat:51.505790, lng:-0.075389},
        	map: map
        });
        var park = new google.maps.Marker({
        	position: {lat:51.507008, lng:-0.165934},
        	map: map
        });
        var tate = new google.maps.Marker({
        	position: {lat:51.507762, lng:-0.099367},
        	map: map
        });
      }

// shout out to https://css-tricks.com/snippets/jquery/smooth-scrolling/ for this scrolling help
$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - 100}, 1000);
        return false;
      }
    }
  });
});

<commit_msg>fixed js media query problem with responsive nav bar<commit_after>
function changeImage(picture) {
	$(".active").css("opacity", "0");
	if (picture == buckingham) {
		$(".active-img").attr("src", "img/buckingham.jpg");
		$(".active-caption").html("
Buckingham Palace
");
		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		})
		$("#buckingham").removeClass("inactive");
	}
	if (picture == tower) {
		$(".active-img").attr("src", "img/tower.jpg");

		$(".active-caption").html("
The Tower of London
");

		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		});
		$("#tower").removeClass("inactive");
	}
	if (picture == market) {
		$(".active-img").attr("src", "img/market.jpg");
		$(".active-caption").html("
The Portobello Market
");
		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		});
		$("#market").removeClass("inactive");
	}
	if (picture == bridge) {
		$(".active-img").attr("src", "img/bridge.jpg");
		$(".active-caption").html("
Tower Bridge
");
		$(".thumbnail").each(function() {
		 	$( this ).addClass("inactive");
		})
		$("#bridge").removeClass("inactive");
	}
	$(".active").animate({opacity: "1"}, 1000);
}

$(document).ready(function() {
	$("#bridge").click(function(){changeImage(bridge)});
	$("#buckingham").click(function(){changeImage(buckingham)});
	$("#tower").click(function(){changeImage(tower)});
	$("#market").click(function(){changeImage(market)});
});

var headerColor = "rgba(240, 240, 240,";

// media query event handler
if (matchMedia) {
  var mq = window.matchMedia("(min-width: 594px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

// media query change
function WidthChange(mq) {
  if (mq.matches) {
    $(window).scroll(checkScroll);
	function checkScroll() {
		checkScroll();
		var top = $(window).scrollTop();
		if(top > 0) {
			$("nav").css("backgroundColor", headerColor + "0)", 500);
		}
		if(top > 80) {
			$("nav").css("backgroundColor", headerColor + ".05", 500);
		}
		if(top > 100) {
			$("nav").css("backgroundColor", headerColor + ".1", 500);
		}
		if(top > 110) {
			$("nav").css("backgroundColor", headerColor + ".15", 500);
		}
		if(top > 120) {
			$("nav").css("backgroundColor", headerColor + ".3", 500);
		}
		if(top > 130) {
			$("nav").css("backgroundColor", headerColor + ".35", 500);
		}
		if(top > 140) {
			$("nav").css("backgroundColor", headerColor + ".4", 500);
		}
		if(top > 150) {
			$("nav").css("backgroundColor", headerColor + ".45", 500);
		}
		if(top > 160) {
			$("nav").css("backgroundColor", headerColor + ".5", 500);
		}
		if(top > 170) {
			$("nav").css("backgroundColor", headerColor + ".55", 500);
		}
		if(top > 180) {
			$("nav").css("backgroundColor", headerColor + ".6", 500);
		}
		if(top > 190) {
			$("nav").css("backgroundColor", headerColor + ".65", 500);
		}
		if(top > 200) {
			$("nav").css("backgroundColor", headerColor + ".7", 500);
		}
		if(top > 210) {
			$("nav").css("backgroundColor", headerColor + ".75", 500);
		}
		if(top > 220) {
			$("nav").css("backgroundColor", headerColor + ".8", 500);
		}
		if(top > 230) {
			$("nav").css("backgroundColor", headerColor + ".85", 500);
		}
		if(top > 240) {
			$("nav").css("backgroundColor", headerColor + ".9", 500);
		}
		if(top > 250) {
			$("nav").css("backgroundColor", headerColor + ".95", 500);
		}
		if(top > 260) {
			$("nav").css("backgroundColor", headerColor + "1", 500);
		}
	}
}
	else {
	    $("nav").css("backgroundColor", "rgba(240,240,240,1)");
	}

}

function initMap() {
		var twr = {lat:51.508293, lng: -0.075992};
        var centr = {lat: 51.510042, lng: -0.128070};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 12,
          center: centr
        });
        var marker = new google.maps.Marker({
          position: twr,
          map: map
        });
        var bigben = new google.maps.Marker({
        	position: {lat:51.500896, lng:-0.124615},
        	map: map
        });
        var buck = new google.maps.Marker({
        	position: {lat:51.501564, lng:-0.141954},
        	map: map
        });
        var portobello = new google.maps.Marker({
        	position: {lat:51.516072, lng:-0.205036},
        	map: map
        });
        var twrbridge = new google.maps.Marker({
        	position: {lat:51.505790, lng:-0.075389},
        	map: map
        });
        var park = new google.maps.Marker({
        	position: {lat:51.507008, lng:-0.165934},
        	map: map
        });
        var tate = new google.maps.Marker({
        	position: {lat:51.507762, lng:-0.099367},
        	map: map
        });
      }

// shout out to https://css-tricks.com/snippets/jquery/smooth-scrolling/ for this scrolling help
$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - 100}, 1000);
        return false;
      }
    }
  });
});

<|endoftext|>


<commit_before>jQuery(function($){

inicio();
 $(window).load(function(){

        $(".sticky-nav").sticky({ topSpacing: 0 });

    });

/* ==================================================
   Login fancybox
================================================== */
$("#login")
    .attr('rel', 'gallery')
    .fancybox({
        maxWidth	: 700,
		maxHeight	: 500,
       openEffect	: 'elastic',
    	closeEffect	: 'elastic',
        helpers : {
            title : null
        }
    });

/* ==================================================
   Mobile Navigation
================================================== */
var mobileMenuClone = $('#menu').clone().attr('id', 'navigation-mobile');

 function mobileNav(){
	var windowWidth = $(window).width();

	if( windowWidth <= 979 ) {
		if( $('#mobile-nav').length > 0 ) {
			mobileMenuClone.insertAfter('#menu');
			$('#navigation-mobile #menu-nav').attr('id', 'menu-nav-mobile');
		}
	} else {
		$('#navigation-mobile').css('display', 'none');
		if ($('#mobile-nav').hasClass('open')) {
			$('#mobile-nav').removeClass('open');
		}
	}
}

 function listenerMenu(){
	$('#mobile-nav').on('click', function(e){

        $(this).toggleClass('open');

		if ($('#mobile-nav').hasClass('open')) {
			$('#navigation-mobile').slideDown(500, 'easeOutExpo');
		} else {
			$('#navigation-mobile').slideUp(500, 'easeOutExpo');
		}
		e.preventDefault();
	});

	$('#menu-nav-mobile a').on('click', function(){
		$('#mobile-nav').removeClass('open');
		$('#navigation-mobile').slideUp(350, 'easeOutExpo');
	});
}

/* ==================================================
   Slider Options
================================================== */
  function slider(){
	$.supersized({
		// Functionality
		slideshow               :   1,			// Slideshow on/off
		autoplay				:	1,			// Slideshow starts playing automatically
		start_slide             :   1,			// Start slide (0 is random)
		stop_loop				:	0,			// Pauses slideshow on last slide
		random					: 	0,			// Randomize slide order (Ignores start slide)
		slide_interval          :   4000,		// Length between transitions
		transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
		transition_speed		:	2000,		// Speed of transition
		new_window				:	1,			// Image links open in new window/tab
		pause_hover             :   0,			// Pause slideshow on hover
		keyboard_nav            :   1,			// Keyboard navigation on/off
		performance				:	1,			// 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
		image_protect			:	1,			// Disables image dragging and right click with Javascript

		// Size & Position
		min_width		        :   0,			// Min width allowed (in pixels)
		min_height		        :   0,			// Min height allowed (in pixels)
		vertical_center         :   1,			// Vertically center background
		horizontal_center       :   1,			// Horizontally center background
		fit_always				:	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_portrait         	:   1,			// Portrait images will not exceed browser height
		fit_landscape			:   0,			// Landscape images will not exceed browser width

		// Components
		slide_links				:	'blank',	// Individual links for each slide (Options: false, 'num', 'name', 'blank')
		thumb_links				:	0,			// Individual thumb links for each slide
		thumbnail_navigation    :   0,			// Thumbnail navigation
		slides 					:  	[			// Slideshow Images

											{image : '../images/slider-images/image03.jpg', title : '

', thumb : '', url : ''},
											{image : '../images/profilePictures/5.jpg', title : '

', thumb : '', url : ''},
											{image : '../images/slider-images/image03.jpg', title : '

', thumb : '', url : ''},
											{image : '../images/slider-images/image03.jpg', title : '

', thumb : '', url : ''}
									],

		// Theme Options
		progress_bar			:	0,			// Timer for each slide
		mouse_scrub				:	0

	});

}

/* ==================================================
   Navigation Fix
================================================== */

 function nav(){
	//$('.sticky-nav').waypoint('sticky');
         $(".sticky-nav").sticky({ topSpacing: 0 });
}

/* ==================================================
   Filter Works
================================================== */

 function filter(){
	if($('#projects').length > 0){
		var $container = $('#projects');

		$container.imagesLoaded(function() {
			$container.isotope({
			  // options
			  animationEngine: 'best-available',
			  itemSelector : '.item-thumbs',
			  layoutMode : 'fitRows'
			});
		});

		// filter items when filter link is clicked
		var $optionSets = $('#options .option-set'),
			$optionLinks = $optionSets.find('a');

		  $optionLinks.click(function(){
			var $this = $(this);
			// don't proceed if already selected
			if ( $this.hasClass('selected') ) {
			  return false;
			}
			var $optionSet = $this.parents('.option-set');
			$optionSet.find('.selected').removeClass('selected');
			$this.addClass('selected');

			// make option object dynamically, i.e. { filter: '.my-filter-class' }
			var options = {},
				key = $optionSet.attr('data-option-key'),
				value = $this.attr('data-option-value');
			// parse 'false' as false boolean
			value = value === 'false' ? false : value;
			options[ key ] = value;
			if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
			  // changes in layout modes need extra logic
			  changeLayoutMode( $this, options )
			} else {
			  // otherwise, apply new options
			  $container.isotope( options );
			}

			return false;
		});
	}
}

/* ==================================================
   FancyBox
================================================== */

 function fancyBox(){
	if($('.fancybox').length > 0 || $('.fancybox-media').length > 0 || $('.fancybox-various').length > 0){

		$(".fancybox").fancybox({
				padding : 0,
				beforeShow: function () {
					this.title = $(this.element).attr('title');
					this.title = '
' + this.title + '
' + '
' + $(this.element).parent().find('img').attr('alt') + '
';
				},
				helpers : {
					title : { type: 'inside' },
				}
			});

		$('.fancybox-media').fancybox({
			openEffect  : 'none',
			closeEffect : 'none',
			helpers : {
				media : {}
			}
		});
	}
}

/* ==================================================
   Contact Form
================================================== */
/*
BRUSHED.contactForm = function(){
	$("#contact-submit").on('click',function() {
		$contact_form = $('#contact-form');

		var fields = $contact_form.serialize();

		$.ajax({
			type: "POST",
			url: "_include/php/contact.php",
			data: fields,
			dataType: 'json',
			success: function(response) {

				if(response.status){
					$('#contact-form input').val('');
					$('#contact-form textarea').val('');
				}

				$('#response').empty().html(response.html);
			}
		});
		return false;
	});
}
*/

/* ==================================================
   Twitter Feed
================================================== */
/*
BRUSHED.tweetFeed = function(){

	var valueTop = -64; // Margin Top Value

    $("#ticker").tweet({
          modpath: '_include/js/twitter/',
          username: "Bluxart", // Change this with YOUR ID
          page: 1,
          avatar_size: 0,
          count: 10,
		  template: "{text}{time}",
		  filter: function(t){ return ! /^@\w+/.test(t.tweet_raw_text); },
          loading_text: "loading ..."
	}).bind("loaded", function() {
	  var ul = $(this).find(".tweet_list");
	  var ticker = function() {
		setTimeout(function() {
			ul.find('li:first').animate( {marginTop: valueTop + 'px'}, 500, 'linear', function() {
				$(this).detach().appendTo(ul).removeAttr('style');
			});
		  ticker();
		}, 5000);
	  };
	  ticker();
	});

}*/

/* ==================================================
   Menu Highlight
================================================== */

function menu(){
	$('#menu-nav, #menu-nav-mobile').onePageNav({
		currentClass: 'current',
    	changeHash: false,
    	scrollSpeed: 750,
    	scrollOffset: 30,
    	scrollThreshold: 0.5,
		easing: 'easeOutExpo',
		filter: ':not(.external)'
	});
}

/* ==================================================
   Next Section
================================================== */

 function goSection(){
        $('#nextsection').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
   GoUp
================================================== */

function goUp(){
    	$('#goUp').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
	Scroll to Top
================================================== */
 function scrollToTop(){

	var windowWidth = $(window).width(),
		didScroll = false;

	var $arrow = $('#back-to-top');

	$arrow.click(function(e) {
		$('body,html').animate({ scrollTop: "0" }, 750, 'easeOutExpo' );
		e.preventDefault();
	})

	$(window).scroll(function() {
		didScroll = true;
	});

	setInterval(function() {
		if( didScroll ) {
			didScroll = false;

			if( $(window).scrollTop() > 1000 ) {
				$arrow.css('display', 'block');
			} else {
				$arrow.css('display', 'none');
			}
		}
	}, 250);
}

/* ==================================================
   Thumbs / Social Effects
================================================== */

 function utils(){

	$('.item-thumbs').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('.image-wrap').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('#social ul li').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

}

/* ==================================================
   Accordion
================================================== */

 function accordion(){
	var accordion_trigger = $('.accordion-heading.accordionize');

	accordion_trigger.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	accordion_trigger.find('.active').addClass('inactive');
		  	accordion_trigger.find('.active').removeClass('active');
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Toggle
================================================== */

 function toggle(){
	var accordion_trigger_toggle = $('.accordion-heading.togglize');

	accordion_trigger_toggle.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Tooltip
================================================== */

 function toolTip(){
    $('a[data-toggle=tooltip]').tooltip();
}

/* ==================================================
	Init
================================================== */

function inicio(){
//	Modernizr.load([
//	{
//		test: Modernizr.placeholder,
//		nope: '<?//php echo Yii::app()->request->baseUrl; ?>/js/placeholder.js',
//		complete : function() {
//				if (!Modernizr.placeholder) {
//						Placeholders.init({
//						live: true,
//						hideOnFocus: false,
//						className: "yourClass",
//						textColor: "#999"
//						});
//				}
//		}
//	}
//	]);

	// Preload the page with jPreLoader
	$('body').jpreLoader({
		splashID: "#jSplash",
		showSplash: true,
		showPercentage: true,
		autoClose: true,
		splashFunction: function() {
			$('#circle').delay(250).animate({'opacity' : 1}, 500, 'linear');
		}
	});

        $(".sticky-nav").sticky({ topSpacing: 0 });

        //var BRUSHED = window.BRUSHED || {};
        slider();

	nav();
	mobileNav();
	listenerMenu();
	menu();
	goSection();
	goUp();
	filter();
	fancyBox();
	//contactForm();
	//tweetFeed();
	scrollToTop();
	utils();
	accordion();
	toggle();
	toolTip();
}

$(window).resize(function(){
	BRUSHED.mobileNav();
});

});
<commit_msg>table publication's<commit_after>jQuery(function($){

inicio();
 $(window).load(function(){

        $(".sticky-nav").sticky({ topSpacing: 0 });

    });

/* ==================================================
   Login fancybox
================================================== */
$("#login")
    .attr('rel', 'gallery')
    .fancybox({
        maxWidth	: 700,
		maxHeight	: 500,
       openEffect	: 'elastic',
    	closeEffect	: 'elastic',
        helpers : {
            title : null
        }
    });

/* ==================================================
   Mobile Navigation
================================================== */
var mobileMenuClone = $('#menu').clone().attr('id', 'navigation-mobile');

 function mobileNav(){
	var windowWidth = $(window).width();

	if( windowWidth <= 979 ) {
		if( $('#mobile-nav').length > 0 ) {
			mobileMenuClone.insertAfter('#menu');
			$('#navigation-mobile #menu-nav').attr('id', 'menu-nav-mobile');
		}
	} else {
		$('#navigation-mobile').css('display', 'none');
		if ($('#mobile-nav').hasClass('open')) {
			$('#mobile-nav').removeClass('open');
		}
	}
}

 function listenerMenu(){
	$('#mobile-nav').on('click', function(e){

        $(this).toggleClass('open');

		if ($('#mobile-nav').hasClass('open')) {
			$('#navigation-mobile').slideDown(500, 'easeOutExpo');
		} else {
			$('#navigation-mobile').slideUp(500, 'easeOutExpo');
		}
		e.preventDefault();
	});

	$('#menu-nav-mobile a').on('click', function(){
		$('#mobile-nav').removeClass('open');
		$('#navigation-mobile').slideUp(350, 'easeOutExpo');
	});
}

/* ==================================================
   Slider Options
================================================== */
  function slider(){
	$.supersized({
		// Functionality
		slideshow               :   1,			// Slideshow on/off
		autoplay				:	1,			// Slideshow starts playing automatically
		start_slide             :   1,			// Start slide (0 is random)
		stop_loop				:	0,			// Pauses slideshow on last slide
		random					: 	0,			// Randomize slide order (Ignores start slide)
		slide_interval          :   4000,		// Length between transitions
		transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
		transition_speed		:	2000,		// Speed of transition
		new_window				:	1,			// Image links open in new window/tab
		pause_hover             :   0,			// Pause slideshow on hover
		keyboard_nav            :   1,			// Keyboard navigation on/off
		performance				:	1,			// 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
		image_protect			:	1,			// Disables image dragging and right click with Javascript

		// Size & Position
		min_width		        :   0,			// Min width allowed (in pixels)
		min_height		        :   0,			// Min height allowed (in pixels)
		vertical_center         :   1,			// Vertically center background
		horizontal_center       :   1,			// Horizontally center background
		fit_always				:	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_portrait         	:   1,			// Portrait images will not exceed browser height
		fit_landscape			:   0,			// Landscape images will not exceed browser width

		// Components
		slide_links				:	'blank',	// Individual links for each slide (Options: false, 'num', 'name', 'blank')
		thumb_links				:	0,			// Individual thumb links for each slide
		thumbnail_navigation    :   0,			// Thumbnail navigation
		slides 					:  	[			// Slideshow Images

											{image : 'http://invisibledisabilities.org/wp-content/gallery/pamphlets/fragrance-free-zone.jpg', title : '

', thumb : '', url : ''},
											{image : '../images/profilePictures/5.jpg', title : '

', thumb : '', url : ''},
											{image : '.http://gsr2r.com/blog/wp-content/uploads/2013/11/bigstock_Office_Life_-_Happy_People_Hav_4098282.jpg ', title : '

', thumb : '', url : ''},
											{image : '../images/slider-images/image03.jpg', title : '

', thumb : '', url : ''}
									],

		// Theme Options
		progress_bar			:	0,			// Timer for each slide
		mouse_scrub				:	0

	});

}

/* ==================================================
   Navigation Fix
================================================== */

 function nav(){
	//$('.sticky-nav').waypoint('sticky');
         $(".sticky-nav").sticky({ topSpacing: 0 });
}

/* ==================================================
   Filter Works
================================================== */

 function filter(){
	if($('#projects').length > 0){
		var $container = $('#projects');

		$container.imagesLoaded(function() {
			$container.isotope({
			  // options
			  animationEngine: 'best-available',
			  itemSelector : '.item-thumbs',
			  layoutMode : 'fitRows'
			});
		});

		// filter items when filter link is clicked
		var $optionSets = $('#options .option-set'),
			$optionLinks = $optionSets.find('a');

		  $optionLinks.click(function(){
			var $this = $(this);
			// don't proceed if already selected
			if ( $this.hasClass('selected') ) {
			  return false;
			}
			var $optionSet = $this.parents('.option-set');
			$optionSet.find('.selected').removeClass('selected');
			$this.addClass('selected');

			// make option object dynamically, i.e. { filter: '.my-filter-class' }
			var options = {},
				key = $optionSet.attr('data-option-key'),
				value = $this.attr('data-option-value');
			// parse 'false' as false boolean
			value = value === 'false' ? false : value;
			options[ key ] = value;
			if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
			  // changes in layout modes need extra logic
			  changeLayoutMode( $this, options )
			} else {
			  // otherwise, apply new options
			  $container.isotope( options );
			}

			return false;
		});
	}
}

/* ==================================================
   FancyBox
================================================== */

 function fancyBox(){
	if($('.fancybox').length > 0 || $('.fancybox-media').length > 0 || $('.fancybox-various').length > 0){

		$(".fancybox").fancybox({
				padding : 0,
				beforeShow: function () {
					this.title = $(this.element).attr('title');
					this.title = '
' + this.title + '
' + '
' + $(this.element).parent().find('img').attr('alt') + '
';
				},
				helpers : {
					title : { type: 'inside' },
				}
			});

		$('.fancybox-media').fancybox({
			openEffect  : 'none',
			closeEffect : 'none',
			helpers : {
				media : {}
			}
		});
	}
}

/* ==================================================
   Contact Form
================================================== */
/*
BRUSHED.contactForm = function(){
	$("#contact-submit").on('click',function() {
		$contact_form = $('#contact-form');

		var fields = $contact_form.serialize();

		$.ajax({
			type: "POST",
			url: "_include/php/contact.php",
			data: fields,
			dataType: 'json',
			success: function(response) {

				if(response.status){
					$('#contact-form input').val('');
					$('#contact-form textarea').val('');
				}

				$('#response').empty().html(response.html);
			}
		});
		return false;
	});
}
*/

/* ==================================================
   Twitter Feed
================================================== */
/*
BRUSHED.tweetFeed = function(){

	var valueTop = -64; // Margin Top Value

    $("#ticker").tweet({
          modpath: '_include/js/twitter/',
          username: "Bluxart", // Change this with YOUR ID
          page: 1,
          avatar_size: 0,
          count: 10,
		  template: "{text}{time}",
		  filter: function(t){ return ! /^@\w+/.test(t.tweet_raw_text); },
          loading_text: "loading ..."
	}).bind("loaded", function() {
	  var ul = $(this).find(".tweet_list");
	  var ticker = function() {
		setTimeout(function() {
			ul.find('li:first').animate( {marginTop: valueTop + 'px'}, 500, 'linear', function() {
				$(this).detach().appendTo(ul).removeAttr('style');
			});
		  ticker();
		}, 5000);
	  };
	  ticker();
	});

}*/

/* ==================================================
   Menu Highlight
================================================== */

function menu(){
	$('#menu-nav, #menu-nav-mobile').onePageNav({
		currentClass: 'current',
    	changeHash: false,
    	scrollSpeed: 750,
    	scrollOffset: 30,
    	scrollThreshold: 0.5,
		easing: 'easeOutExpo',
		filter: ':not(.external)'
	});
}

/* ==================================================
   Next Section
================================================== */

 function goSection(){
        $('#nextsection').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
   GoUp
================================================== */

function goUp(){
    	$('#goUp').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
	Scroll to Top
================================================== */
 function scrollToTop(){

	var windowWidth = $(window).width(),
		didScroll = false;

	var $arrow = $('#back-to-top');

	$arrow.click(function(e) {
		$('body,html').animate({ scrollTop: "0" }, 750, 'easeOutExpo' );
		e.preventDefault();
	})

	$(window).scroll(function() {
		didScroll = true;
	});

	setInterval(function() {
		if( didScroll ) {
			didScroll = false;

			if( $(window).scrollTop() > 1000 ) {
				$arrow.css('display', 'block');
			} else {
				$arrow.css('display', 'none');
			}
		}
	}, 250);
}

/* ==================================================
   Thumbs / Social Effects
================================================== */

 function utils(){

	$('.item-thumbs').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('.image-wrap').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('#social ul li').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

}

/* ==================================================
   Accordion
================================================== */

 function accordion(){
	var accordion_trigger = $('.accordion-heading.accordionize');

	accordion_trigger.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	accordion_trigger.find('.active').addClass('inactive');
		  	accordion_trigger.find('.active').removeClass('active');
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Toggle
================================================== */

 function toggle(){
	var accordion_trigger_toggle = $('.accordion-heading.togglize');

	accordion_trigger_toggle.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Tooltip
================================================== */

 function toolTip(){
    $('a[data-toggle=tooltip]').tooltip();
}

/* ==================================================
	Init
================================================== */

function inicio(){
//	Modernizr.load([
//	{
//		test: Modernizr.placeholder,
//		nope: '<?//php echo Yii::app()->request->baseUrl; ?>/js/placeholder.js',
//		complete : function() {
//				if (!Modernizr.placeholder) {
//						Placeholders.init({
//						live: true,
//						hideOnFocus: false,
//						className: "yourClass",
//						textColor: "#999"
//						});
//				}
//		}
//	}
//	]);

	// Preload the page with jPreLoader
	$('body').jpreLoader({
		splashID: "#jSplash",
		showSplash: true,
		showPercentage: true,
		autoClose: true,
		splashFunction: function() {
			$('#circle').delay(250).animate({'opacity' : 1}, 500, 'linear');
		}
	});

        $(".sticky-nav").sticky({ topSpacing: 0 });

        //var BRUSHED = window.BRUSHED || {};
        slider();

	nav();
	mobileNav();
	listenerMenu();
	menu();
	goSection();
	goUp();
	filter();
	fancyBox();
	//contactForm();
	//tweetFeed();
	scrollToTop();
	utils();
	accordion();
	toggle();
	toolTip();
}

$(window).resize(function(){
	BRUSHED.mobileNav();
});

});
<|endoftext|>


<commit_before>(function(undefined) {
  function getGraphSources() {
    var graphSources = [];
    d3.selectAll(".graph").each(function() {
      graphSources.push(d3.select(this).attr("data-src"));
    });
    return graphSources;
  }

  function renderError(err, source) {
    console.error("Error retrieving " + source + ": " + err);
  }

  /* Graphite structures points as [value, timestamp] */
  function xVal(point) { return new Date(1000 * point[1]) }
  function yVal(point) { return point[0] }

  var bisectDate = d3.bisector(function(d) { return xVal(d); }).left;

  function renderGraph(el, json) {
    var colors = d3.scale.category10();

    var h = 600;
    var w = 700;
    var padding = 80;

    var xScale = d3.time.scale()
      .range([padding, w - padding])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, xVal) })
      ]);

    var yScale = d3.scale.linear()
      .range([h - padding, 0])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, yVal) }),
      ]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return xScale(xVal(d)); })
      .y(function(d) { return yScale(yVal(d)); })
      .interpolate("monotone")
      .defined(function(d) { return !isNaN(yVal(d)); });

    var svg = d3.select(el)
                .append("svg")
                .attr("height", h)
                .attr("width", w);

    var legend = d3.select(el)
                   .append("ul")
                   .classed("legend", true)
                   .select("li")
                   .data(json)
                   .enter()
                     .append("li")
                     .text(function(d) { return d.target; })
                     .style("color", function(d, index) { return colors(index); });

    svg.append("defs").append("clipPath")
      .attr("id", "clip")
      .append("rect")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - (2 * padding))
      .attr("height", h - padding);

    svg.selectAll("g.series")
      .data(json, function(d) { return d.target; })
      .enter().append("g")
        .attr("class", "series")
        .attr("clip-path", "url(#clip)")
        .attr("stroke", function(d, index) {
          return colors(index);
        })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .enter().append("path")
            .classed("line", true)
            .attr("d", function(d) {
              return line(d);
            });

    svg.append("g")
      .classed("x-axis", true)
      .attr("transform", "translate(0, " + (h - padding) + ")")
      .call(xAxis);

    svg.append("g")
      .classed("y-axis", true)
      .attr("transform", "translate(" + padding + ", 0)")
      .call(yAxis);

    var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

    focus.append("line")
      .attr("x1", 0)
      .attr("x2", 0)
      .attr("y1", 0)
      .attr("y2", h - padding);

    svg.append("rect")
      .attr("class", "overlay")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - 2 * padding)
      .attr("height", h - padding)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout",  function() { focus.style("display", "none"); })
      .on("mousemove", function() {
        /* TODO validate the assumption that the first series in the json will
         * have x values for the whole shebang */
        var data = d3.selectAll("g.series").datum();
        var x0 = xScale.invert(d3.mouse(this)[0]),
            i = bisectDate(data.datapoints, x0, 1),
            d0 = data.datapoints[i - 1],
            d1 = data.datapoints[i];
        if(d0 && d1) {
          var d = x0 - xVal(d0) > xVal(d1) - x0 ? d1 : d0;
        } else if(d0) {
          var d = d0;
        } else if(d1) {
          var d = d1;
        } else {
          console.log("Failed to get datapoint for highlight");
        }
        focus.attr("transform", "translate(" + xScale(xVal(d)) + ",0)");
      });

    var tick = function(newJson) {
      var data = [];
      var lastData = d3.selectAll("g.series").data();
      for(var i = 0; i < lastData.length; i++) {
        var droppedPointCount = d3.bisectLeft(
          lastData[i].datapoints.map(function(d) { return d[1]; }),
          newJson[i].datapoints[0][1]
        );
        var addedPointCount = newJson[i].datapoints.length - lastData[i].datapoints.length;
        data[i] = {
          target: newJson[i].target,
          datapoints: lastData[i].datapoints.slice(0, droppedPointCount).concat(newJson[i].datapoints)
        }
      };

      xScale.domain([
        d3.min(data, function(d) { return d3.min(d.datapoints.slice(1), xVal) }),
        d3.max(data, function(d) { return d3.max(d.datapoints.slice(1), xVal) })
      ]);

      /* Draw the line with the new xscale, but translated back to the right */
      svg.selectAll("g.series")
        .data(data, function(d) { return d.target; })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .attr("d", line)
          .attr("transform", "translate(" + (xScale(xVal(data[0].datapoints[2])) - padding) + ",0)");

      yScale.domain([
        d3.min(data, function(d) { return d3.min(d.datapoints.slice(1), yVal) }),
        d3.max(data, function(d) { return d3.max(d.datapoints.slice(1), yVal) }),
      ]);

      xAxis.scale(xScale);
      yAxis.scale(yScale);

      var t = svg.transition()
        .duration(300)
        .ease("linear")

      t.selectAll("g.series path")
        .attr("d", line)
        .attr("transform", "translate(0,0)");
      t.select("g.x-axis").call(xAxis);
      t.select("g.y-axis").call(yAxis);

      for(var i = 0; i < data.length; i++) {
        data[i].datapoints.shift();
      }
    }

    return tick;
  }

  function randomSeries(name, start, stop, step) {
    var rand = d3.random.normal(100, 10);
    var times = d3.range(start, stop, step);
    var series = times.map(function(time) {
      return [rand(), time];
    });

    return function(steps) {
      if(steps != 0) {
        var lastTime = series[series.length - 1][1];
        var extraTimes = d3.range(lastTime + step, lastTime + step + steps * step, step);
        series = series.slice(steps).concat(extraTimes.map(function(time) {
          return [rand(), time];
        }));
        console.log(series);
      }
      return { target: 'a', datapoints: series };
    }
  }

  getGraphSources().forEach(function(source) {
    var start = 1364523350;
    var data = randomSeries('a', start, start + 60, 10);

    var tick = renderGraph("body", [data(0)]);
    var update = function() {
      tick([data(1)]);
    };

    setInterval(update, 10000);
  })

  //getGraphSources().forEach(function(source) {
  //  d3.json(source, function(err, json) {
  //    if(err && !json) {
  //      renderError(err, source);
  //    } else {
  //      var tick = renderGraph("body", json),
  //          update = function() {
  //            d3.json(source, function(err, json) {
  //              if(err && !json) {
  //                renderError(err, source);
  //              } else {
  //                tick(json);
  //              }
  //            });
  //          };
  //      //setTimeout(tick, 1000);
  //      setInterval(update, 1000);
  //    }
  //  });
  //});
})();
<commit_msg>The graph is undefined where the y value is null<commit_after>(function(undefined) {
  function getGraphSources() {
    var graphSources = [];
    d3.selectAll(".graph").each(function() {
      graphSources.push(d3.select(this).attr("data-src"));
    });
    return graphSources;
  }

  function renderError(err, source) {
    console.error("Error retrieving " + source + ": " + err);
  }

  /* Graphite structures points as [value, timestamp] */
  function xVal(point) { return new Date(1000 * point[1]) }
  function yVal(point) { return point[0] }

  var bisectDate = d3.bisector(function(d) { return xVal(d); }).left;

  function renderGraph(el, json) {
    var colors = d3.scale.category10();

    var h = 600;
    var w = 700;
    var padding = 80;

    var xScale = d3.time.scale()
      .range([padding, w - padding])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, xVal) })
      ]);

    var yScale = d3.scale.linear()
      .range([h - padding, 0])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, yVal) }),
      ]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return xScale(xVal(d)); })
      .y(function(d) { return yScale(yVal(d)); })
      .interpolate("monotone")
      .defined(function(d) { return !(yVal(d) == null) && !isNaN(yVal(d)); });

    var svg = d3.select(el)
                .append("svg")
                .attr("height", h)
                .attr("width", w);

    var legend = d3.select(el)
                   .append("ul")
                   .classed("legend", true)
                   .select("li")
                   .data(json)
                   .enter()
                     .append("li")
                     .text(function(d) { return d.target; })
                     .style("color", function(d, index) { return colors(index); });

    svg.append("defs").append("clipPath")
      .attr("id", "clip")
      .append("rect")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - (2 * padding))
      .attr("height", h - padding);

    svg.selectAll("g.series")
      .data(json, function(d) { return d.target; })
      .enter().append("g")
        .attr("class", "series")
        .attr("clip-path", "url(#clip)")
        .attr("stroke", function(d, index) {
          return colors(index);
        })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .enter().append("path")
            .classed("line", true)
            .attr("d", function(d) {
              return line(d);
            });

    svg.append("g")
      .classed("x-axis", true)
      .attr("transform", "translate(0, " + (h - padding) + ")")
      .call(xAxis);

    svg.append("g")
      .classed("y-axis", true)
      .attr("transform", "translate(" + padding + ", 0)")
      .call(yAxis);

    var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

    focus.append("line")
      .attr("x1", 0)
      .attr("x2", 0)
      .attr("y1", 0)
      .attr("y2", h - padding);

    svg.append("rect")
      .attr("class", "overlay")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - 2 * padding)
      .attr("height", h - padding)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout",  function() { focus.style("display", "none"); })
      .on("mousemove", function() {
        /* TODO validate the assumption that the first series in the json will
         * have x values for the whole shebang */
        var data = d3.selectAll("g.series").datum();
        var x0 = xScale.invert(d3.mouse(this)[0]),
            i = bisectDate(data.datapoints, x0, 1),
            d0 = data.datapoints[i - 1],
            d1 = data.datapoints[i];
        if(d0 && d1) {
          var d = x0 - xVal(d0) > xVal(d1) - x0 ? d1 : d0;
        } else if(d0) {
          var d = d0;
        } else if(d1) {
          var d = d1;
        } else {
          console.log("Failed to get datapoint for highlight");
        }
        focus.attr("transform", "translate(" + xScale(xVal(d)) + ",0)");
      });

    var tick = function(newJson) {
      var data = [];
      var lastData = d3.selectAll("g.series").data();
      for(var i = 0; i < lastData.length; i++) {
        var droppedPointCount = d3.bisectLeft(
          lastData[i].datapoints.map(function(d) { return d[1]; }),
          newJson[i].datapoints[0][1]
        );
        var addedPointCount = newJson[i].datapoints.length - lastData[i].datapoints.length;
        data[i] = {
          target: newJson[i].target,
          datapoints: lastData[i].datapoints.slice(0, droppedPointCount).concat(newJson[i].datapoints)
        }
      };

      xScale.domain([
        d3.min(data, function(d) { return d3.min(d.datapoints.slice(1), xVal) }),
        d3.max(data, function(d) { return d3.max(d.datapoints.slice(1), xVal) })
      ]);

      /* Draw the line with the new xscale, but translated back to the right */
      svg.selectAll("g.series")
        .data(data, function(d) { return d.target; })
        .selectAll("path.line")
          .data(function(d) { return [d.datapoints]; })
          .attr("d", line)
          .attr("transform", "translate(" + (xScale(xVal(data[0].datapoints[2])) - padding) + ",0)");

      yScale.domain([
        d3.min(data, function(d) { return d3.min(d.datapoints.slice(1), yVal) }),
        d3.max(data, function(d) { return d3.max(d.datapoints.slice(1), yVal) }),
      ]);

      xAxis.scale(xScale);
      yAxis.scale(yScale);

      var t = svg.transition()
        .duration(300)
        .ease("linear")

      t.selectAll("g.series path")
        .attr("d", line)
        .attr("transform", "translate(0,0)");
      t.select("g.x-axis").call(xAxis);
      t.select("g.y-axis").call(yAxis);

      for(var i = 0; i < data.length; i++) {
        data[i].datapoints.shift();
      }
    }

    return tick;
  }

  function randomSeries(name, start, stop, step) {
    var rand = d3.random.normal(100, 10);
    var times = d3.range(start, stop, step);
    var series = times.map(function(time) {
      return [rand(), time];
    });

    return function(steps) {
      if(steps != 0) {
        var lastTime = series[series.length - 1][1];
        var extraTimes = d3.range(lastTime + step, lastTime + step + steps * step, step);
        series = series.slice(steps).concat(extraTimes.map(function(time) {
          return [rand(), time];
        }));
        console.log(series);
      }
      return { target: 'a', datapoints: series };
    }
  }

  getGraphSources().forEach(function(source) {
    var start = 1364523350;
    var data = randomSeries('a', start, start + 60, 10);

    var tick = renderGraph("body", [data(0)]);
    var update = function() {
      tick([data(1)]);
    };

    setInterval(update, 10000);
  })

  //getGraphSources().forEach(function(source) {
  //  d3.json(source, function(err, json) {
  //    if(err && !json) {
  //      renderError(err, source);
  //    } else {
  //      var tick = renderGraph("body", json),
  //          update = function() {
  //            d3.json(source, function(err, json) {
  //              if(err && !json) {
  //                renderError(err, source);
  //              } else {
  //                tick(json);
  //              }
  //            });
  //          };
  //      //setTimeout(tick, 1000);
  //      setInterval(update, 1000);
  //    }
  //  });
  //});
})();
<|endoftext|>


<commit_before>function Checkers() {
  this.board = [];
  this.redTeam = [];
  this.whiteTeam = [];
  // WHY DOESN'T THIS WORK WHEN this.currentSquare IS undefined?
  this.currentSquare = true;
  this.destinationSquare = undefined;
  this.team = undefined;
  this.selectedPiece = undefined;
  this.possibleSquareOne = false;
  this.possibleSquareTwo = false;
  this.turn = 'red';
};

function Square(row, column, playable) {
  this.row = row;
  this.column = column;
  this.playable = playable;
  this.occupied = false;
  this.destination = false;
  this.isCurrentSquare = false;
};

function Piece(team, idNum, row, column) {
  this.team = team;
  this.id = idNum;
  this.row = row;
  this.column = column;
  this.king = false;
};

// This function updates the squares in the board array with destination values
// when a .man is clicked
Piece.prototype.availableMoves = function() {
  // Determine direction the man is moving (team, basically)
  // Determine 'king' value
  // Determine if possible destinations are occupied BY AN ENEMY MAN

  if (game.selectedPiece.column === 0) {
    // only look for one possible destination
    game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
  } else if (game.selectedPiece.column === 7) {
    // only look for one possible destination
    game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
  } else {
    game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
    game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
  };

  // NEED TO FIND IF THE SECOND DESTINATION IS ALSO ON THE BOARD
  if (game.possibleSquareOne.occupied === true) {
    // Check if the possible square is occupied by a piece of the same team
    // This needs to check the Piece{} that is in the possibleSquare, not the
    // team value of the possibleSquare, because that doesn't exist...
    if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
      console.log('No move necessary, the team is the same.');
      game.possibleSquareOne.destination = false;
    } else {
      game.possibleSquareOne = game.board[this.row + 2][this.column - 2];
    }
  };

  if (game.possibleSquareTwo.occupied === true) {
    // Check if the possible square is occupied by a piece of the same team
    if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
      console.log('No move necessary, the team is the same.');
      game.possibleSquareTwo.destination = false;
    } else {
      game.possibleSquareTwo = game.board[this.row + 2][this.column + 2];
      game.possibleSquareTwo = true;
    }
  }

  game.possibleSquareOne.destination = true;
  game.possibleSquareTwo.destination = true;
  game.currentSquare.isCurrentSquare = true;
};

// This function moves the selected man from its current square into the
// destination square
Piece.prototype.moveMan = function() {
  // Changing coordinates of the man
  this.row = game.destinationSquare.row;
  this.column = game.destinationSquare.column;

  // Capturing relevant pieces

  // Unoccupy previous square
  game.currentSquare.occupied = false;

  // Occupy destination square
  game.destinationSquare.occupied = true;

  // Check for possible chained moves

  // Clear destinations and current square
  // MAYBE MAKE THIS INTO ITS OWN FUNCTION, OTHER PLACES COULD USE IT
  game.possibleSquareOne.destination = false;
  game.possibleSquareTwo.destination = false;
  game.currentSquare.isCurrentSquare = false;

  // Update relevant values:
  // Last square > unoccupied
  // New square > occupied
  // Captured piece > out of play
  // Kinged man > kinged
};

// A simple looping function that puts eight arrays, representing rows, into
// the board array
function fillBoard() {
  for (var i = 0; i < 8; i++) {
    game.board[i] = fillRow(i);
  };
};

// This function is called by fillBoard() in order to fill each row that is
// created while filling the board array
function fillRow(rowNumber) {
  var row = [];
  // If the row is odd, reverse the black/white(playable/not) scheme
  if (isOdd(rowNumber)) {
    // Creates 8 squares in the row array, following the correct scheme of
    // playable/unplayable squares
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, false);
      } else {
        row[i] = new Square(rowNumber, i, true);
      }
    }
    // If the row is even, the normal scheme of black/white squares is followed
  } else {
    // Creates eight squares, following the correct scheme
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, true);
      } else {
        row[i] = new Square(rowNumber, i, false);
      }
    }
  }
  // Returns the row back to the loop in the fillBoard() function, which puts
  // this new row into its place in the board array
  return row;
};

// A simple function that returns true when a given number is odd, and false
// if it is not
function isOdd(num) {
  return (num % 2) == 1;
};

function drawBoard() {
  // Creates the div for the board to be drawn in
  $('body').empty();
  $('body').prepend('

');
  // Creates divs for each row array in the board array
  for (i = 0; i < game.board.length; i++) {
    $('#board').append('

');
    // Creates divs for each square object in the board array
    for (n = 0; n < game.board[i].length; n++) {
      // Checks if the square is a playable square and adds a class if it is
      if (game.board[i][n].playable) {
        $('#row' + i).append(
            '

'
            );
        if (game.board[i][n].destination) {
          $('#' + i + n).addClass('destination');
        };
        if (game.board[i][n].isCurrentSquare) {
          $('#' + i + n).addClass('currentSquare');
        };
      } else {
        $('#row' + i).append(
            '

'
            );
      };
    };
  };
};

// This will create all the pieces for both teams
// Currently it just creates one piece and gives it the desires values
// MAKE THIS MORE SUCCINCT
function createPieces(team) {
  var row = 0;
  var column = 1;
  // Creates 12 pieces for the team
  if (team === 'red') {
    for (i = 0; i < 12; i++) {
      game.redTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.redTeam[i*4].row = i;
      game.redTeam[i*4 + 1].row = i;
      game.redTeam[i*4 + 2].row = i;
      game.redTeam[i*4 + 3].row = i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.redTeam[i].row)) {
        game.redTeam[i].column = n;
      } else {
        game.redTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  } else if (team === 'white') {
    for (i = 0; i < 12; i++) {
      game.whiteTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.whiteTeam[i*4].row = 7 - i;
      game.whiteTeam[i*4 + 1].row = 7 - i;
      game.whiteTeam[i*4 + 2].row = 7 - i;
      game.whiteTeam[i*4 + 3].row = 7 - i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.whiteTeam[i].row)) {
        game.whiteTeam[i].column = n;
      } else {
        game.whiteTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  }
};

// This clears all the pieces off the board and then redraws the pieces in
// their current positions.
function drawPieces() {
  $('.man').remove();
  for (i = 0; i < game.redTeam.length; i++) {
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupied = true;
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupiedBy =
      game.redTeam[i];
    $('#' + game.redTeam[i].row + game.redTeam[i].column).append(
        '

');
  };
  for (i = 0; i < game.whiteTeam.length; i++) {
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupied = true;
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupiedBy =
      game.whiteTeam[i];
    $('#' + game.whiteTeam[i].row + game.whiteTeam[i].column).append(
        '

');
  };
};

function getPiece(event, team) {
  if (team === 'red') {
    return game.redTeam[event.target.id];
  } else if (team === 'white') {
    return game.whiteTeam[event.target.id];
  };
};

function getSquare(thisSquare) {
  var row = thisSquare.charAt(0);
  var column = thisSquare.charAt(1);

  return game.board[row][column];
};

var game = new Checkers();

$(document).ready(function() {
  fillBoard();
  drawBoard();
  createPieces('red');
  createPieces('white');
  drawPieces();
  $('body').on('click', '.man', function(event) {
    // Grab the ID of the piece clicked
    // Make sure the piece matches the player moving
    // Check for available moves
    // Highlight open squares
    // Move piece selected to square clicked
    // Remove captured men
    // Check for additional moves

    // This prevents more than one .man from being selected
    if ($('.currentSquare').length === 1) {
      return;
    }

    // Gets the Piece{} that corresponds with the .man element that has been
    // clicked by the player
    game.team = $(this).attr('class').split(' ')[0];
    game.selectedPiece = getPiece(event, game.team);

    // Gets the Square{} that corresponds with the .playable element that has
    // been clicked by the player
    // MAYBE JUST GET THE COORDINATES OF THE SELECTED PIECE? IDK
    game.currentSquare = getSquare($(this).closest('.playable').attr('id'));

    game.selectedPiece.availableMoves();

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.currentSquare', function(event) {
    game.currentSquare.isCurrentSquare = false;

    game.possibleSquareOne.destination = false;
    game.possibleSquareTwo.destination = false;

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.destination', function(event) {
    game.destinationSquare = getSquare(event.currentTarget.id);

    game.selectedPiece.moveMan();

    drawBoard();
    drawPieces();
  });
});

// To Do:
// Comment more of the code
//
// Remove redundant variables/trackers
//
// Polish Piece.availableMoves
// - needs to work for both teams
// - needs to not give errors when one possible destination isn't a real square
//
// Create Pieces function is too clunky and won't work well once it has to do
// two teams
//
// When a .man is clicked, game.currentSquare is set, but when a .man is clicked
// again, it is set to the new one WITHOUT resetting the old... fix that
// - I *think* this is prevented now... we'll see
//
// Make the .destination 'x' look nicer... probably with CSS, not JS, but I
// don't have a to do list in the CSS
<commit_msg>Pieces now check for teammates of jumped piece<commit_after>function Checkers() {
  this.board = [];
  this.redTeam = [];
  this.whiteTeam = [];
  // WHY DOESN'T THIS WORK WHEN this.currentSquare IS undefined?
  this.currentSquare = true;
  this.destinationSquare = undefined;
  this.team = undefined;
  this.selectedPiece = undefined;
  this.possibleSquareOne = false;
  this.possibleSquareTwo = false;
  this.turn = 'red';
};

function Square(row, column, playable) {
  this.row = row;
  this.column = column;
  this.playable = playable;
  this.occupied = false;
  this.destination = false;
  this.isCurrentSquare = false;
};

function Piece(team, idNum, row, column) {
  this.team = team;
  this.id = idNum;
  this.row = row;
  this.column = column;
  this.king = false;
};

// This function updates the squares in the board array with destination values
// when a .man is clicked
Piece.prototype.availableMoves = function() {
  // Determine direction the man is moving (team, basically)
  // Determine 'king' value
  // Determine if possible destinations are occupied BY AN ENEMY MAN

  if (game.selectedPiece.column === 0) {
    // only look for one possible destination
    game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
  } else if (game.selectedPiece.column === 7) {
    // only look for one possible destination
    game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
  } else {
    game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
    game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
  };

  // NEED TO FIND IF THE SECOND DESTINATION IS ALSO ON THE BOARD
  if (game.possibleSquareOne.occupied === true) {
    // Check if the possible square is occupied by a piece of the same team
    // This needs to check the Piece{} that is in the possibleSquare, not the
    // team value of the possibleSquare, because that doesn't exist...
    if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
      game.possibleSquareOne.destination = false;
    } else {
      game.possibleSquareOne = game.board[this.row + 2][this.column - 2];
      game.possibleSquareOne.destination = true;
      game.currentSquare.isCurrentSquare = true;
    }
  } else {
    game.possibleSquareOne.destination = true;
    game.currentSquare.isCurrentSquare = true;
  };

  if (game.possibleSquareTwo.occupied === true) {
    // Check if the possible square is occupied by a piece of the same team
    if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
      game.possibleSquareTwo.destination = false;
    } else {
      game.possibleSquareTwo = game.board[this.row + 2][this.column + 2];
      game.possibleSquareTwo.destination = true;
      game.currentSquare.isCurrentSquare = true;
    }
  } else {
    game.possibleSquareTwo.destination = true;
    game.currentSquare.isCurrentSquare = true;
  };
};

// This function moves the selected man from its current square into the
// destination square
Piece.prototype.moveMan = function() {
  // Changing coordinates of the man
  this.row = game.destinationSquare.row;
  this.column = game.destinationSquare.column;

  // Capturing relevant pieces

  // Unoccupy previous square
  game.currentSquare.occupied = false;

  // Occupy destination square
  game.destinationSquare.occupied = true;

  // Check for possible chained moves

  // Clear destinations and current square
  // MAYBE MAKE THIS INTO ITS OWN FUNCTION, OTHER PLACES COULD USE IT
  game.possibleSquareOne.destination = false;
  game.possibleSquareTwo.destination = false;
  game.currentSquare.isCurrentSquare = false;

  // Update relevant values:
  // Last square > unoccupied
  // New square > occupied
  // Captured piece > out of play
  // Kinged man > kinged
};

// A simple looping function that puts eight arrays, representing rows, into
// the board array
function fillBoard() {
  for (var i = 0; i < 8; i++) {
    game.board[i] = fillRow(i);
  };
};

// This function is called by fillBoard() in order to fill each row that is
// created while filling the board array
function fillRow(rowNumber) {
  var row = [];
  // If the row is odd, reverse the black/white(playable/not) scheme
  if (isOdd(rowNumber)) {
    // Creates 8 squares in the row array, following the correct scheme of
    // playable/unplayable squares
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, false);
      } else {
        row[i] = new Square(rowNumber, i, true);
      }
    }
    // If the row is even, the normal scheme of black/white squares is followed
  } else {
    // Creates eight squares, following the correct scheme
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, true);
      } else {
        row[i] = new Square(rowNumber, i, false);
      }
    }
  }
  // Returns the row back to the loop in the fillBoard() function, which puts
  // this new row into its place in the board array
  return row;
};

// A simple function that returns true when a given number is odd, and false
// if it is not
function isOdd(num) {
  return (num % 2) == 1;
};

function drawBoard() {
  // Creates the div for the board to be drawn in
  $('body').empty();
  $('body').prepend('

');
  // Creates divs for each row array in the board array
  for (i = 0; i < game.board.length; i++) {
    $('#board').append('

');
    // Creates divs for each square object in the board array
    for (n = 0; n < game.board[i].length; n++) {
      // Checks if the square is a playable square and adds a class if it is
      if (game.board[i][n].playable) {
        $('#row' + i).append(
            '

'
            );
        if (game.board[i][n].destination) {
          $('#' + i + n).addClass('destination');
        };
        if (game.board[i][n].isCurrentSquare) {
          $('#' + i + n).addClass('currentSquare');
        };
      } else {
        $('#row' + i).append(
            '

'
            );
      };
    };
  };
};

// This will create all the pieces for both teams
// Currently it just creates one piece and gives it the desires values
// MAKE THIS MORE SUCCINCT
function createPieces(team) {
  var row = 0;
  var column = 1;
  // Creates 12 pieces for the team
  if (team === 'red') {
    for (i = 0; i < 12; i++) {
      game.redTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.redTeam[i*4].row = i;
      game.redTeam[i*4 + 1].row = i;
      game.redTeam[i*4 + 2].row = i;
      game.redTeam[i*4 + 3].row = i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.redTeam[i].row)) {
        game.redTeam[i].column = n;
      } else {
        game.redTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  } else if (team === 'white') {
    for (i = 0; i < 12; i++) {
      game.whiteTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.whiteTeam[i*4].row = 7 - i;
      game.whiteTeam[i*4 + 1].row = 7 - i;
      game.whiteTeam[i*4 + 2].row = 7 - i;
      game.whiteTeam[i*4 + 3].row = 7 - i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.whiteTeam[i].row)) {
        game.whiteTeam[i].column = n;
      } else {
        game.whiteTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  }
};

// This clears all the pieces off the board and then redraws the pieces in
// their current positions.
function drawPieces() {
  $('.man').remove();
  for (i = 0; i < game.redTeam.length; i++) {
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupied = true;
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupiedBy =
      game.redTeam[i];
    $('#' + game.redTeam[i].row + game.redTeam[i].column).append(
        '

');
  };
  for (i = 0; i < game.whiteTeam.length; i++) {
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupied = true;
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupiedBy =
      game.whiteTeam[i];
    $('#' + game.whiteTeam[i].row + game.whiteTeam[i].column).append(
        '

');
  };
};

function getPiece(event, team) {
  if (team === 'red') {
    return game.redTeam[event.target.id];
  } else if (team === 'white') {
    return game.whiteTeam[event.target.id];
  };
};

function getSquare(thisSquare) {
  var row = thisSquare.charAt(0);
  var column = thisSquare.charAt(1);

  return game.board[row][column];
};

var game = new Checkers();

$(document).ready(function() {
  fillBoard();
  drawBoard();
  createPieces('red');
  createPieces('white');
  drawPieces();
  $('body').on('click', '.man', function(event) {
    // Grab the ID of the piece clicked
    // Make sure the piece matches the player moving
    // Check for available moves
    // Highlight open squares
    // Move piece selected to square clicked
    // Remove captured men
    // Check for additional moves

    // This prevents more than one .man from being selected
    if ($('.currentSquare').length === 1) {
      return;
    }

    // Gets the Piece{} that corresponds with the .man element that has been
    // clicked by the player
    game.team = $(this).attr('class').split(' ')[0];
    game.selectedPiece = getPiece(event, game.team);

    // Gets the Square{} that corresponds with the .playable element that has
    // been clicked by the player
    // MAYBE JUST GET THE COORDINATES OF THE SELECTED PIECE? IDK
    game.currentSquare = getSquare($(this).closest('.playable').attr('id'));

    game.selectedPiece.availableMoves();

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.currentSquare', function(event) {
    game.currentSquare.isCurrentSquare = false;

    game.possibleSquareOne.destination = false;
    game.possibleSquareTwo.destination = false;

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.destination', function(event) {
    game.destinationSquare = getSquare(event.currentTarget.id);

    game.selectedPiece.moveMan();

    drawBoard();
    drawPieces();
  });
});

// To Do:
// Comment more of the code
//
// Remove redundant variables/trackers
//
// Polish Piece.availableMoves
// - needs to work for both teams
// - needs to not give errors when one possible destination isn't a real square
//
// Create Pieces function is too clunky and won't work well once it has to do
// two teams
//
// When a .man is clicked, game.currentSquare is set, but when a .man is clicked
// again, it is set to the new one WITHOUT resetting the old... fix that
// - I *think* this is prevented now... we'll see
//
// Make the .destination 'x' look nicer... probably with CSS, not JS, but I
// don't have a to do list in the CSS
<|endoftext|>


<commit_before>(function($, _, Transparency) {

  // Constants
  var VIDEO_ID = 'zKdwTgrow3E',
      EMBED = '',
      SECRET = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];

  // Utilities
  var getIdx = _.curry(function(idx, arr) {return arr[idx];});

  // Globals
  var kkeys = [];

  // Make transparency only match data-bind and data-cmd
  Transparency.matcher = function(element, key) {
    return (element.el.getAttribute('data-bind') === key ||
            element.el.getAttribute('data-cmd') === key);
  };

  function errRedirect(jqXHR, msg, err) {
    console.log(msg, err);
    if (document.location.hostname !== "localhost")
      window.location.replace('error.html?msg='+msg+'&err='+err);
  }

  function hideIfNot(p) {
    var req = p.element.dataset.values;
    if (!req)
      return;

    req = req.split(' ');
    var reduction = function(a, b) {return a && !b;};

    if (_(req).reduce(reduction, true))
      return 'display: none';
  }

  function webLink(p) {
    // Get dest obj from data binding
    var dest = p.element.dataset.bind;
    if (!dest || !this[dest])
      return;
    var url = this[dest];

    // Add protocol if not already at start
    if (url.indexOf('http://'))
      url = 'http://' + url;
    return url;
  }

  function namedWebLink() {
    // Requires url to be in values scope
    var url = this.url;
    if (!url)
      return;

    // Add protocol if not already at start
    if (url.indexOf('http://'))
      url = 'http://' + url;
    return url;
  }

  function commaize(str, index, arr) {
    return str + ((index !== arr.length) - 1 ? ',' : '');
  }

  $(function() {
    // Fade in after ajax
    $('body').hide();

    $.when(
      $.getJSON('data/data.json', function(data) {
        $('html').render(data, {
          'hide-if-not': {
            text: function() {
              return '';
            },
            style: hideIfNot
          },
          fullname: {
            text: function() {
              return (this.first || '') + (this.first && this.last ? ' ' : '') + (this.last || '');
            }
          },
          phone: {
            href: function() {
              if (this.phone)
                return 'tel:' + this.phone.replace(/\s+/g, '');
            }
          },
          email: {
            href: function() {
              if (this.email)
                return 'mailto:' + this.email;
            }
          },
          location: {
            href: function() {
              if (this.location)
                return 'https://www.google.com/maps/place/' + this.location.replace(/\s+/g, '+');
            }
          },
          link: {
            href: webLink
          },
          experience: {
            name: {
              href: namedWebLink
            },
            content: {
              value: {
                text: function() {
                  return this.value;
                }
              }
            }
          },
          skills: {
            icon: {
              text: function() {
                return '';
              },
              class: function(p) {
                return p.element.className + ' ' + (this.icon || 'fa-code');
              }
            },
            name: {
              text: function(p) {
                if (this.name && data.skills)
                  return commaize(this.name, p.index, data.skills);
              }
            }
          },
          projects: {
            content: {
              value: {
                text: function() {
                  return this.value;
                }
              }
            }
          },
          organizations: {
            namedate: {
              text: function(p) {
                if (this.name && this.date && data.organizations)
                  return commaize(this.name + ' (' + this.date + ')', p.index, data.organizations);
              }
            }
          }
        });
      }).fail(errRedirect),

      $.getJSON('data/credits.json', function(data) {
        $('#credits-list').render(data, {
          entry: {
            text: function(p) {
              if (this.name && data)
                return commaize(this.name, p.index, data);
            },
            href: namedWebLink
          }
        });
      }).fail(errRedirect)
    ).

    then(function() {
      var reduction = function(a, b) {return a && (b === 'success');};

      if (_(arguments).map(getIdx(1)).reduce(reduction, true))
        $('body').fadeIn('slow');
    });

    // shhhh
    $(document).keydown(function(e) {
      kkeys.push(e.keyCode);
      if (kkeys.length > SECRET.length)
        kkeys.shift();
      if (_.isEqual(kkeys, SECRET)) {
        $(document).unbind('keydown', arguments.callee);
        $('body').append(EMBED);
      }
    });
  });

})(window.jQuery, window._, window.Transparency);<commit_msg>Added JS responsive framework<commit_after>(function($, _, Transparency) {

  "use strict";

  // Constants
  var XS = 0,
      SM = 768,
      MD = 992,
      LG = 1200,
      VIDEO_ID = 'zKdwTgrow3E',
      EMBED = '',
      SECRET = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];

  // Globals
  var kkeys = [];

  // Utilities
  var pLog = _.curry(function(qty, text, args) {
    console.log.apply(console, [text + ': '].concat(Array.prototype.slice.call(arguments, 2, qty + 2)));
  });
  var getIdx = _.curry(function(idx, arr) {return arr[idx];});

  function commaize(str, index, arr) {
    return str + ((index !== arr.length) - 1 ? ',' : '');
  }

  // Takes object with width:func(curWidth)
  function onWidths(obj) {
    // Initialize 0 if not already there
    if (!obj[0])
      obj[0] = function(){};

    var base = function() {
      var $width = $(window).width();
      var reduction = function(a, v, k) {return $width > k ? k : a}
      obj[_.reduce(obj, reduction, 0)]($width);
    };

    $(base);
    $(window).resize(base);
  };

  function errRedirect(jqXHR, msg, err) {
    console.log(msg, err);
    if (document.location.hostname !== "localhost")
      window.location.replace('error.html?msg='+msg+'&err='+err);
  }

  // Make transparency only match data-bind and data-cmd
  Transparency.matcher = function(element, key) {
    return (element.el.getAttribute('data-bind') === key ||
            element.el.getAttribute('data-cmd') === key);
  };

  function hideIfNot(p) {
    var req = p.element.dataset.values;
    if (!req)
      return;

    req = req.split(' ');
    var reduction = function(a, b) {return a && !b;};

    if (_(req).reduce(reduction, true))
      return 'display: none';
  }

  function webLink(p) {
    // Get dest obj from data binding
    var dest = p.element.dataset.bind;
    if (!dest || !this[dest])
      return;
    var url = this[dest];

    // Add protocol if not already at start
    if (url.indexOf('http://'))
      url = 'http://' + url;
    return url;
  }

  function namedWebLink() {
    // Requires url to be in values scope
    var url = this.url;
    if (!url)
      return;

    // Add protocol if not already at start
    if (url.indexOf('http://'))
      url = 'http://' + url;
    return url;
  }

  $(function() {
    // Fade in after ajax
    $('body').hide();

    // Ajax calls
    $.when(
      $.getJSON('data/data.json', function(data) {
        $('html').render(data, {
          'hide-if-not': {
            text: function() {
              return '';
            },
            style: hideIfNot
          },
          fullname: {
            text: function() {
              return (this.first || '') + (this.first && this.last ? ' ' : '') + (this.last || '');
            }
          },
          phone: {
            href: function() {
              if (this.phone)
                return 'tel:' + this.phone.replace(/\s+/g, '');
            }
          },
          email: {
            href: function() {
              if (this.email)
                return 'mailto:' + this.email;
            }
          },
          location: {
            href: function() {
              if (this.location)
                return 'https://www.google.com/maps/place/' + this.location.replace(/\s+/g, '+');
            }
          },
          link: {
            href: webLink
          },
          experience: {
            name: {
              href: namedWebLink
            },
            content: {
              value: {
                text: function() {
                  return this.value;
                }
              }
            }
          },
          skills: {
            icon: {
              text: function() {
                return '';
              },
              class: function(p) {
                return p.element.className + ' ' + (this.icon || 'fa-code');
              }
            },
            name: {
              text: function(p) {
                if (this.name && data.skills)
                  return commaize(this.name, p.index, data.skills);
              }
            }
          },
          projects: {
            content: {
              value: {
                text: function() {
                  return this.value;
                }
              }
            }
          },
          organizations: {
            namedate: {
              text: function(p) {
                if (this.name && this.date && data.organizations)
                  return commaize(this.name + ' (' + this.date + ')', p.index, data.organizations);
              }
            }
          }
        });
      }).fail(errRedirect),

      $.getJSON('data/credits.json', function(data) {
        $('#credits-list').render(data, {
          entry: {
            text: function(p) {
              if (this.name && data)
                return commaize(this.name, p.index, data);
            },
            href: namedWebLink
          }
        });
      }).fail(errRedirect)
    ).

    then(function() {
      var reduction = function(a, b) {return a && (b === 'success');};

      if (_(arguments).map(getIdx(1)).reduce(reduction, true))
        $('body').fadeIn('slow');
    });

    // Other listeners
    var widths = {};
    var pLog1 = pLog(1);
    widths[XS] = pLog1('XS');
    widths[SM] = pLog1('SM');
    widths[MD] = pLog1('MD');
    widths[LG] = pLog1('LG');
    onWidths(widths);

    // shhhh
    $(document).keydown(function(e) {
      kkeys.push(e.keyCode);
      if (kkeys.length > SECRET.length)
        kkeys.shift();
      if (_.isEqual(kkeys, SECRET)) {
        $(document).unbind('keydown', arguments.callee);
        $('body').append(EMBED);
      }
    });
  });

})(window.jQuery, window._, window.Transparency);<|endoftext|>


<commit_before>$(document).ready(function() {
    $("#btn1").click(calcPrime);

    function calcPrime() {
        var n, i, j, k, ms1, ms2, lookBack, lastPrime;
        var notPrime = {
            0: false,
            1: false
        };

        n = $("#input1").val();
        lookBack = 100000;
        $('#results').empty();
        $('#time').empty();

        $("#time").append("Twin Primes between " + (n - lookBack) + " and " + n + "
");

        var date = new Date();
        ms1 = date.getTime();

        k = (n % 2 == 0) ? (n - lookBack) : (n - lookBack - 1);
        k = (k < 4) ? 4 : k;

        for (i = k; i <= n; i += 2)
            notPrime[i] = false;

        for (i = 3; i <= Math.sqrt(n); i += 2) {
            k = Math.floor((n - lookBack) / i);
            k = (k < 3) ? 3 : k;
            if (i > 8) {
                if (i % 3 != 0 && i % 5 != 0 && i % 7 != 0) {
                    for (j = i * k; j <= n; j += i)
                        notPrime[j] = false;
                }
            } else {
                for (j = i * k; j <= n; j += i)
                    notPrime[j] = false;
            }
        }

        lastPrime = -1;
        for (i = n - lookBack; i <= n; i++) {
            if (!(i in notPrime)) {
                if (i - lastPrime == 2) {
                    $("#results").append(lastPrime + ", " + i + "
");
                }
                lastPrime = i;
            }
        }

        date = new Date();
        ms2 = date.getTime();

        $("#time").append("elapsed=" + (ms2 - ms1) + "ms
");
    }
});
<commit_msg>changed object name<commit_after>$(document).ready(function() {
    $("#btn1").click(calcPrime);

    function calcPrime() {
        var n, i, j, k, ms1, ms2, lookBack, lastPrime;
        var isPrime = {
            0: false,
            1: false
        };

        n = $("#input1").val();
        lookBack = 100000;
        $('#results').empty();
        $('#time').empty();

        $("#time").append("Twin Primes between " + (n - lookBack) + " and " + n + "
");

        var date = new Date();
        ms1 = date.getTime();

        k = (n % 2 == 0) ? (n - lookBack) : (n - lookBack - 1);
        k = (k < 4) ? 4 : k;

        for (i = k; i <= n; i += 2)
            isPrime[i] = false;

        for (i = 3; i <= Math.sqrt(n); i += 2) {
            k = Math.floor((n - lookBack) / i);
            k = (k < 3) ? 3 : k;
            if (i > 8) {
                if (i % 3 != 0 && i % 5 != 0 && i % 7 != 0) {
                    for (j = i * k; j <= n; j += i)
                        isPrime[j] = false;
                }
            } else {
                for (j = i * k; j <= n; j += i)
                    isPrime[j] = false;
            }
        }

        lastPrime = -1;
        for (i = n - lookBack; i <= n; i++) {
            if (!(i in isPrime)) {
                if (i - lastPrime == 2) {
                    $("#results").append(lastPrime + ", " + i + "
");
                }
                lastPrime = i;
            }
        }

        date = new Date();
        ms2 = date.getTime();

        $("#time").append("elapsed=" + (ms2 - ms1) + "ms
");
    }
});
<|endoftext|>