<commit_before>// this is set get and set local storage to prevent the intro from playing everytime the lightbox gets closed
// can remove the local storage cookie in dev console ;)

function intro(){
    let ls = window.localStorage;
    if(ls.getItem('intro') === 'undefined' || ls.getItem('intro') === null)
    {
        ls.setItem('intro', true);
    } // I think i need to add a for loop here to loop through all objects and append class name
    if(ls.getItem('intro') === 'true'){
        document.getElementsByClassName('imageItem').className += 'intro';
        document.getElementsByClassName('gallery').className += 'intro2';
    } else if(ls.getItem('intro') === 'false'){
        document.getElementsByClassName('imageItem').remove('intro');
        document.getElementsByClassName('gallery').remove('intro2');
    } else {
        // future usage
    }
}
intro();
/**
 * Created by Warren Leyes on 2017-07-25.
 */

function searchAndDetroy() {
let images, input, imageItem, i;
    images = document.getElementsByClassName('image');
    input = document.getElementById('search');
    imageItem = document.querySelectorAll('.imageItem');

    input.onkeyup = function () {
        for(i=0; i < images.length; i++){
            if (images[i].getAttribute('title').toUpperCase().indexOf(input.value.toUpperCase()) <= -1) {
                //hide images that don't contain keyword from input
                document.getElementsByClassName('imageItem')[i].style.display = 'none';
            } else {
                document.getElementsByClassName('imageItem')[i].style.display = 'block';
                window.localStorage.setItem('intro', 'true');
            }
            // Clear input after the image has been clicked
            // let result = document.getElementsByClassName('imageItem')[i];
                input.onblur = function () {
                    $('.image').on('click', function(event) {
                        event.preventDefault();
                        this.value = '';
                        for (i = 0; i < images.length; i++) {
                            imageItem[i].style.display = 'block';
                        } // end for()
                    })// end click
                }; // end onblur()
        }// end for
    };
}// EOF
searchAndDetroy();

/**
 * Created by Warren Leyes on 2017-07-25.
 */

$(document).ready(function() {

        $(this).find('.imageTitle').hide();
        $(this).find('.imageText').hide();
        $('.imageItem').hover( function() {
            $(this).find('.imageTitle').slideDown(400);
            $(this).find('.imageText').slideDown(400);
        }, function() {
            $(this).find('.imageTitle').slideUp(400);
            $(this).find('.imageText').slideUp(400);
        });
}); // EOF

/**
* Created by Warren Leyes on 2017-07-25.
*/

let $imageIndex, images, imageItem,$imageObject, lightbox;
images = document.getElementsByClassName('image');
imageItem = document.querySelectorAll('.imageItem');

$('.gallery').addClass('intro2');   // todo: add to onclick()
$('.imageItem').addClass('intro');  // todo: add to onclick()
// todo: add logic to change Local Storage to false to remove/disable intro classes (move and tweak from intro.js)

$('.imageItem').on('click', '.image', function(event)  {
    document.getElementById('search').value = '';
    event.preventDefault();
    $imageIndex = $(this).attr('src');
    $imageObject = $(this);

    // ?? tring to workout current next() and previous logic
    for(i=0; i < $('.imageItem').length; i++){
        console.log($('.imageItem')[i]);
        // if current logic matches something then next() $imageIndex = ++ logic, ele previous() $imageIndex == -- logic
        if(''){

        }
    }
    // console.log($('.imageItem').index($imageObject[i]));

    overlayElements();
    open();
    exit();
    next();
    previous();
}); // end imageItem click

function open() {
    $('body').append(lightbox.background);
    lightbox.overlay
        .append(lightbox.exit)
        .append(lightbox.title)
        .append(lightbox.image)
        .append(lightbox.next)
        .append(lightbox.previous)
        .append(lightbox.caption);
    $('body').append(lightbox.overlay);
    $('.gallery').hide();
    $('.overlayBackground').css({'background-image': 'url('+ imagePath($imageIndex) +')'});
    lightbox.image.attr('src', imagePath($imageIndex));
    lightbox.title.text($imageObject[0].previousElementSibling.innerHTML);
    lightbox.caption.text($imageObject[0].nextElementSibling.innerHTML);
    // console.log($imageObject); // todo: remove
}; // end open()

function overlayElements() {
    lightbox = {
        overlay:    $('

'),
        background: $('

'),
        previous:   $('<button id="previousButton" class="fas fa-arrow-alt-circle-left"></button>'),
        next:       $('<button id="nextButton" class="fas fa-arrow-alt-circle-right"></button>'),
        exit:       $('<button id="closeButton" class="fas fa-times"></button>'),
        image:      $(''),
        title:      $('

'),
        caption:    $('

')
    };
}; // end overlayElements()

function exit() {
    $('.overlay-container').on('click', '#closeButton', function()  {
        lightbox.background.remove();
        lightbox.overlay.empty().remove();
        $('.gallery').show();
    });// end #closeButton click
}; // end exit()

function next() {
    $('.overlay-container').on('click', '#nextButton', function()  {
        alert('next');
    });// end #nextButton click
}; // end next()

function previous() {
    $('.overlay-container').on('click', '#previousButton', function()  {
        alert('previous');
    });// end #previousButton click
}; //end previous()

function imagePath(path) {
    // string replace image path
    let imagePath = 'img/thumbnails/';
    let newImagePath = 'img/';
    path =  $imageIndex;
    return path.replace(imagePath, newImagePath);
} //end imagePath()

<commit_msg>just a quick save push. Still trying to figure out indx, next and previous logic<commit_after>// this is set get and set local storage to prevent the intro from playing everytime the lightbox gets closed
// can remove the local storage cookie in dev console ;)

function intro(){
    let ls = window.localStorage;
    if(ls.getItem('intro') === 'undefined' || ls.getItem('intro') === null)
    {
        ls.setItem('intro', true);
    } // I think i need to add a for loop here to loop through all objects and append class name
    if(ls.getItem('intro') === 'true'){
        document.getElementsByClassName('imageItem').className += 'intro';
        document.getElementsByClassName('gallery').className += 'intro2';
    } else if(ls.getItem('intro') === 'false'){
        document.getElementsByClassName('imageItem').remove('intro');
        document.getElementsByClassName('gallery').remove('intro2');
    } else {
        // future usage
    }
}
intro();
/**
 * Created by Warren Leyes on 2017-07-25.
 */

function searchAndDetroy() {
let images, input, imageItem, i;
    images = document.getElementsByClassName('image');
    input = document.getElementById('search');
    imageItem = document.querySelectorAll('.imageItem');

    input.onkeyup = function () {
        for(i=0; i < images.length; i++){
            if (images[i].getAttribute('title').toUpperCase().indexOf(input.value.toUpperCase()) <= -1) {
                //hide images that don't contain keyword from input
                document.getElementsByClassName('imageItem')[i].style.display = 'none';
            } else {
                document.getElementsByClassName('imageItem')[i].style.display = 'block';
                window.localStorage.setItem('intro', 'true');
            }
            // Clear input after the image has been clicked
            // let result = document.getElementsByClassName('imageItem')[i];
                input.onblur = function () {
                    $('.image').on('click', function(event) {
                        event.preventDefault();
                        this.value = '';
                        for (i = 0; i < images.length; i++) {
                            imageItem[i].style.display = 'block';
                        } // end for()
                    })// end click
                }; // end onblur()
        }// end for
    };
}// EOF
searchAndDetroy();

/**
 * Created by Warren Leyes on 2017-07-25.
 */

$(document).ready(function() {

        $(this).find('.imageTitle').hide();
        $(this).find('.imageText').hide();
        $('.imageItem').hover( function() {
            $(this).find('.imageTitle').slideDown(400);
            $(this).find('.imageText').slideDown(400);
        }, function() {
            $(this).find('.imageTitle').slideUp(400);
            $(this).find('.imageText').slideUp(400);
        });
}); // EOF

/**
* Created by Warren Leyes on 2017-07-25.
*/

let $imageIndex, images, imageItem,$imageObject, indexValue,nextIndexValue,previousIndexValue,current, lightbox;
images = document.getElementsByClassName('image');  // <image tags>
imageItem = document.querySelectorAll('.imageItem');// the wraping

$('.gallery').addClass('intro2');   // todo: add to onclick()
$(imageItem).addClass('intro');  // todo: add to onclick()
// todo: add logic to change Local Storage to false to remove/disable intro classes (move and tweak from intro.js)

$('.imageItem').on('click', '.image', function(event)  {
    document.getElementById('search').value = '';
    event.preventDefault();
    current = $(this);
    indexValue = $('.image').index(this);// set image index to clicked value

    console.log('Current Index: ' + indexValue);
    console.log(images); // NodeList of images
    console.log(images[indexValue]);    // returns the img tag of clicked
    console.log(imageItem[indexValue]); // returns obj <figure of clicked

    console.log('Path: '+ imagePath(images[indexValue].src));

    overlayElements();
    open();
    exit();
    next(indexValue);
    previous(indexValue);
}); // end imageItem click

function open() {

    indexValue = $($imageIndex).parent().index();// might remove
    nextIndexValue = indexValue + 1;
    previousIndexValue = indexValue - 1;

    if (indexValue === $(imageItem).length -1){ nextIndexValue = 0; };
    if(indexValue === 0){ previousIndexValue = $(imageItem).length -1; }

    for(i=0; i < $(imageItem).length; i++){
        // console.log($(imageItem)[i].innerHTML)
        if(i === indexValue){

            lightbox.background.css({'background-image': 'url('+ imagePath(current[indexValue].src) +')'});

            lightbox.image.attr('src', imagePath(indexValue));
        }
    }

    $('.gallery').hide();
    lightbox.overlay
        .append(lightbox.exit)
        .append(lightbox.title)
        .append(lightbox.image)
        .append(lightbox.next)
        .append(lightbox.previous)
        .append(lightbox.caption);
    $('body').append(lightbox.overlay);
    $('body').append(lightbox.background);
}; // end open()

function overlayElements() {
    lightbox = {
        overlay:    $('

'),
        background: $('

'),
        previous:   $('<button id="previousButton" class="fas fa-arrow-alt-circle-left"></button>'),
        next:       $('<button id="nextButton" class="fas fa-arrow-alt-circle-right"></button>'),
        exit:       $('<button id="closeButton" class="fas fa-times"></button>'),
        image:      $(''),
        title:      $('

'),
        caption:    $('

')
    };
}; // end overlayElements()

function exit() {
    $('.overlay-container').on('click', '#closeButton', function()  {
        lightbox.background.remove();
        lightbox.overlay.empty().remove();
        $('.gallery').show();
    });// end #closeButton click
}; // end exit()

function next(index) {
    $('.overlay-container').on('click', '#nextButton', function()  {
         return $imageIndex = index+1;
    });// end #nextButton click
}; // end next()

function previous(index) {
    $('.overlay-container').on('click', '#previousButton', function()  {
        return $imageIndex = index-1;
    });// end #previousButton click
}; //end previous()

function imagePath(path) {
    // string replace image path
    let imagePath = 'img/thumbnails/';
    let newImagePath = 'img/';
    path =  images[indexValue].src;
    return path.replace(imagePath, newImagePath);
} //end imagePath()

<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 05/07/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic.github.io

*/

var Webtwic = Webtwic || {};

var browser = bowser.name.toLowerCase();

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic.github.io',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser_name : b.toLowerCase();
		if ( ! ( bowser.webkit ) )
			$( 'body' ).addClass( b + ' ' + b + parseInt( bowser.version ) );
		else
			$( 'body' ).addClass( 'webkit' + ' ' + b + ' ' + b + parseInt( bowser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,
	 $$ = Webtwic,
	 close_button = '',
	 browser_link = ' ' + 'browser.' + ' ',
	 notif_text = 'Whoa. Your browser currently dosen\'t support some important features. Please try refreshing this page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection
	switch ( browser_name ) {
	   case 'microsoft edge':
	      Webtwic.showBrowser( 'msedge' );
	      break;
		default:
			Webtwic.showBrowser();
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/

	var required_features = [
		Modernizr.flexbox,
		Modernizr.inlinesvg,
		Modernizr.svg,
		Modernizr.svgclippaths,
		Modernizr.fontface,
		Modernizr.boxshadow,
		Modernizr.borderradius,
		Modernizr.csstransforms
	];

	if ( window.Modernizr )
		if ( !( required_features ) )
			Webtwic.showNotif();
		else /* do nothing */ ;
	else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).on('click', function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).on('scroll', function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.find( '.tooltip' )
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.find( '.tooltip' )
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUIOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUIOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUIOverlay() {
		$( '.ui-overlay-search' )
		.fadeIn(400)
		.addClass( 'is_open' );
	}

	function closeUIOverlay() {
		$( '.ui-overlay-search' )
		.fadeOut(400)
		.removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).on('focus', function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).on('blur', function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).on('keydown', function( e ) {
		if ( e.keyCode == 27 )
			closeUIOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Replace: browser_name with browser<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 05/07/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic.github.io

*/

var Webtwic = Webtwic || {};

var browser = bowser.name.toLowerCase();

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic.github.io',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser : b.toLowerCase();
		if ( ! ( bowser.webkit ) )
			$( 'body' ).addClass( b + ' ' + b + parseInt( bowser.version ) );
		else
			$( 'body' ).addClass( 'webkit' + ' ' + b + ' ' + b + parseInt( bowser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,
	 $$ = Webtwic,
	 close_button = '',
	 browser_link = ' ' + 'browser.' + ' ',
	 notif_text = 'Whoa. Your browser currently dosen\'t support some important features. Please try refreshing this page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection
	switch ( browser ) {
	   case 'microsoft edge':
	      Webtwic.showBrowser( 'msedge' );
	      break;
		default:
			Webtwic.showBrowser();
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/

	var required_features = [
		Modernizr.flexbox,
		Modernizr.inlinesvg,
		Modernizr.svg,
		Modernizr.svgclippaths,
		Modernizr.fontface,
		Modernizr.boxshadow,
		Modernizr.borderradius,
		Modernizr.csstransforms
	];

	if ( window.Modernizr )
		if ( !( required_features ) )
			Webtwic.showNotif();
		else /* do nothing */ ;
	else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).on('click', function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).on('scroll', function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.find( '.tooltip' )
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.find( '.tooltip' )
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUIOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUIOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUIOverlay() {
		$( '.ui-overlay-search' )
		.fadeIn(400)
		.addClass( 'is_open' );
	}

	function closeUIOverlay() {
		$( '.ui-overlay-search' )
		.fadeOut(400)
		.removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).on('focus', function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).on('blur', function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).on('keydown', function( e ) {
		if ( e.keyCode == 27 )
			closeUIOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>var selectTree = (function(){
	'use strict'
	// selectors tree dom
	// get.item("seletor",fatherDom)
	// get.all("seletor",fatherDom)
	var get = {
	 	item: function(el, root){
			if(typeof(root)!="undefined") return root.querySelector(el);
			return document.querySelector(el);
	 	},
	 	all: function(el, root){
	 		if(typeof(root)!="undefined") return root.querySelectorAll(el);
	 		return document.querySelectorAll(el);
	 	}
	},
	app = {
		buildList: function(son){
			var elOptions = get.all("option",son),
			list = [],
			arr = {};
			for (var i = 0, lim = elOptions.length; i<lim; i++) {
				//arr.father
				delete elOptions[i].dataset['codEm'];
				console.log(elOptions[i].outerHTML);
				// return
			};
		},
		init: function(){

		}
	}
	//app.buildList(get.item(".teste"));
	app.init();
	return function(eu){
		console.log(eu);
	}
}());
selectTree("eu"); <commit_msg>Mudança no nome do javascript.<commit_after><|endoftext|>


<commit_before>/* jshint esnext: true */

function splitNumber(content) {
  var str = content.innerHTML;
  if (content.innerHTML.length === 10) {
    content.innerHTML = str.slice(0,2) + "-" + str.slice(2,4) + "-" + str.slice(4, 6) + "-" + str.slice(6, 8) + "-" + str.slice(8, 10);
  }
}

if (document.querySelector('html').baseURI === "app://communications.gaiamobile.org/contacts/index.html") {
  var contactAppDetails = document.querySelector('#view-contact-details');

  var observer = new MutationObserver(function (mutations) {
    var numbers = document.getElementById("details-list");
    for (var number of numbers.children) {
      if (!number.id.search("phone-details-template-")) {
        var content = number.children[1].children[0].children[0].children[0].children[0];
        splitNumber(content);
      }
    }
  });

  observer.observe(contactAppDetails, {
    childList: true, subtree: true
  });

}
else {
  console.log("coucou");
  var messageAppConv = document.querySelector('#messages-subheader');

  var newObserver = new MutationObserver(function (mutations) {
    var number = document.querySelector("#contact-carrier").children[0].children[2];
    splitNumber(number);
  });

  newObserver.observe(messageAppConv, {
    childList: true, subtree: true
  });

}
<commit_msg>Applies with +33 and (+33) numbers<commit_after>/* jshint esnext: true */

function splitNumber(content) {
  var str = content.innerHTML;
  var step = 2;
  var offset = 0;

  if (content.innerHTML.length === 10) {
    offset = 0;
  }
  else {
    if (content.innerHTML[0] === "(") {
      offset = 5;
    }
    else if (content.innerHTML[0] === "+") {
      offset = 3;
    }
  }
  content.innerHTML = str.slice(0 + offset, step + offset) + "-" + str.slice(offset + step, offset + step * 2) + "-" + str.slice(offset + step * 2, offset + step * 3) + "-" + str.slice(offset + step * 3, offset + step * 4) + "-" + str.slice(offset + step * 4, offset + step * 5);
}

if (document.querySelector('html').baseURI === "app://communications.gaiamobile.org/contacts/index.html") {
  var contactAppDetails = document.querySelector('#view-contact-details');

  var observer = new MutationObserver(function (mutations) {
    var numbers = document.getElementById("details-list");
    for (var number of numbers.children) {
      if (!number.id.search("phone-details-template-")) {
        var content = number.children[1].children[0].children[0].children[0].children[0];
        splitNumber(content);
      }
    }
  });

  observer.observe(contactAppDetails, {
    childList: true, subtree: true
  });

}
else {
  console.log("coucou");
  var messageAppConv = document.querySelector('#messages-subheader');

  var newObserver = new MutationObserver(function (mutations) {
    var number = document.querySelector("#contact-carrier").children[0].children[2];
    splitNumber(number);
  });

  newObserver.observe(messageAppConv, {
    childList: true, subtree: true
  });

}
<|endoftext|>


<commit_before>var scriptApp = angular.module('scriptApp',[]);

scriptApp.controller('scriptController',function($scope,$http){

    $http.get("./js/fileSettings.json")
    .then(function(res){
        $scope.init(res.data[0]);
    });

    $scope.outputLines = [];
    $scope.selectedLines = [];
    $scope.hideoutput = true;
    $scope.textExtensions="";
    $scope.requiredInputs=[
        {name:$scope.projtag,id:"idProjTag",model:"projectName"},
        {name:"Source Folder",id:"idSource",model:"sourceFolder"},
        {name:"Target Folder",id:"idTarget",model:"targetFolder"}
    ];

    var chokidar = require('chokidar');
    var fs = require('fs');
    var nodePath = require('path');
    var targz = require('targz');
    var watcher = null;

    var convertToPath = function(pathString){
        return nodePath.join(pathString,'')
    };

    var checkFields = function(fields){
        $scope.checkInputsMissing = [];
        for (i = 0; i < fields.length; ++i) {
            if ($scope[fields[i].model]=="") {
                $scope.warnInput(fields[i].id);
                $scope.checkInputsMissing.push(fields[i].name);
            };
        };
        if ($scope.checkInputsMissing.length > 0) {
            return false
        } else {
            return true
        };
    };

    var createFileName = function(){
        return $scope.projectName.replace(" ","_")+".tar.gz"
    };

    var checkInputs = function(){
        if (checkFields($scope.requiredInputs)) {
            finalFileName=createFileName();
            $scope.destinyFolder=nodePath.join($scope.targetFolder,finalFileName);
            $scope.StartWatcher($scope.sourceFolder);
            return true
        } else {
            return false
        }
    };

    var checkFiles = function(fname){
        ext = fname.substr(fname.lastIndexOf('.')+1);
        return ($scope.fileSettings.exts.indexOf(ext) > -1);
    };

    $scope.warnInput = function(id){
        $("#"+id).addClass("has-error");
    };

    $scope.compressFiles = function(){
        targz.compress({
            src: $scope.sourceFolder,
            dest: $scope.destinyFolder,
            tar: {
                entries: $scope.selectedLines,
            }
        }, function(err){
            if(err) {
                console.log(err);
            } else {
                console.log("Done!");
            }
        });
    };

    $scope.startInputs = function(fields){
        for (i = 0; i < fields.length; ++i) {
            $("#"+fields[i].id).removeClass("has-error");
        };
    };

    $scope.init = function(fileSettings) {
        $scope.fileSettings = fileSettings;
        $scope.targetFolder = convertToPath($scope.fileSettings.outfolder);
        $scope.projectName = "";
        $scope.sourceFolder = "";
    };

    $scope.StartWatcher = function(pathName){
        watcher = chokidar.watch(pathName, {
            ignored: /[\/\\]\./,
            persistent: true
        });
        function onWatcherReady(){
            console.info('Initial scan has been completed.');
            watcher.close();
            $scope.compressFiles();
        }
        watcher
        .on('add', function(pathName) {
            if (checkFiles(pathName)) {
                console.log('File', pathName, 'has been selected');
                $scope.addLog("File: "+pathName,"selected");
                $scope.saveLog(pathName);
            } else {
                console.log('File', pathName, 'has been review');
                $scope.addLog("File: "+pathName,"new");
            };
            $scope.$apply();
        })
        .on('error', function(error) {
            console.log('Error happened', error);
            $scope.addLog("An error ocurred: ","delete");
        })
        .on('ready', onWatcherReady);
    };

    $scope.getFolderDir = function(idLabel) {
        const {dialog} = require('electron').remote;
        dialog.showOpenDialog({
            properties: ['openDirectory']
        },function(path){
            if(path){
                if (idLabel==1) {
                    $scope.sourceFolder=path[0];
                } else if (idLabel==2) {
                    $scope.targetFolder=path[0];
                }
                $scope.$apply();
            }else {
                console.log("No path selected");
            }
        });
    };

    $scope.resetLog = function(){
        $scope.hideoutput = true;
        $scope.outputLines= [];
        $scope.selectedLines= [];
        $scope.startInputs($scope.requiredInputs);
        $scope.init($scope.fileSettings);
    };

    $scope.addLog = function(message,type){
        if(type == "selected"){
            ttcolor = "bg-primary";
        }else{
            ttcolor = "text-muted";
        };
        $scope.outputLines.push({
            message:message,
            tcolor:ttcolor
        });
    };

    $scope.saveLog = function(path){
        $scope.selectedLines.push(path);
    }

    $scope.initApp = function() {
        $scope.startInputs($scope.requiredInputs);
        if (checkInputs() == true) {
            $scope.hideoutput = false;
        } else {
            $scope.hideoutput = true;
        }
    };

});
<commit_msg>Reduce Path from Selected Variable.  For Tar to be working.<commit_after>var scriptApp = angular.module('scriptApp',[]);

scriptApp.controller('scriptController',function($scope,$http){

    $http.get("./js/fileSettings.json")
    .then(function(res){
        $scope.init(res.data[0]);
    });

    $scope.outputLines = [];
    $scope.selectedLines = [];
    $scope.hideoutput = true;
    $scope.textExtensions="";
    $scope.requiredInputs=[
        {name:$scope.projtag,id:"idProjTag",model:"projectName"},
        {name:"Source Folder",id:"idSource",model:"sourceFolder"},
        {name:"Target Folder",id:"idTarget",model:"targetFolder"}
    ];

    var chokidar = require('chokidar');
    var fs = require('fs');
    var nodePath = require('path');
    var targz = require('targz');
    var watcher = null;

    var convertToPath = function(pathString){
        return nodePath.join(pathString,'')
    };

    var checkFields = function(fields){
        $scope.checkInputsMissing = [];
        for (i = 0; i < fields.length; ++i) {
            if ($scope[fields[i].model]=="") {
                $scope.warnInput(fields[i].id);
                $scope.checkInputsMissing.push(fields[i].name);
            };
        };
        if ($scope.checkInputsMissing.length > 0) {
            return false
        } else {
            return true
        };
    };

    var createFileName = function(){
        return $scope.projectName.replace(" ","_")+".tar.gz"
    };

    var checkInputs = function(){
        if (checkFields($scope.requiredInputs)) {
            finalFileName=createFileName();
            $scope.destinyFolder=nodePath.join($scope.targetFolder,finalFileName);
            $scope.StartWatcher($scope.sourceFolder);
            return true
        } else {
            return false
        }
    };

    var checkFiles = function(fname){
        ext = fname.substr(fname.lastIndexOf('.')+1);
        return ($scope.fileSettings.exts.indexOf(ext) > -1);
    };

    $scope.warnInput = function(id){
        $("#"+id).addClass("has-error");
    };

    $scope.compressFiles = function(){
        targz.compress({
            src: $scope.sourceFolder,
            dest: $scope.destinyFolder,
            tar: {
                entries: $scope.selectedLines,
            }
        }, function(err){
            if(err) {
                console.log(err);
            } else {
                console.log("Done!");
            }
        });
    };

    $scope.startInputs = function(fields){
        for (i = 0; i < fields.length; ++i) {
            $("#"+fields[i].id).removeClass("has-error");
        };
    };

    $scope.init = function(fileSettings) {
        $scope.fileSettings = fileSettings;
        $scope.targetFolder = convertToPath($scope.fileSettings.outfolder);
        $scope.projectName = "";
        $scope.sourceFolder = "";
    };

    $scope.StartWatcher = function(pathName){
        watcher = chokidar.watch(pathName, {
            ignored: /[\/\\]\./,
            persistent: true
        });
        function onWatcherReady(){
            console.info('Initial scan has been completed.');
            watcher.close();
            $scope.compressFiles();
        }
        watcher
        .on('add', function(pathName) {
            if (checkFiles(pathName)) {
                console.log('File', pathName, 'has been selected');
                $scope.addLog("File: "+pathName,"selected");
                $scope.saveLog(pathName);
            } else {
                console.log('File', pathName, 'has been review');
                $scope.addLog("File: "+pathName,"new");
            };
            $scope.$apply();
        })
        .on('error', function(error) {
            console.log('Error happened', error);
            $scope.addLog("An error ocurred: ","delete");
        })
        .on('ready', onWatcherReady);
    };

    $scope.getFolderDir = function(idLabel) {
        const {dialog} = require('electron').remote;
        dialog.showOpenDialog({
            properties: ['openDirectory']
        },function(path){
            if(path){
                if (idLabel==1) {
                    $scope.sourceFolder=path[0];
                } else if (idLabel==2) {
                    $scope.targetFolder=path[0];
                }
                $scope.$apply();
            }else {
                console.log("No path selected");
            }
        });
    };

    $scope.resetLog = function(){
        $scope.hideoutput = true;
        $scope.outputLines= [];
        $scope.selectedLines= [];
        $scope.startInputs($scope.requiredInputs);
        $scope.init($scope.fileSettings);
    };

    $scope.addLog = function(message,type){
        if(type == "selected"){
            ttcolor = "bg-primary";
        }else{
            ttcolor = "text-muted";
        };
        $scope.outputLines.push({
            message:message,
            tcolor:ttcolor
        });
    };

    $scope.saveLog = function(path){
        $scope.selectedLines.push(path.replace($scope.sourceFolder+"\\",""));
    }

    $scope.initApp = function() {
        $scope.startInputs($scope.requiredInputs);
        if (checkInputs() == true) {
            $scope.hideoutput = false;
        } else {
            $scope.hideoutput = true;
        }
    };

});
<|endoftext|>


<commit_before>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', function (event) {
    event.preventDefault()
});

$(document).ready(function () {
    stopGame = false;
    firstLeftClick = true;
    firstClick = true;
    timer = new Timer();
    updateTimer();

    $('select#niveau').change(function(){   // Selection du niveau
      console.log($('select#niveau').val());
      switch ($('select#niveau').val()) {
        case "Facile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(10);
          $('#hauteur').val(10);
          $('#bombs').val(10);
          break;
        case "Moyen":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(20);
          $('#hauteur').val(15);
          $('#bombs').val(45);
          break;
        case "Difficile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(35);
          $('#hauteur').val(20);
          $('#bombs').val(170);
          break;
        case "Personnalisé":
          $('#menu input').prop('disabled', false);
          break;
      }
    });

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('#hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)) {
                if (testParameters(largeur, hauteur, bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {
    if (((largeur * hauteur) / 3) * 2 >= bombs) {
        if (largeur <= 40 && hauteur <= 50) {
            return true;
        }
    }
    return false;
}

function initGameboard() {
    stopGame = false;
    firstLeftClick = true;
    firstClick = true;
    timer.reset();
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('.reset').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            generateLayout(largeur, hauteur);
            firstLeftClick = true;
            firstClick = true;
            timer.reset();
            grid = new Grid(largeur, hauteur);
            grid.addBombs(bombs);
            $('#nbbombes').text(grid.flags + ' bombes');

            $('td').each(function () {
                initEvents($(this));
            });

        });
    });

    $('.menu-back').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            $('#largeur').val(largeur);
            $('#hauteur').val(hauteur);
            $('#bombs').val(bombs);

            $('#menu').css('display', 'block');
            $('#gameboard').css('display', 'none');

        });
    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem) {

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {
            console.log('clic du bouton gauche');

           if (firstLeftClick)
           {
             if (grid.cells[x][y].isBomb()){
               grid.moveOutBomb(x, y);
             }
             firstLeftClick=false;
           }

            var result = grid.reveal(x, y);

            result.cases.forEach(updateView);

            if (result.lost) {
                gameOverLose();
            }
            else {
                gameOverWin();
            }
        } else if (event.button == 2) {
            console.log('clic du bouton droit');

            grid.toggleFlag(x, y);

            updateView(grid.cells[x][y]);
            $('#nbbombes').text(grid.flags + ' bombes');
        }

        if (firstClick && (event.button == 0 || event.button  == 2)) {
            firstClick = false;
            timer.start();
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].isShown()) {
                result = grid.quickReveal(x, y);
                console.log(result.cases);

                result.cases.forEach(updateView);

                if (result.lost) {
                    gameOverLose()
                }
            }
        }
    });

}

function updateView(cell)
{
    var td = $('td[data-x="' + cell.x + '"][data-y="' + cell.y + '"]').removeClass();

    //console.log(cell);

    if (cell.isShown())
    {
        if (cell.isBomb())
        {
            td.addClass('bomb');
        }
        else {
            if (cell.isFlagged())
            {
                td.addClass('flagError');
            }
            else
            {
                if (cell.getValue() === 0)
                {
                    td.addClass('empty');
                }
                else
                {
                    td.addClass('number');
                    td.html(cell.getValue());
                }
            }
        }
    }
    else if (cell.isFlagged())
    {
        td.addClass('flag');
    }
}

function gameOverLose(elem) {
    timer.stop();
    $('#modal-lost').modal('show');
    bombCells = grid.getBombs();
    bombCells.forEach(updateView);
    stopGame = true;
    return stopGame;
}

function gameOverWin() {
    var i = 0;
    $('td').each(function () {
        if ($(this).hasClass('bomb')) {
            return false
        } else if (!$(this).hasClass('empty') && !$(this).hasClass('number')) {
            i += 1;
        } else if ($(this).hasClass('flag')) {
            i += 1;
        }
    });
    if (i == grid.bombs) {
        $('#modal-win').modal('show');
        stopGame = true;
        timer.stop();
        return stopGame;
    }
}

function updateTimer(){
  $('#timer').text(timer.get());

  setTimeout(updateTimer,500);
}
<commit_msg>taille<commit_after>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', function (event) {
    event.preventDefault()
});

$(document).ready(function () {
    stopGame = false;
    firstLeftClick = true;
    firstClick = true;
    timer = new Timer();
    updateTimer();

    $('select#niveau').change(function(){   // Selection du niveau
      console.log($('select#niveau').val());
      switch ($('select#niveau').val()) {
        case "Facile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(10);
          $('#hauteur').val(10);
          $('#bombs').val(10);
          break;
        case "Moyen":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(20);
          $('#hauteur').val(15);
          $('#bombs').val(45);
          break;
        case "Difficile":
          $('#menu input').prop('disabled', true);
          $('#largeur').val(35);
          $('#hauteur').val(20);
          $('#bombs').val(170);
          break;
        case "Personnalisé":
          $('#menu input').prop('disabled', false);
          break;
      }
    });

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('#hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)) {
                if (testParameters(largeur, hauteur, bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {
    if (((largeur * hauteur) / 3) * 2 >= bombs) {
        if (largeur <= 50 && hauteur <= 40) {
            return true;
        }
    }
    return false;
}

function initGameboard() {
    stopGame = false;
    firstLeftClick = true;
    firstClick = true;
    timer.reset();
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('.reset').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            generateLayout(largeur, hauteur);
            firstLeftClick = true;
            firstClick = true;
            timer.reset();
            grid = new Grid(largeur, hauteur);
            grid.addBombs(bombs);
            $('#nbbombes').text(grid.flags + ' bombes');

            $('td').each(function () {
                initEvents($(this));
            });

        });
    });

    $('.menu-back').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            $('#largeur').val(largeur);
            $('#hauteur').val(hauteur);
            $('#bombs').val(bombs);

            $('#menu').css('display', 'block');
            $('#gameboard').css('display', 'none');

        });
    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem) {

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {
            console.log('clic du bouton gauche');

           if (firstLeftClick)
           {
             if (grid.cells[x][y].isBomb()){
               grid.moveOutBomb(x, y);
             }
             firstLeftClick=false;
           }

            var result = grid.reveal(x, y);

            result.cases.forEach(updateView);

            if (result.lost) {
                gameOverLose();
            }
            else {
                gameOverWin();
            }
        } else if (event.button == 2) {
            console.log('clic du bouton droit');

            grid.toggleFlag(x, y);

            updateView(grid.cells[x][y]);
            $('#nbbombes').text(grid.flags + ' bombes');
        }

        if (firstClick && (event.button == 0 || event.button  == 2)) {
            firstClick = false;
            timer.start();
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].isShown()) {
                result = grid.quickReveal(x, y);
                console.log(result.cases);

                result.cases.forEach(updateView);

                if (result.lost) {
                    gameOverLose()
                }
            }
        }
    });

}

function updateView(cell)
{
    var td = $('td[data-x="' + cell.x + '"][data-y="' + cell.y + '"]').removeClass();

    //console.log(cell);

    if (cell.isShown())
    {
        if (cell.isBomb())
        {
            td.addClass('bomb');
        }
        else {
            if (cell.isFlagged())
            {
                td.addClass('flagError');
            }
            else
            {
                if (cell.getValue() === 0)
                {
                    td.addClass('empty');
                }
                else
                {
                    td.addClass('number');
                    td.html(cell.getValue());
                }
            }
        }
    }
    else if (cell.isFlagged())
    {
        td.addClass('flag');
    }
}

function gameOverLose(elem) {
    timer.stop();
    $('#modal-lost').modal('show');
    bombCells = grid.getBombs();
    bombCells.forEach(updateView);
    stopGame = true;
    return stopGame;
}

function gameOverWin() {
    var i = 0;
    $('td').each(function () {
        if ($(this).hasClass('bomb')) {
            return false
        } else if (!$(this).hasClass('empty') && !$(this).hasClass('number')) {
            i += 1;
        } else if ($(this).hasClass('flag')) {
            i += 1;
        }
    });
    if (i == grid.bombs) {
        $('#modal-win').modal('show');
        stopGame = true;
        timer.stop();
        return stopGame;
    }
}

function updateTimer(){
  $('#timer').text(timer.get());

  setTimeout(updateTimer,500);
}
<|endoftext|>


<commit_before>$(document).ready(function($) {
	// $('.welcome-wrapper') .css({'min-height': (($(window).height()) - $('.enter').height() ) + 'px'}); //allows space for the enter section
	// $('#about').css({'min-height': $(window).height()+ 'px'}); //allows space for the footer section
	// $('#projects').css({'min-height': (($(window).height()) - $('.footer').height() ) + 'px'}); //allows space for the footer section
	$('.welcome-text').css({
		left: ($(window).outerWidth() - $('.welcome-text').outerWidth()) / 2 + 'px',
		top: ($(window).outerHeight() - $('.welcome-text').outerHeight()) / 2 + 'px'
	});
});
$(window).resize(function() {
	$('.welcome-wrapper').css({
		left: ($(window).outerWidth() - $('.welcome-text').outerWidth()) / 2 + 'px',
		top: ($(window).outerHeight() - $('.welcome-text').outerHeight()) / 2 + 'px'
	});
});

$(document).ready(function(){
	//Toggle between projects and about section
	$(".toggle").click(function(event){
		var sectionArray = ["about", "projects", "research" , "publications", "contact"];
		for (var i=0; i<sectionArray.length; i++){
			$("."+sectionArray[i]+"-text").hide();
		}
		var sectionId = this.id;
		$("."+sectionId+"-text").fadeIn();
	});
	$(".toggleAbout").click(function(event){
		$(".project-text").hide();
		$(".about-text").fadeIn();
	});
	var curProject;
	$(".project-box").click(function(event){
		var projectId = this.id;
		if (projectId === curProject){
			curProject = ""; //resets curProject so it can slide down again
			$('.project-specs#'+projectId).slideUp();
		}else{
			curProject = projectId;
			$('.project-specs').hide();
			$('.project-specs#'+projectId).slideDown();
		}
	});
	//Scrolling animation
	$(".scroll").click(function(event){
		event.preventDefault();
		var full_url = this.href;
		var parts = full_url.split("#");
		var trgt = parts[1];
		var target_offset = $("#" + trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop: target_top}, 400);
	});
});<commit_msg>fixed home page height<commit_after>$(document).ready(function($) {
	$('.welcome-wrapper') .css({'min-height': (($(window).height()) - $('.enter').height() ) + 'px'}); //allows space for the enter section
	// $('#about').css({'min-height': $(window).height()+ 'px'}); //allows space for the footer section
	// $('#projects').css({'min-height': (($(window).height()) - $('.footer').height() ) + 'px'}); //allows space for the footer section
	$('.welcome-text').css({
		left: ($(window).outerWidth() - $('.welcome-text').outerWidth()) / 2 + 'px',
		top: ($(window).outerHeight() - $('.welcome-text').outerHeight()) / 2 + 'px'
	});
});
$(window).resize(function() {
	$('.welcome-wrapper').css({
		left: ($(window).outerWidth() - $('.welcome-text').outerWidth()) / 2 + 'px',
		top: ($(window).outerHeight() - $('.welcome-text').outerHeight()) / 2 + 'px'
	});
});

$(document).ready(function(){
	//Toggle between projects and about section
	$(".toggle").click(function(event){
		var sectionArray = ["about", "projects", "research" , "publications", "contact"];
		for (var i=0; i<sectionArray.length; i++){
			$("."+sectionArray[i]+"-text").hide();
		}
		var sectionId = this.id;
		$("."+sectionId+"-text").fadeIn();
	});
	$(".toggleAbout").click(function(event){
		$(".project-text").hide();
		$(".about-text").fadeIn();
	});
	var curProject;
	$(".project-box").click(function(event){
		var projectId = this.id;
		if (projectId === curProject){
			curProject = ""; //resets curProject so it can slide down again
			$('.project-specs#'+projectId).slideUp();
		}else{
			curProject = projectId;
			$('.project-specs').hide();
			$('.project-specs#'+projectId).slideDown();
		}
	});
	//Scrolling animation
	$(".scroll").click(function(event){
		event.preventDefault();
		var full_url = this.href;
		var parts = full_url.split("#");
		var trgt = parts[1];
		var target_offset = $("#" + trgt).offset();
		var target_top = target_offset.top;

		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop: target_top}, 400);
	});
});<|endoftext|>


<commit_before>var CSS_COLOR_NAMES = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "ForestGreen", "Fuchsia", "Gainsboro", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "Yellow", "YellowGreen"];
var color;
var reset_counter = 0;
var lamp_awsome = '';
var spinner = '';
var first_init = 0;
var player_name=null;
var score=0;
var first_move=true;
var init_flag=false;
function getname(){
    while(player_name==null||player_name.length<1||player_name.length>10){
    player_name=prompt("Please Enter Your Name ;-)\n(1-10 Character)");
    }
}
function init(flag) {
    first_init = 1;
    color = CSS_COLOR_NAMES[Math.floor((Math.random() * CSS_COLOR_NAMES.length) + 1)].toLowerCase();
    var i, random_number, random_counter, move, game_name, random_init, reset;
    var random_list = [];
    random_counter = 0;
    game_name = document.getElementById("game_name");
    game_name.style.color = color;
    game_name.innerHTML = "Lights Out Game";
    move = document.getElementById("move");
    reset = document.getElementById("reset");
    random_init = 0;
    init_flag=true;
    if (flag == 2) {
        reset_counter = reset_counter + 1;
        reset.innerHTML = "Reset" + " (" + reset_counter + ")";
    }
    while (random_init < 10) {
        random_init = Math.floor((Math.random() * 15) + 1);
    }
    while (random_counter < random_init) {
        random_number = Math.floor((Math.random() * 25) + 1);
        if (random_list.indexOf(random_number) < 0) {
            random_list.push(random_number);
            random_counter = random_counter + 1;
        }
    }
    for (i = 1; i < 26; i++) {
        document.getElementById(i.toString()).style.backgroundColor = color;
        document.getElementById(i.toString()).innerHTML = "";
    }
    for (i = 0; i < random_list.length; i++) {
        reply_click(random_list[i].toString(),true);
    }

    move.innerHTML = 0;
    init_flag=false;
}

var reply_click = function (e) {
    var input_id, ele, move;
    move = document.getElementById("move");
    if (first_move==true&&init_flag==false){
                display = document.querySelector('#time');
                startTimer(7*60, display);
        first_move=false;
    }
    input_id = parseInt(e);
    if (first_init == 1) {
        if ((input_id + 5) <= 25) {
            toggle(input_id + 5);
        }
        if ((input_id - 5) >= 1) {
            toggle(input_id - 5);
        }
        if (((input_id - 1) % 5) == 0) {
            toggle(input_id + 1);
        }
        else if ((input_id % 5) == 0) {
            toggle(input_id - 1);

        }
        else {
            toggle(input_id - 1);
            toggle(input_id + 1);
        }
        move.innerHTML = parseInt(move.innerHTML) + 1;
        toggle(input_id)

        end_game();
    }

}

function toggle(input_id) {
    var press_button;
    press_button = document.getElementById(input_id.toString());
    if (press_button.style.backgroundColor == color) {
        press_button.style.backgroundColor = "white";
        press_button.innerHTML = lamp_awsome;
    }
    else {
        press_button.style.backgroundColor = color;
        press_button.innerHTML = "";
    }

}

function end_game() {
    var i, on_lamp, win;
    on_lamp = 0;
    for (i = 1; i < 26; i++) {
        if (document.getElementById(i.toString()).style.backgroundColor == "white") {
            on_lamp = on_lamp + 1;
            break;
        }
    }
    if (on_lamp == 0) {
        score=score+1
        win = document.getElementById("win");
        win.innerHTML = parseInt(win.innerHTML) + 1;
        init();
    }
}

function savescore(){
    getname();
    saveToFirebase(player_name,score);

}

function get_data(){
    var leadsRef = firebase.database().ref('subscription-entries').orderByChild("score").limitToLast(10);
    var counter=0;
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var name = childSnapshot.val().name;
      var score= childSnapshot.val().score;
      document.getElementById("N"+(10-counter).toString()).innerHTML=name;
      document.getElementById("S"+(10-counter).toString()).innerHTML=score;
     counter=counter+1;
    });
});
}

function saveToFirebase(name,score) {
    var submit_button
    submit_button=document.getElementById("submit_button");
    var scoreObject = {
        name: name,
        score: score
    };
    try{
    firebase.database().ref('subscription-entries').push().set(scoreObject)
        .then(function(snapshot) {
            alert("Your Score Saved :-)")
            submit_button.style.display="none";
        }, function(error) {
            console.log('error' + error);
            alert("Error In Score Submit :-(");
        });
    }
    catch(e){
        alert("Error In Score Submit :-(");
    }
}

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var interval_id=setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            alert("Time is up\n Score:"+score.toString()+"\n Reset:"+reset_counter.toString());
            timer = duration;
            display.textContent = 7 + ":" + "00";
            win = document.getElementById("win");
            win.innerHTML = 0;
            score=0;
            reset = document.getElementById("reset");
            reset.innerHTML = "Reset"
            init(1);
            clearInterval(interval_id);
        }
    }, 1000);
}

<commit_msg>fix : minor edit in timer<commit_after>var CSS_COLOR_NAMES = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "ForestGreen", "Fuchsia", "Gainsboro", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "Yellow", "YellowGreen"];
var color;
var reset_counter = 0;
var lamp_awsome = '';
var spinner = '';
var first_init = 0;
var player_name=null;
var score=0;
var first_move=true;
var init_flag=false;
function getname(){
    while(player_name==null||player_name.length<1||player_name.length>10){
    player_name=prompt("Please Enter Your Name ;-)\n(1-10 Character)");
    }
}
function init(flag) {
    first_init = 1;
    color = CSS_COLOR_NAMES[Math.floor((Math.random() * CSS_COLOR_NAMES.length) + 1)].toLowerCase();
    var i, random_number, random_counter, move, game_name, random_init, reset;
    var random_list = [];
    random_counter = 0;
    game_name = document.getElementById("game_name");
    game_name.style.color = color;
    game_name.innerHTML = "Lights Out Game";
    move = document.getElementById("move");
    reset = document.getElementById("reset");
    random_init = 0;
    init_flag=true;
    if (flag == 2) {
        reset_counter = reset_counter + 1;
        reset.innerHTML = "Reset" + " (" + reset_counter + ")";
    }
    while (random_init < 10) {
        random_init = Math.floor((Math.random() * 15) + 1);
    }
    while (random_counter < random_init) {
        random_number = Math.floor((Math.random() * 25) + 1);
        if (random_list.indexOf(random_number) < 0) {
            random_list.push(random_number);
            random_counter = random_counter + 1;
        }
    }
    for (i = 1; i < 26; i++) {
        document.getElementById(i.toString()).style.backgroundColor = color;
        document.getElementById(i.toString()).innerHTML = "";
    }
    for (i = 0; i < random_list.length; i++) {
        reply_click(random_list[i].toString(),true);
    }

    move.innerHTML = 0;
    init_flag=false;
}

var reply_click = function (e) {
    var input_id, ele, move;
    move = document.getElementById("move");
    if (first_move==true&&init_flag==false){
                display = document.querySelector('#time');
                startTimer(7*60, display);
        first_move=false;
    }
    input_id = parseInt(e);
    if (first_init == 1) {
        if ((input_id + 5) <= 25) {
            toggle(input_id + 5);
        }
        if ((input_id - 5) >= 1) {
            toggle(input_id - 5);
        }
        if (((input_id - 1) % 5) == 0) {
            toggle(input_id + 1);
        }
        else if ((input_id % 5) == 0) {
            toggle(input_id - 1);

        }
        else {
            toggle(input_id - 1);
            toggle(input_id + 1);
        }
        move.innerHTML = parseInt(move.innerHTML) + 1;
        toggle(input_id)

        end_game();
    }

}

function toggle(input_id) {
    var press_button;
    press_button = document.getElementById(input_id.toString());
    if (press_button.style.backgroundColor == color) {
        press_button.style.backgroundColor = "white";
        press_button.innerHTML = lamp_awsome;
    }
    else {
        press_button.style.backgroundColor = color;
        press_button.innerHTML = "";
    }

}

function end_game() {
    var i, on_lamp, win;
    on_lamp = 0;
    for (i = 1; i < 26; i++) {
        if (document.getElementById(i.toString()).style.backgroundColor == "white") {
            on_lamp = on_lamp + 1;
            break;
        }
    }
    if (on_lamp == 0) {
        score=score+1
        win = document.getElementById("win");
        win.innerHTML = parseInt(win.innerHTML) + 1;
        init();
    }
}

function savescore(){
    getname();
    saveToFirebase(player_name,score);

}

function get_data(){
    var leadsRef = firebase.database().ref('subscription-entries').orderByChild("score").limitToLast(10);
    var counter=0;
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var name = childSnapshot.val().name;
      var score= childSnapshot.val().score;
      document.getElementById("N"+(10-counter).toString()).innerHTML=name;
      document.getElementById("S"+(10-counter).toString()).innerHTML=score;
     counter=counter+1;
    });
});
}

function saveToFirebase(name,score) {
    var submit_button
    submit_button=document.getElementById("submit_button");
    var scoreObject = {
        name: name,
        score: score
    };
    try{
    firebase.database().ref('subscription-entries').push().set(scoreObject)
        .then(function(snapshot) {
            alert("Your Score Saved :-)")
            submit_button.style.display="none";
        }, function(error) {
            console.log('error' + error);
            alert("Error In Score Submit :-(");
        });
    }
    catch(e){
        alert("Error In Score Submit :-(");
    }
}

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var interval_id=setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            alert("Time is up\n Score:"+score.toString()+"\n Reset:"+reset_counter.toString());
            timer = duration;
            display.textContent = 7 + ":" + "00";
            win = document.getElementById("win");
            win.innerHTML = 0;
            score=0;
            reset = document.getElementById("reset");
            reset.innerHTML = "Reset"
            first_move=true;
            init(1);
            clearInterval(interval_id);
        }
    }, 1000);
}

<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //create an empty map
        var map = new Array(960);
        for(var i = 0; i < 960; i++) {
            map[i] = new Array(540);
        }

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

        var id = c.createImageData(1,1);
        var d = id.data;

        function ncount(i,j) {
            var i1 = i+1;
            var i2 = i-1;
            var j1 = j+1;
            var j2 = j-1;
            var neighbors = 0;
            if(i1 < 960 && i2 >=0 && j1 < 540 && j2 >=0){
                if(map[i1][j1] == 1){
                    neighbors++;
                }
                if(map[i][j1] == 1){
                    neighbors++;
                }
                if(map[i2][j1] == 1){
                    neighbors++;
                }
                if(map[i1][j] == 1){
                    neighbors++;
                }
                if(map[i2][j] == 1){
                    neighbors++;
                }
                if(map[i1][j2] == 1){
                    neighbors++;
                }
                if(map[i][j2] == 1){
                    neighbors++;
                }
                if(map[i2][j2] == 1){
                    neighbors++;
                }
            }
            return neighbors;
        }

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        var it = 1;
        function paint() {
            if(it == 1){
                //fill the values
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++) {
                        if(Math.random() < .45){
                            map[i][j] = 1;
                        } else {
                            map[i][j] = 0;
                        }
                    }
                }
            } else {
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++){
                        var nc = ncount(i,j);
                        switch(nc){
                            case 4:
                                break;
                            case 5:
                                map[i][j] = 1;
                                break;
                            case 6:
                                map[i][j] = 1;
                                break;
                            case 7:
                                map[i][j] = 1;
                                break;
                            case 8:
                                map[i][j] = 1;
                                break;
                            default:
                                map[i][j] = 0;
                        }
                    }
                }
            }

            d[0] = 255;
            d[1] = 255;
            d[2] = 255;
            d[3] = 1;

            //paint the map
            for(var i = 0; i < 960; i++) {
                for(var j = 0; j< 540; j++){
                    if(map[i][j] == 1){
                        c.putImageData(id, i, j);
                    }else {
                        c.fillStyle = '#FFFFFF';
                        c.fillRect(i + 0.5,j + 0.5,1,1);
                    }
                }
            }
            it++;
            document.getElementById("iter").innerHTML = it;
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //create an empty map
        var map = new Array(960);
        for(var i = 0; i < 960; i++) {
            map[i] = new Array(540);
        }

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

        var id = c.createImageData(1,1);
        var d = id.data;

        function ncount(i,j) {
            var i1 = i+1;
            var i2 = i-1;
            var j1 = j+1;
            var j2 = j-1;
            var neighbors = 0;
            if(i1 < 960 && i2 >=0 && j1 < 540 && j2 >=0){
                if(map[i1][j1] == 1){
                    neighbors++;
                }
                if(map[i][j1] == 1){
                    neighbors++;
                }
                if(map[i2][j1] == 1){
                    neighbors++;
                }
                if(map[i1][j] == 1){
                    neighbors++;
                }
                if(map[i2][j] == 1){
                    neighbors++;
                }
                if(map[i1][j2] == 1){
                    neighbors++;
                }
                if(map[i][j2] == 1){
                    neighbors++;
                }
                if(map[i2][j2] == 1){
                    neighbors++;
                }
            }
            return neighbors;
        }

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        var it = 1;
        function paint() {
            if(it == 1){
                //fill the values
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++) {
                        if(Math.random() < .45){
                            map[i][j] = 1;
                        } else {
                            map[i][j] = 0;
                        }
                    }
                }
            } else {
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++){
                        var nc = ncount(i,j);
                        switch(nc){
                            case 4:
                                break;
                            case 5:
                                map[i][j] = 1;
                                break;
                            case 6:
                                map[i][j] = 1;
                                break;
                            case 7:
                                map[i][j] = 1;
                                break;
                            case 8:
                                map[i][j] = 1;
                                break;
                            default:
                                map[i][j] = 0;
                        }
                    }
                }
            }

            //paint the map
            for(var i = 0; i < 960; i++) {
                for(var j = 0; j< 540; j++){
                    if(map[i][j] == 1){
                        d[0] = 0;
                        d[1] = 0;
                        d[2] = 0;
                        d[3] = 1;
                        c.putImageData(id, i, j);
                    }else {
                        d[0] = 255;
                        d[1] = 255;
                        d[2] = 255;
                        d[3] = 1;
                        c.putImageData(id, i, j);
                    }
                }
            }
            it++;
            document.getElementById("iter").innerHTML = it;
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>$(function() {
	var isFetchingPosts = false;
	var postsToLoad = 3;
	var all_results = new Array();
  // Initialize lunr with the fields to be searched, plus the boost.
  window.idx = lunr(function () {
    this.field('id');
    this.field('postHeading');
    this.field('subHeading');
    this.field('content', { boost: 10 });
    this.field('date');
    this.field('tags');
    this.field('image');
  });

  // Get the generated search_data.json file so lunr.js can search it locally.
  window.data = $.getJSON('/search-data.json');

  // Wait for the data to load and add it to lunr
  window.data.then(function(loaded_data){
    $.each(loaded_data, function(index, value){
      window.idx.add(
        $.extend({ "id": index }, value)
      );
    });
  });

  // Event when the form is submitted
  $("#site_search").submit(function(event){
      event.preventDefault();
      var query = $("#search_box").val(); // Get the value for the text field
      var results = window.idx.search(query); // Get lunr to perform a search
      display_search_results(results); // Hand the results off to be displayed
	  show_more_results_btn(); // Display more search results button
  });

  function display_search_results(results) {
    // Wait for data to load
    window.data.then(function(loaded_data) {

      // Are there any results?
      if (results.length) {
        $("#search_results").empty(); // Clear any old results

        // Iterate over the results
        results.forEach(function(result,i) {
          var item = loaded_data[result.ref];

		  // Populate all_results
		  all_results.push({url:item.url, postHeading:item.postHeading, date:item.date, tags:item.tags, subHeading:item.subHeading});

		  if(i < postsToLoad){
			  // Build a snippet of HTML for this result
			  build_html(item.url, item.postHeading, item.subHeading, item.date, item.tags.split(', '));
			}
        });
      } else {
        // If there are no results, let the user know.
        $("#search_results").html('
No results found.

Please check spelling, spacing, and so on.

Make sure you are not searching for common words like "and", "the", "yet" etc. Such words appear throughout the site and are automatically discarded during the search process.

');
      }
    });
	return all_results;
  }

  function show_more_results_btn(){
	  if(all_results.length > postsToLoad){
		  var element = document.createElement("a");
		  element.setAttribute('href', '#');
		  element.setAttribute('class', 'next');
		  element.onclick = function(e){getMoreResults();return false;};
		  var anchorText = document.createTextNode("Show More Results");
		  element.appendChild(anchorText);
		  $(element).appendTo(".pagination");
	  }
  }

	//get more button
	function getMoreResults(){
		if (isFetchingPosts) return;
		fetchPosts();
	}

	// Fetch a chunk of posts
	function fetchPosts() {
		isFetchingPosts = true;

		// After successfully loading a post, load the next one
		var loadedPosts = 0;
		var postIndex = 0;
		while(postIndex < all_results.length-1){
			postIndex = postsToLoad + loadedPosts;
			if (loadedPosts < postsToLoad) {
				fetchPostWithIndex(postIndex);
			} else {
				isFetchingPosts = false;
			}
			loadedPosts++;
		}
		disableFetching();
	}

	function fetchPostWithIndex(index) {
		var item = all_results[index];
		build_html(item.url, item.postHeading, item.subHeading, item.date, item.tags.split(', '));
	}

	function disableFetching() {
		isFetchingPosts = false;
		$(".pager").remove();
	}

  function build_html(url, heading, subHeading, date, tags){
    // Create div
    var postPreview = document.createElement("div");
	postPreview.setAttribute('class', 'post-preview');
	// Create anchor
	var anchor = document.createElement("a");
	anchor.setAttribute('href', url);
	var title = document.createElement("h2");
	title.setAttribute('class', 'post-title');
	title.innerHTML = heading;
	var subTitle = document.createElement("h3");
	subTitle.setAttribute('class', 'post-subtitle');
	subTitle.innerHTML = subHeading;
	// Close anchor
	anchor.appendChild(title);
	anchor.appendChild(subTitle);
	// Create paragraph
	var paragraph = document.createElement('P');
	paragraph.setAttribute('class', 'paragraph post-meta');
	var calendar = document.createElement('i');
	calendar.setAttribute('class', 'icon-calendar');
	var node1 = document.createTextNode("Posted on: " + date + " |");
	var tag = document.createElement('i');
	tag.setAttribute('class', 'icon-tags');
	var node2 = document.createTextNode(" Tags: ");
	var subAnchor = document.createElement("a");
	if(tags[0] == 'food') subAnchor.setAttribute('href', '/recipes.html');
	else  subAnchor.setAttribute('href', '/creative-writing.html');
	subAnchor.setAttribute('title', 'View posts tagged with "' + tags[0] + '"');
	var span = document.createElement("span");
	span.setAttribute('class', 'label label-info');
	span.innerHTML = tags[0];
	subAnchor.appendChild(span);
	// Close paragraph
	paragraph.appendChild(calendar);
	paragraph.appendChild(node1);
	paragraph.appendChild(tag);
	paragraph.appendChild(node2);
	paragraph.appendChild(subAnchor);
	// Close div
	postPreview.appendChild(anchor);
	postPreview.appendChild(paragraph);
	// Add html to the collection of results.
	$("#search_results").append(postPreview);
	$("#search_results").append(document.createElement("HR"));
  }
});<commit_msg>changed search function<commit_after>$(function() {
	var isFetchingPosts = false;
	var postsToLoad = 3;
	var all_results = new Array();
  // Initialize lunr with the fields to be searched, plus the boost.
  window.idx = lunr(function () {
    this.field('id');
    this.field('postHeading');
    this.field('subHeading');
    this.field('content', { boost: 10 });
    this.field('date');
    this.field('tags');
    this.field('image');
  });

  // Get the generated search_data.json file so lunr.js can search it locally.
  window.data = $.getJSON('/search-data.json');

  // Wait for the data to load and add it to lunr
  window.data.then(function(loaded_data){
    $.each(loaded_data, function(index, value){
      window.idx.add(
        $.extend({ "id": index }, value)
      );
    });
  });

  // Event when the form is submitted
  $("#site_search").submit(function(event){
      event.preventDefault();
      var query = $("#search_box").val(); // Get the value for the text field
      var results = window.idx.search(query); // Get lunr to perform a search
      display_search_results(results); // Hand the results off to be displayed
	  show_more_results_btn(); // Display more search results button
  });

  function display_search_results(results) {
    // Wait for data to load
    window.data.then(function(loaded_data) {
		// Clear any old results
        $("#search_results").empty();
		$(".pagination").empty();
		all_results = [];

      // Are there any results?
      if (results.length) {
        // Iterate over the results
        results.forEach(function(result,i) {
          var item = loaded_data[result.ref];

		  // Populate all_results
		  all_results.push({url:item.url, postHeading:item.postHeading, date:item.date, tags:item.tags, subHeading:item.subHeading});

		  if(i < postsToLoad){
			  // Build a snippet of HTML for this result
			  build_html(item.url, item.postHeading, item.subHeading, item.date, item.tags.split(', '));
			}
        });
      } else {
        // If there are no results, let the user know.
        $("#search_results").html('
No results found.

Please check spelling, spacing, and so on.

Make sure you are not searching for common words like "and", "the", "yet" etc. Such words appear throughout the site and are automatically discarded during the search process.

');
      }
    });
  }

  function show_more_results_btn(){
	  if(all_results.length > postsToLoad){
		  var element = document.createElement("a");
		  element.setAttribute('href', '#');
		  element.setAttribute('class', 'next');
		  element.onclick = function(e){getMoreResults();return false;};
		  var anchorText = document.createTextNode("Show More Results");
		  element.appendChild(anchorText);
		  $(element).appendTo(".pagination");
	  }
  }

	//get more button
	function getMoreResults(){
		if (isFetchingPosts) return;
		fetchPosts();
	}

	// Fetch a chunk of posts
	function fetchPosts() {
		isFetchingPosts = true;

		// After successfully loading a post, load the next one
		var loadedPosts = 0;
		var postIndex = 0;
		while(postIndex < all_results.length-1){
			postIndex = postsToLoad + loadedPosts;
			if (loadedPosts < postsToLoad) {
				fetchPostWithIndex(postIndex);
			} else {
				isFetchingPosts = false;
			}
			loadedPosts++;
		}
		disableFetching();
	}

	function fetchPostWithIndex(index) {
		var item = all_results[index];
		build_html(item.url, item.postHeading, item.subHeading, item.date, item.tags.split(', '));
	}

	function disableFetching() {
		isFetchingPosts = false;
		$(".pager").remove();
	}

  function build_html(url, heading, subHeading, date, tags){
    // Create div
    var postPreview = document.createElement("div");
	postPreview.setAttribute('class', 'post-preview');
	// Create anchor
	var anchor = document.createElement("a");
	anchor.setAttribute('href', url);
	var title = document.createElement("h2");
	title.setAttribute('class', 'post-title');
	title.innerHTML = heading;
	var subTitle = document.createElement("h3");
	subTitle.setAttribute('class', 'post-subtitle');
	subTitle.innerHTML = subHeading;
	// Close anchor
	anchor.appendChild(title);
	anchor.appendChild(subTitle);
	// Create paragraph
	var paragraph = document.createElement('P');
	paragraph.setAttribute('class', 'paragraph post-meta');
	var calendar = document.createElement('i');
	calendar.setAttribute('class', 'icon-calendar');
	var node1 = document.createTextNode("Posted on: " + date + " |");
	var tag = document.createElement('i');
	tag.setAttribute('class', 'icon-tags');
	var node2 = document.createTextNode(" Tags: ");
	var subAnchor = document.createElement("a");
	if(tags[0] == 'food') subAnchor.setAttribute('href', '/recipes.html');
	else  subAnchor.setAttribute('href', '/creative-writing.html');
	subAnchor.setAttribute('title', 'View posts tagged with "' + tags[0] + '"');
	var span = document.createElement("span");
	span.setAttribute('class', 'label label-info');
	span.innerHTML = tags[0];
	subAnchor.appendChild(span);
	// Close paragraph
	paragraph.appendChild(calendar);
	paragraph.appendChild(node1);
	paragraph.appendChild(tag);
	paragraph.appendChild(node2);
	paragraph.appendChild(subAnchor);
	// Close div
	postPreview.appendChild(anchor);
	postPreview.appendChild(paragraph);
	// Add html to the collection of results.
	$("#search_results").append(postPreview);
	$("#search_results").append(document.createElement("HR"));
  }
});<|endoftext|>


<commit_before>$(document).ready(crearCollapse());

function crearCollapse() {
    var i = 0;
    $.getJSON("../../data/semana/clases.json", function(data) {
        var i = 0;
        $.each(data.semanas, function(key, value) {
            var panelDefault = $('

');
            var panelHeading = $('

');
            if (i == 0) {
                var panelTitle = $('
' + "Semana #" + value.numero + " - Capítulo " + value.capitulo + '
');
                var panelCollapse = $('

');
            } else {
                var panelTitle = $('
' + "Semana #" +value.numero + " - Capítulo " + value.capitulo + '
');
                var panelCollapse = $('

');
            }
            $.each(value.clases, function(key, valueClase) {
                var panelBody = $('

');
                var label = $('
Tema: ' + valueClase.tema +'
');
                var p = $('
' + valueClase.descripcion +'
');
                panelBody.append(label);
                panelBody.append(p);
                panelCollapse.append(panelBody);
                var panelFooter = $('

');
                if (valueClase.recursos.length != 0) {
                    label = $('Recursos
');
                    panelFooter.append(label);
                    $.each(valueClase.recursos, function(key, valueRecursos) {
                        var a = $('' + valueRecursos.tipo + ' - ' + valueRecursos.titulo + '
');
                        panelFooter.append(a);
                    });
                    panelCollapse.append(panelFooter);
                }
            });
            panelHeading.append(panelTitle);
            panelDefault.append(panelHeading);
            panelDefault.append(panelCollapse);
            $("#accordion").append(panelDefault);
            i++;
        });
    });
}<commit_msg>Abrir en nueva pestaña los recursos<commit_after>$(document).ready(crearCollapse());

function crearCollapse() {
    var i = 0;
    $.getJSON("../../data/semana/clases.json", function(data) {
        var i = 0;
        $.each(data.semanas, function(key, value) {
            var panelDefault = $('

');
            var panelHeading = $('

');
            if (i == 0) {
                var panelTitle = $('
' + "Semana #" + value.numero + " - Capítulo " + value.capitulo + '
');
                var panelCollapse = $('

');
            } else {
                var panelTitle = $('
' + "Semana #" +value.numero + " - Capítulo " + value.capitulo + '
');
                var panelCollapse = $('

');
            }
            $.each(value.clases, function(key, valueClase) {
                var panelBody = $('

');
                var label = $('
Tema: ' + valueClase.tema +'
');
                var p = $('
' + valueClase.descripcion +'
');
                panelBody.append(label);
                panelBody.append(p);
                panelCollapse.append(panelBody);
                var panelFooter = $('

');
                if (valueClase.recursos.length != 0) {
                    label = $('Recursos
');
                    panelFooter.append(label);
                    $.each(valueClase.recursos, function(key, valueRecursos) {
                        var a = $('' + valueRecursos.tipo + ' - ' + valueRecursos.titulo + '
');
                        panelFooter.append(a);
                    });
                    panelCollapse.append(panelFooter);
                }
            });
            panelHeading.append(panelTitle);
            panelDefault.append(panelHeading);
            panelDefault.append(panelCollapse);
            $("#accordion").append(panelDefault);
            i++;
        });
    });
}<|endoftext|>