<commit_before>var player_positions = ["part", "right", "own", "left"];
var sides = ["N", "E", "S", "W"];
var suit_image_template = "";
var big_suit_image_template = "";
var update_cnt = 1000;
var pass_dbl_rdbl = ["pass", "dbl", "rdbl"];

var lead_count;
var current_bidder;

var update_handlers = new Array();
update_handlers["move"] = process_lead;
update_handlers["bid"] = process_bid;
update_handlers["hand"] = process_hand;
update_handlers["start.bidding"] = kick_bidding;
update_handlers["start.play"] = kick_play;
update_handlers["end.play"] = end_play;

function on_body_load() {
    $("body").ajaxError(ajaxErrorHandler);
    $(document.documentElement).keypress(updator)
}

function updator(event) {
    if (event.charCode == 32) {
	get_json();
    }
}

function get_json() {
    $.getJSON("update.json", function(data){$.each(data, process_update);});
}

function process_update(i, data) {
    handler = update_handlers[data.type];
    if (handler == undefined) {
	window.alert("action " + data.type + " is not yet supported!");
    } else {
	handler(data.value);
    }
}

function process_hand(v) {
    var player = v.player;
    var cards = v.cards;
    // var suits = v.suits;
    // $.each(suits, function(i, suit){load_suit(player, suit)});
    load_hand(player, cards);
}

function card_sort(c1, c2) {
    if (Math.floor(c1/13) + Math.floor(c2/13) == 1) {
	return c1 - c2;
    } else {
	return c2 - c1;
    }
}

function load_hand(player, cards) {
    var pos = $.inArray(player, player_positions);
    if (pos == 0 || pos == 2) {
	cards.sort(card_sort);
	var h = $("#" + player + "_hand");
	$.each(cards,
	       function(idx, value) {
		   var s = document.createElement("span");
		   $(s).addClass("card")
		       var bg = "url(images/cards.png) " + (value * -71) +  "px 0";
		   $(s).css({"background": bg, "z-index": idx + 1, "left": idx * 7 + "%"});
		   h.append(s);
	       });
    }
}

/* FIXME: remove when card pic used */
function load_suit(player, suit) {
    var s = suit.suit;
    var cards = suit.cards;
    var divid = "#" + player + "_" + s;
    var card_str = cards.replace(/([2-9JQKA]|10)/g, "
$1
");
    $(divid).html(card_str);
}

function process_bid(v) {
	var side = v.side;
	var bid = v.bid;
	var dbl_rdbl_allowed = v.dbl_mode;
	prohibit_bid("#bid_dbl.clickable");
	prohibit_bid("#bid_rdbl.clickable");
	if (dbl_rdbl_allowed == "dbl") {
	    allow_bid("#bid_dbl:not(.clickable)");
	} else if (dbl_rdbl_allowed == "rdbl") {
	    allow_bid("#bid_rdbl:not(.clickable)");
	}
	var bid_html;
	var idx = $.inArray(bid, pass_dbl_rdbl);
	if (idx == -1) {
	    var r = bid[0];
	    var s = bid[1];
	    if (s != 'Z') {
		var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
		bid_html = r + img;
	    } else {
		bid_html = r + "NT";
	    }

	    disallow_lower_bids(parseInt(r), s);
	} else {
	    bid_html = bid;
	}
	$("#bidding_area tr:last td:eq(" + side + ")").html(bid_html);
	if (side == 3) {
	    $("#bidding_area").append("

")
	}
}

function prohibit_bid(bid_selector) {
    $(bid_selector).unbind("click").removeClass("clickable").addClass("prohibited_bid");
}

function allow_bid(bid_selector) {
    $(bid_selector).bind("click", do_bid).addClass("clickable").removeClass("prohibited_bid");
}

function disallow_lower_bids(r, s) {
    var bid_id = "bid_" + r + s;
    var alowed_bids = $(".clickable.bidbox_bid");
    var filtered = alowed_bids.filter(function(index){return this.id <= bid_id});
    filtered.unbind("click").removeClass("clickable").addClass("prohibited_bid");
}

function process_lead(v) {
    if (lead_count % 4 == 0) {
	for (var i = 0; i < 4; i += 1) {
	    $("#" + player_positions[i] + "_lead").html(" ");
   	}
    }

    var player = v.player;
    var suit = v.suit;
    var rank = v.rank;
    var next = v.next;
    var allowed = v.allowed;
    if (allowed == null) {
	allowed = "any";
    }
    var card_div_id = "#" + suit + "_" + rank;
    $(card_div_id).detach();
    var lead_div_id = "#" + player + "_lead";
    $(lead_div_id).html(img_by_suit(suit) + rank);
    var np;
    if (next == null) {
	np = next_player(player);
    } else {
	var idx = $.inArray(next, player_positions);
	if (idx % 2 == 1) {
	    $("#their_tricks").text(trick_inc);
	} else {
	    $("#our_tricks").text(trick_inc);
	}
	np = next;
    }
    var np_class = ".card_" + np;
    $(".card").unbind("click").removeClass("clickable");
    if (allowed == 'any') {
	$(np_class).bind("click", np, do_lead).addClass("clickable");
    } else {
	var np_suit_class = np_class + "_" + allowed;
	$(np_suit_class).bind("click", np, do_lead).addClass("clickable");
    }
    lead_count += 1;
}

function next_player(player) {
    var idx = $.inArray(player, player_positions);
    if (idx == 3) {
	return player_positions[0];
    } else {
	return player_positions[idx + 1];
    }
}

function do_lead(event) {
    var player = event.data;
    var splitted_id = event.target.id.split("_");
    var suit = splitted_id[0];
    var rank = splitted_id[1];
    var url = "action.json?move/" + player + "/" + suit + "/" + rank;
    $.post(url);
}

function ajaxErrorHandler(event, xhr, opts, error) {
    // retry should be here for some requests
    window.alert("request failed");
}

function img_by_suit(suit) {
    var c = suit.charAt(0);
    return suit_image_template.replace("{suit}", c.toLowerCase()).replace("{alt_suit}", c.toUpperCase());
}

function kick_bidding(v) {
    $(".bidbox_bid,.bidbox_pass").bind("click", do_bid).addClass("clickable");
    prohibit_bid("#bid_dbl");
    prohibit_bid("#bid_rdbl");
    current_bidder = v.dealer;
    if (v.vuln & 1) {
	$(".vuln_NS").addClass("vulnerable");
    }

    if (v.vuln & 2) {
	$(".vuln_EW").addClass("vulnerable");
    }

    side = sides[v.dealer];
    $("#dealer_" + side).addClass("dealer");

}

function kick_play(v) {
    var contract = v.contract;
    var lead_maker = v.lead;
    var player = player_positions[lead_maker];
    lead_count = 0;
    $(".bidbox").addClass("hidden").after($("#bidding_area").detach());

    $("#lead_area").removeClass("hidden");
    $(".card_" + player).bind("click", player, do_lead).addClass("clickable");
    var csuit = contract[1];
    var cntrct_html;
    if (csuit != "Z") {
	cntrct_html = contract[0] +
	    big_suit_image_template.replace("{suit}", csuit.toLowerCase())
	    .replace("{alt_suit}", csuit.toUpperCase());;
    } else {
	cntrct_html = contract[0] + "NT";
    }
    $("#contract").html(cntrct_html + contract.substr(2, 2));
}

function do_bid(event) {
    var splitted_id = event.currentTarget.id.split("_");
    var bid = splitted_id[1];

    var url = "action.json?bid/" + player_positions[current_bidder] + "/" + bid;
    current_bidder = (current_bidder + 1) % 4;
    $.post(url);
}

function trick_inc(i, s) {
    if (s.length == 0) {
	return 1;
    } else {
	return parseInt(s) + 1;
    }
}

function end_play(v) {
    $(".vuln_NS,.vuln_EW").removeClass("vulnerable");
    $("#dealer_N,#dealer_E,#dealer_S,#dealer_W").removeClass("dealer");
    $("#bidding_area,.bidbox").removeClass("hidden");
    $("#lead_area").addClass("hidden");
    $("#contract,.tricks").html("");
    $("#bidding_area tr:gt(1)").remove();
    $("#bidding_area tr:gt(0) td").text("");
    $(".bidbox_bid,.bidbox_pass,.bidbox_dbl,.bidbox_rdbl")
	.unbind("click").removeClass("prohibited_bid clickable");
    $(".lead").text("");
    $("#lead_area").before($("#bidding_area").detach());
    var contract = v.contract;
    var decl = v.declearer;
    var points = v.points;
    var tricks = v.tricks;
    var url = v.protocol_url;
    var sign = "";
    if (points > 0) {
	sign = "+";
    }
    var contract_html;
    var r = contract[0];
    var s = contract[1];
    if (s != 'Z') {
	var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
	contract_html = r + img;
    } else {
	contract_html = r + "NT";
    }
    contract_html += contract.substr(2, 2);
    $("#popup_res").html("" +  tricks
			 + " tricks, " + sign + points + "");
    $("#popup_contract").html(contract_html + " by " + decl);
    $(".popup").bPopup();

}<commit_msg>preliminary display of left/right hands<commit_after>var player_positions = ["part", "right", "own", "left"];
var sides = ["N", "E", "S", "W"];
var suit_image_template = "";
var big_suit_image_template = "";
var update_cnt = 1000;
var pass_dbl_rdbl = ["pass", "dbl", "rdbl"];

var lead_count;
var current_bidder;

var update_handlers = new Array();
update_handlers["move"] = process_lead;
update_handlers["bid"] = process_bid;
update_handlers["hand"] = process_hand;
update_handlers["start.bidding"] = kick_bidding;
update_handlers["start.play"] = kick_play;
update_handlers["end.play"] = end_play;

function on_body_load() {
    $("body").ajaxError(ajaxErrorHandler);
    $(document.documentElement).keypress(updator)
}

function updator(event) {
    if (event.charCode == 32) {
	get_json();
    }
}

function get_json() {
    $.getJSON("update.json", function(data){$.each(data, process_update);});
}

function process_update(i, data) {
    handler = update_handlers[data.type];
    if (handler == undefined) {
	window.alert("action " + data.type + " is not yet supported!");
    } else {
	handler(data.value);
    }
}

function process_hand(v) {
    var player = v.player;
    var cards = v.cards;
    // var suits = v.suits;
    // $.each(suits, function(i, suit){load_suit(player, suit)});
    load_hand(player, cards);
}

function card_sort(c1, c2) {
    if (Math.floor(c1/13) + Math.floor(c2/13) == 1) {
	return c1 - c2;
    } else {
	return c2 - c1;
    }
}

function load_hand(player, cards) {
    var pos = $.inArray(player, player_positions);
    cards.sort(card_sort);
    var h = $("#" + player + "_hand");
    if (pos == 0 || pos == 2) {
	$.each(cards,
	       function(idx, value) {
		   var s = document.createElement("span");
		   $(s).addClass("card")
		       var bg = "url(images/cards.png) " + (value * -71) +  "px 0";
		   $(s).css({"background": bg, "z-index": idx + 1, "left": idx * 7 + "%"});
		   h.append(s);
	       });
    } else {
	var old_suit = Math.floor(cards[0]/13);
	var voffset = 0;
	var hoffset = -7;
	var hoffset_diff = 7;
	var z = 0;
	for (var i = 0; i < cards.length; i += 1) {
	    var c = cards[i];
	    var new_suit = Math.floor(c/13)
	    if (old_suit != new_suit) {
		voffset += 35;
		hoffset = 0;
		old_suit = new_suit;
		hoffset_diff += 1;
	    } else {
		hoffset += hoffset_diff;
	    }
	    z += 1;
	    var s = document.createElement("span");
	    $(s).addClass("card")
		var bg = "url(images/cards.png) " + (c * -71) +  "px 0";
	    $(s).css({"background": bg, "z-index": z, "left":  hoffset + "%", "top": voffset + "%"});
	    h.append(s);
	}
    }
}

function process_bid(v) {
	var side = v.side;
	var bid = v.bid;
	var dbl_rdbl_allowed = v.dbl_mode;
	prohibit_bid("#bid_dbl.clickable");
	prohibit_bid("#bid_rdbl.clickable");
	if (dbl_rdbl_allowed == "dbl") {
	    allow_bid("#bid_dbl:not(.clickable)");
	} else if (dbl_rdbl_allowed == "rdbl") {
	    allow_bid("#bid_rdbl:not(.clickable)");
	}
	var bid_html;
	var idx = $.inArray(bid, pass_dbl_rdbl);
	if (idx == -1) {
	    var r = bid[0];
	    var s = bid[1];
	    if (s != 'Z') {
		var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
		bid_html = r + img;
	    } else {
		bid_html = r + "NT";
	    }

	    disallow_lower_bids(parseInt(r), s);
	} else {
	    bid_html = bid;
	}
	$("#bidding_area tr:last td:eq(" + side + ")").html(bid_html);
	if (side == 3) {
	    $("#bidding_area").append("

")
	}
}

function prohibit_bid(bid_selector) {
    $(bid_selector).unbind("click").removeClass("clickable").addClass("prohibited_bid");
}

function allow_bid(bid_selector) {
    $(bid_selector).bind("click", do_bid).addClass("clickable").removeClass("prohibited_bid");
}

function disallow_lower_bids(r, s) {
    var bid_id = "bid_" + r + s;
    var alowed_bids = $(".clickable.bidbox_bid");
    var filtered = alowed_bids.filter(function(index){return this.id <= bid_id});
    filtered.unbind("click").removeClass("clickable").addClass("prohibited_bid");
}

function process_lead(v) {
    if (lead_count % 4 == 0) {
	for (var i = 0; i < 4; i += 1) {
	    $("#" + player_positions[i] + "_lead").html(" ");
   	}
    }

    var player = v.player;
    var suit = v.suit;
    var rank = v.rank;
    var next = v.next;
    var allowed = v.allowed;
    if (allowed == null) {
	allowed = "any";
    }
    var card_div_id = "#" + suit + "_" + rank;
    $(card_div_id).detach();
    var lead_div_id = "#" + player + "_lead";
    $(lead_div_id).html(img_by_suit(suit) + rank);
    var np;
    if (next == null) {
	np = next_player(player);
    } else {
	var idx = $.inArray(next, player_positions);
	if (idx % 2 == 1) {
	    $("#their_tricks").text(trick_inc);
	} else {
	    $("#our_tricks").text(trick_inc);
	}
	np = next;
    }
    var np_class = ".card_" + np;
    $(".card").unbind("click").removeClass("clickable");
    if (allowed == 'any') {
	$(np_class).bind("click", np, do_lead).addClass("clickable");
    } else {
	var np_suit_class = np_class + "_" + allowed;
	$(np_suit_class).bind("click", np, do_lead).addClass("clickable");
    }
    lead_count += 1;
}

function next_player(player) {
    var idx = $.inArray(player, player_positions);
    if (idx == 3) {
	return player_positions[0];
    } else {
	return player_positions[idx + 1];
    }
}

function do_lead(event) {
    var player = event.data;
    var splitted_id = event.target.id.split("_");
    var suit = splitted_id[0];
    var rank = splitted_id[1];
    var url = "action.json?move/" + player + "/" + suit + "/" + rank;
    $.post(url);
}

function ajaxErrorHandler(event, xhr, opts, error) {
    // retry should be here for some requests
    window.alert("request failed");
}

function img_by_suit(suit) {
    var c = suit.charAt(0);
    return suit_image_template.replace("{suit}", c.toLowerCase()).replace("{alt_suit}", c.toUpperCase());
}

function kick_bidding(v) {
    $(".bidbox_bid,.bidbox_pass").bind("click", do_bid).addClass("clickable");
    prohibit_bid("#bid_dbl");
    prohibit_bid("#bid_rdbl");
    current_bidder = v.dealer;
    if (v.vuln & 1) {
	$(".vuln_NS").addClass("vulnerable");
    }

    if (v.vuln & 2) {
	$(".vuln_EW").addClass("vulnerable");
    }

    side = sides[v.dealer];
    $("#dealer_" + side).addClass("dealer");

}

function kick_play(v) {
    var contract = v.contract;
    var lead_maker = v.lead;
    var player = player_positions[lead_maker];
    lead_count = 0;
    $(".bidbox").addClass("hidden").after($("#bidding_area").detach());

    $("#lead_area").removeClass("hidden");
    $(".card_" + player).bind("click", player, do_lead).addClass("clickable");
    var csuit = contract[1];
    var cntrct_html;
    if (csuit != "Z") {
	cntrct_html = contract[0] +
	    big_suit_image_template.replace("{suit}", csuit.toLowerCase())
	    .replace("{alt_suit}", csuit.toUpperCase());;
    } else {
	cntrct_html = contract[0] + "NT";
    }
    $("#contract").html(cntrct_html + contract.substr(2, 2));
}

function do_bid(event) {
    var splitted_id = event.currentTarget.id.split("_");
    var bid = splitted_id[1];

    var url = "action.json?bid/" + player_positions[current_bidder] + "/" + bid;
    current_bidder = (current_bidder + 1) % 4;
    $.post(url);
}

function trick_inc(i, s) {
    if (s.length == 0) {
	return 1;
    } else {
	return parseInt(s) + 1;
    }
}

function end_play(v) {
    $(".vuln_NS,.vuln_EW").removeClass("vulnerable");
    $("#dealer_N,#dealer_E,#dealer_S,#dealer_W").removeClass("dealer");
    $("#bidding_area,.bidbox").removeClass("hidden");
    $("#lead_area").addClass("hidden");
    $("#contract,.tricks").html("");
    $("#bidding_area tr:gt(1)").remove();
    $("#bidding_area tr:gt(0) td").text("");
    $(".bidbox_bid,.bidbox_pass,.bidbox_dbl,.bidbox_rdbl")
	.unbind("click").removeClass("prohibited_bid clickable");
    $(".lead").text("");
    $("#lead_area").before($("#bidding_area").detach());
    var contract = v.contract;
    var decl = v.declearer;
    var points = v.points;
    var tricks = v.tricks;
    var url = v.protocol_url;
    var sign = "";
    if (points > 0) {
	sign = "+";
    }
    var contract_html;
    var r = contract[0];
    var s = contract[1];
    if (s != 'Z') {
	var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
	contract_html = r + img;
    } else {
	contract_html = r + "NT";
    }
    contract_html += contract.substr(2, 2);
    $("#popup_res").html("" +  tricks
			 + " tricks, " + sign + points + "");
    $("#popup_contract").html(contract_html + " by " + decl);
    $(".popup").bPopup();

}<|endoftext|>


<commit_before>var config = {
	'bgColor': 0
};

$(document).ready(function() {

	console.log("Document Ready");

	// Init
	var bgColorPicker = $('#bgColorPicker')[0];

	// Check local storage
    if(localStorage['bgColor']) {
      bgColorPicker.value = localStorage['bgColor'];
    }

	$('#send').on('click', function() {
		// Set options
		config.bgColor = bgColorPicker.value;

		// Store values
		localStorage['bgColor'] = options['bgColor'];

		// Close config page and return data
		location.href = 'pebblejs://close#' + encodeURIComponent(JSON.stringify(config));
	});

});<commit_msg>Cleanup + var name fix<commit_after>var config = {
	'bgColor': 0
};

$(document).ready(function() {

	console.log("Document Ready");

	// Init
	var bgColorPicker = $('#bgColorPicker')[0];

	// Check local storage
    if(localStorage.bgColor) {
      bgColorPicker.value = localStorage.bgColor;
    }

	$('#send').on('click', function() {
		// Set options
		config.bgColor = bgColorPicker.value;

		// Store values
		localStorage.bgColor = config.bgColor;

		// Close config page and return data
		location.href = 'pebblejs://close#' + encodeURIComponent(JSON.stringify(config));
	});

});<|endoftext|>


<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() {
var 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
            var result = document.getElementsByClassName('imageItem')[i];
                input.onblur = function () {
                    $('.image').on('click', function(event) {
                        this.value = '';
                        for (i = 0; i < images.length; i++) {
                            document.querySelectorAll('.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.
 */

$(document).ready(function() {
    //Global letiables
    let image =         document.getElementsByClassName('image');
    let imageItem =     document.getElementsByClassName('imageItem');
    let headerText =    document.getElementsByClassName('imageTitle');
    let captionText =   document.getElementsByClassName('imageText');
    let $imageIndex = 0;
    let lightbox;

    $('.gallery').addClass('intro2');
    $('.imageItem').addClass('intro'); // todo: add to onclick()

    $('.imageItem').on('click', '.image', function(event)  {
        event.preventDefault();
        $('.gallery').hide();
        $imageIndex = $(this);
       overlayElements();
        open();
        exit();
        // todo: add functions to buttons

       next();
        previous();
    }); // end imageItem click

    function open() {
    $('body').append(lightbox.background)
        .append(lightbox.exit)
        .append(lightbox.title)
        .append(lightbox.largeImage)
        .append(lightbox.next)
        .append(lightbox.previous)
        .append(lightbox.caption);
        $('.overlayBackground').css({
            'background-image': 'url('+ largeImagePath($imageIndex) +')'
        });
    }

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

'),
            wrapper:   $('

'),
            overlay:    $('

'),
            previous:   $(''),
            next:       $(''),
            exit:       $(''),
            largeImage: $(''),
            title:      $('
' + $imageIndex[0].previousElementSibling.innerHTML + '
'),
            caption:    $('
' + $imageIndex[0].nextElementSibling.innerHTML + '
')
        };
    }

    function exit() {
        $(document).on('click', '#closeButton', function()  {
            $(lightbox.background).remove();
            $(lightbox.largeImage).remove();
            $('#heading').remove();
            $("#closeButton").empty();
            $('#closeButton').remove();
            $('#nextButton').remove();
            $('#previousButton').remove();
            $('#caption').remove();
            $('.gallery').show();
        });// end #closeButton click
    }
    function next() {
        $(document).on('click', '#nextButton',function()  {
            alert('next');
        });// end #nextButton click
    }
    function previous() {
        $(document).on('click', '#previousButton',function()  {
            alert('previous');
        });// end #previousButton click
    }

    // string replace image path
    function largeImagePath(path) {
        let imagePath = 'img/thumbnails/';
        let newImagePath = 'img/';
        path =  $imageIndex[0].src;
        return path.replace(imagePath, newImagePath);
    }
}); // EOF

<commit_msg>trying to workout an index value in order to set next and previous button 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() {
var 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
            var result = document.getElementsByClassName('imageItem')[i];
                input.onblur = function () {
                    $('.image').on('click', function(event) {
                        this.value = '';
                        for (i = 0; i < images.length; i++) {
                            document.querySelectorAll('.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.
 */

$(document).ready(function() {
    let $imageIndex, lightbox;

    $('.gallery').addClass('intro2');
    $('.imageItem').addClass('intro'); // todo: add to onclick()

    $('.imageItem').on('click', '.image', function(event)  {
        event.preventDefault();
        $imageIndex = $(this);
       overlayElements();
        open();
        exit();
        next();
        previous();
    }); // end imageItem click

    function open() {
    $('body').append(lightbox.background)
        .append(lightbox.exit)
        .append(lightbox.title)
        .append(lightbox.largeImage)
        .append(lightbox.next)
        .append(lightbox.previous)
        .append(lightbox.caption);
    $('.gallery').hide();
        $('.overlayBackground').css({
            'background-image': 'url('+ largeImagePath($imageIndex) +')'
        });
    }

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

'),
            overlay:    $('

'),
            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>'),
            largeImage: $(''),
            title:      $('
' + $imageIndex[0].previousElementSibling.innerHTML + '
'),
            caption:    $('
' + $imageIndex[0].nextElementSibling.innerHTML + '
')
        };
    }

    function exit() {
        $(document).on('click', '#closeButton', function()  {
            lightbox.background.remove()
            lightbox.caption.remove();
            lightbox.title.remove()
            lightbox.largeImage.remove()
            $('#closeButton').remove()
            $('#nextButton').remove()
            $('#previousButton').remove()

            $('.gallery').show();
        });// end #closeButton click
    }

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

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

    // string replace image path
    function largeImagePath(path) {
        let imagePath = 'img/thumbnails/';
        let newImagePath = 'img/';
        path =  $imageIndex[0].src;
        return path.replace(imagePath, newImagePath);
    }
}); // EOF

<|endoftext|>


<commit_before>var FakePebble = (function () {

  var _Pebble = null;
  var eventListeners = {
    ready: [],
    appmessage: [],
    webviewclosed: []
  };
  var eventHandlers = {
    appmessage: [],
    notifications: []
  };

  return {
    addEventListener: addEventListener,
    sendAppMessage: sendAppMessage,
    showSimpleNotificationOnPebble: showSimpleNotificationOnPebble,
    getAccountToken: getAccountToken,
    openURL: openURL,

    reset: reset,
    inject: inject,
    restore: restore,
    on: on
  };

  function addEventListener(event, callback) {
    if (eventListeners[event]) {
      eventListeners[event].push(callback);
    }
  }

  function sendAppMessage(message, ack, nack) {
    var _arguments = Array.prototype.slice.call(arguments);
    eventHandlers.appmessage.forEach(function (handler) {
      handler.apply(null, _arguments);
    });
  }

  function showSimpleNotificationOnPebble(title, text) {
    var _arguments = Array.prototype.slice.call(arguments);
    eventHandlers.notifications.forEach(function (handler) {
      handler.apply(null, _arguments);
    });
  }

  function getAccountToken() {
    return '';
  }

  function openURL(url) {
  }

  function reset() {
    eventListeners.ready = [];
    eventListeners.appmessage = [];
    eventListeners.webviewclosed = [];
    eventHandlers.appmessage = [];
    eventHandlers.notifications = [];
  }

  function inject() {
    if (_Pebble !== null) {
      return;
    }
    if (typeof(Pebble) !== 'undefined') {
      _Pebble = Pebble;
    }
    Pebble = this;
  }

  function restore() {
    if (_Pebble === null) {
      return;
    }
    Pebble = _Pebble;
    _Pebble = null;
  }

  function on(event, callback) {
    eventHandlers[event].push(callback);
  }

}());<commit_msg>Add more functionality to the FakePebble object.<commit_after>var FakePebble = (function () {

  var _Pebble = null;

  var eventListeners = {
    ready: [],
    appmessage: [],
    webviewclosed: []
  };

  var eventHandlers = {
    appmessage: [],
    notifications: [],
    url: []
  };

  return {
    addEventListener: addEventListener,
    sendAppMessage: sendAppMessage,
    showSimpleNotificationOnPebble: showSimpleNotificationOnPebble,
    getAccountToken: getAccountToken,
    openURL: openURL,

    reset: reset,
    inject: inject,
    restore: restore,
    on: on
  };

  function addEventListener(event, callback) {
    if (eventListeners[event]) {
      eventListeners[event].push(callback);
    }
  }

  function sendAppMessage(message, ack, nack) {
    var _arguments = Array.prototype.slice.call(arguments);
    eventHandlers.appmessage.forEach(function (handler) {
      handler.apply(null, _arguments);
    });
  }

  function showSimpleNotificationOnPebble(title, text) {
    var _arguments = Array.prototype.slice.call(arguments);
    eventHandlers.notifications.forEach(function (handler) {
      handler.apply(null, _arguments);
    });
  }

  function getAccountToken() {
    return '';
  }

  function openURL(url) {
    eventHandlers.openurl.forEach(function (handler) {
      handler(url);
    });
  }

  function reset() {
    eventListeners.ready = [];
    eventListeners.appmessage = [];
    eventListeners.webviewclosed = [];
    eventHandlers.appmessage = [];
    eventHandlers.notifications = [];
  }

  function inject() {
    if (_Pebble !== null) {
      return;
    }
    if (typeof(Pebble) !== 'undefined') {
      _Pebble = Pebble;
    }
    Pebble = this;
  }

  function restore() {
    if (_Pebble === null) {
      return;
    }
    Pebble = _Pebble;
    _Pebble = null;
  }

  function on(event, callback) {
    eventHandlers[event].push(callback);
  }

}());<|endoftext|>


<commit_before>// npm dependencies
//
import React from 'react';
import isArray from 'lodash/isArray';
import flatMap from 'lodash/flatMap';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

/**
 * The Dropdown component
 */
class Dropdown extends React.Component {
    /**
     * Construct the component instance
     * @param  {Object} props The component props
     */
    constructor(props) {
        super(props);

        // generate a unique ID for this instance
        //
        this.id = props.id || uniqueId('form-dropdown-');

        // do we have a value? if not, then we need call onChange (if it exists)
        // with the first option to ensure that the value is set
        //
        if (!props.value && props.onChange) {
            // is the list of options an array?
            //
            if (isArray(props.options)) {
                // yes - return the value of the first item (if we have one)
                //
                if (props.options.length > 0) {
                    props.onChange(props.options[0].value);
                }
            } else {
                // no - return the value of the first item in the first property
                // (if there is one)
                //
                const keys = Object.keys(props.options);

                if (keys.length > 0) {
                    props.onChange(props.options[keys[0]][0].value);
                }
            }
        }

        // bind `this` to the event handlers
        //
        this.isValid = this.isValid.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    /**
     * Handle the `onChange` event for the select element
     * @param  {Object} event The event object
     */
    onChange(event) {
        // do we have an onChange handler? if so, call it with the appropriate
        // value
        //
        if (this.props.onChange) {
            // figure out which value to use
            //
            let value = this.isValid(event.target.value)
                ? event.target.value
                : '';

            if (this.props.options[0] && !value) {
                value = this.props.options[0].value;
            }

            // call the onChange handler with the value
            //
            this.props.onChange(value);
        }
    }

    /**
     * Get the list of options as a flat array
     * @return {Array} The list of options
     */
    getOptionsList() {
        // is it an array? if so, return it; otherwise, map it to a flat array
        //
        return isArray(this.props.options)
            ? this.props.options
            : flatMap(this.props.options, (opt) => opt);
    }

    /**
     * Determine if a value is valid (ie. in the list of options)
     * @param  {String}  The value to check
     * @return {Boolean} True if the value is valid (ie. found in the array of
     *                   options); false otherwise
     */
    isValid(value = this.props.value) {
        return this.getOptionsList().findIndex((opt) => `${opt.value}` === `${value}`) !== -1;
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        // figure out what value to display
        //
        let value = this.isValid() ? this.props.value : '';
        if (this.props.options[0] && !value) {
            value = this.props.options[0].value;
        }

        // generate the label for the component
        //
        const label = this.props.label
            ? (
            <label
                htmlFor={this.id}
                className={classnames('control-label', {
                    [`col-xs-${this.context.labelColumns}`]: this.context.labelColumns,
                })}
            >
                {this.props.label}

            )
            : null;

        // build the options
        //
        let options = null;

        // is the list of options an array or an object?
        //
        if (isArray(this.props.options)) {
            // it's an array - simply map it to a list of <option> elements
            //
            options = this.props.options.map((opt) => {
                return (
                    <option key={uniqueId('form-dropdown-option-')} value={opt.value || opt}>
                        {opt.name || opt}
                    </option>
                );
            });
        } else {
            // it's an object - build a list of options, separated into
            // optgroups by key
            //
            options = [];

            Object.keys(this.props.options).forEach((key) => {
                options.push(
                    <optgroup key={uniqueId('form-dropdown-optgroup-')} label={key}>
                        {this.props.options[key].map((opt) => (
                            <option key={uniqueId('form-dropdown-option-')} value={opt.value || opt}>
                                {opt.name || opt}
                            </option>))
                        }
                    </optgroup>
                );
            });
        }

        // generate the select element for the component
        //
        let select = (
            <select
                id={this.id}
                name={this.props.name}
                disabled={!!this.props.disabled}
                className="form-control"
                value={value}
                onChange={this.onChange}
            >
                {options}
            </select>
        );

        // do we have columns for this component? if so, wrap the select element
        // in a div to implement those columns
        //
        if (this.context.labelColumns) {
            select = (
                <div
                    className={classnames(
                        'form-dropdown-columns',
                        `col-xs-${12 - this.context.labelColumns}`
                    )}
                >
                    {select}

            );
        }

        // return the component
        //
        return label
            ?
{label}{select}

            : select;
    }
}

/**
 * The property types for the component
 * @type {Object}
 */
Dropdown.propTypes = {
    /** A flag to indicated whether this component is disabled */
    disabled: React.PropTypes.bool,
    /** The ID for the component */
    id:       React.PropTypes.string,
    /** The label for the checkbox group */
    label:    React.PropTypes.string,
    /** The name for the select element */
    name:     React.PropTypes.string,
    /** The selected value */
    value:    React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ]),
    /** The options for the dropdown */
    options:  React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.object,
    ]).isRequired,
    /** The 'onChange' handler for the component */
    onChange: React.PropTypes.func,
};

/**
 * The context types for the component
 * @type {Object}
 */
Dropdown.contextTypes = {
    labelColumns: React.PropTypes.number,
};

// export the component
//
export default Dropdown;
<commit_msg>code cleanup<commit_after>// npm dependencies
//
import React from 'react';
import isArray from 'lodash/isArray';
import flatMap from 'lodash/flatMap';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

/**
 * The Dropdown component
 */
class Dropdown extends React.Component {
    /**
     * Construct the component instance
     * @param  {Object} props The component props
     */
    constructor(props) {
        super(props);

        // generate a unique ID for this instance
        //
        this.id = props.id || uniqueId('form-dropdown-');

        // do we have a value? if not, then we need call onChange (if it exists)
        // with the first option to ensure that the value is set
        //
        if (!props.value && props.onChange) {
            // is the list of options an array?
            //
            if (isArray(props.options)) {
                // yes - return the value of the first item (if we have one)
                //
                if (props.options.length > 0) {
                    props.onChange(props.options[0].value);
                }
            } else {
                // no - return the value of the first item in the first property
                // (if there is one)
                //
                const keys = Object.keys(props.options);

                if (keys.length > 0) {
                    props.onChange(props.options[keys[0]][0].value);
                }
            }
        }

        // bind `this` to the event handlers
        //
        this.isValid = this.isValid.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    /**
     * Handle the `onChange` event for the select element
     * @param  {Object} event The event object
     */
    onChange(event) {
        // do we have an onChange handler? if so, call it with the appropriate
        // value
        //
        if (this.props.onChange) {
            // figure out which value to use
            //
            let value = this.isValid(event.target.value)
                ? event.target.value
                : '';

            if (this.props.options[0] && !value) {
                value = this.props.options[0].value;
            }

            // call the onChange handler with the value
            //
            this.props.onChange(value);
        }
    }

    /**
     * Get the list of options as a flat array
     * @return {Array} The list of options
     */
    getOptionsList() {
        // is it an array? if so, return it; otherwise, map it to a flat array
        //
        return isArray(this.props.options)
            ? this.props.options
            : flatMap(this.props.options, (opt) => opt);
    }

    /**
     * Determine if a value is valid (ie. in the list of options)
     * @param  {String}  The value to check
     * @return {Boolean} True if the value is valid (ie. found in the array of
     *                   options); false otherwise
     */
    isValid(value = this.props.value) {
        return this.getOptionsList().findIndex((opt) => `${opt.value}` === `${value}`) !== -1;
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        // figure out what value to display
        //
        let value = this.isValid() ? this.props.value : '';
        if (this.props.options[0] && !value) {
            value = this.props.options[0].value;
        }

        // generate the label for the component
        //
        const label = this.props.label
            ? (
            <label
                htmlFor={this.id}
                className={classnames('control-label', {
                    [`col-xs-${this.context.labelColumns}`]: this.context.labelColumns,
                })}
            >
                {this.props.label}

            )
            : null;

        // build the options
        //
        let options = null;

        // is the list of options an array or an object?
        //
        if (isArray(this.props.options)) {
            // it's an array - simply map it to a list of <option> elements
            //
            options = this.props.options.map((opt) => {
                return (
                    <option key={uniqueId('form-dropdown-option-')} value={opt.value || opt}>
                        {opt.name || opt}
                    </option>
                );
            });
        } else {
            // it's an object - build a list of options, separated into
            // optgroups by key
            //
            options = [];

            Object.keys(this.props.options).forEach((key) => {
                options.push(
                    <optgroup key={uniqueId('form-dropdown-optgroup-')} label={key}>
                        {this.props.options[key].map((opt) => (
                            <option
                                key={uniqueId('form-dropdown-option-')}
                                value={opt.value || opt}
                            >{opt.name || opt}</option>)
                        )}
                    </optgroup>
                );
            });
        }

        // generate the select element for the component
        //
        let select = (
            <select
                id={this.id}
                name={this.props.name}
                disabled={!!this.props.disabled}
                className="form-control"
                value={value}
                onChange={this.onChange}
            >
                {options}
            </select>
        );

        // do we have columns for this component? if so, wrap the select element
        // in a div to implement those columns
        //
        if (this.context.labelColumns) {
            select = (
                <div
                    className={classnames(
                        'form-dropdown-columns',
                        `col-xs-${12 - this.context.labelColumns}`
                    )}
                >
                    {select}

            );
        }

        // return the component
        //
        return label
            ?
{label}{select}

            : select;
    }
}

/**
 * The property types for the component
 * @type {Object}
 */
Dropdown.propTypes = {
    /** A flag to indicated whether this component is disabled */
    disabled: React.PropTypes.bool,
    /** The ID for the component */
    id:       React.PropTypes.string,
    /** The label for the checkbox group */
    label:    React.PropTypes.string,
    /** The name for the select element */
    name:     React.PropTypes.string,
    /** The selected value */
    value:    React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.number,
    ]),
    /** The options for the dropdown */
    options:  React.PropTypes.oneOfType([
        React.PropTypes.array,
        React.PropTypes.object,
    ]).isRequired,
    /** The 'onChange' handler for the component */
    onChange: React.PropTypes.func,
};

/**
 * The context types for the component
 * @type {Object}
 */
Dropdown.contextTypes = {
    labelColumns: React.PropTypes.number,
};

// export the component
//
export default Dropdown;
<|endoftext|>


<commit_before>import test from 'ava';
import processCss from './_processCss';

test(
    'should prefer double quotes by default',
    processCss,
    `p:after {
        content: ""
    }`,
    `p:after{content:""}`
);

test(
    'should transform single quotes to double quotes by default',
    processCss,
    `p:after {
        content: ''
    }`,
    `p:after{content:""}`
);

test(
    'should transform double quotes to single quotes via an option',
    processCss,
    `p:after {
        content: ""
    }`,
    `p:after{content:''}`,
    {normalizeString: {preferredQuote: 'single'}}
);

test(
    'should keep single quotes inside a double quoted string intact',
    processCss,
    `p:after {
        content: "'string' is intact"
    }`,
    `p:after{content:"'string' is intact"}`
);

test(
    'should keep double quotes inside a single quoted string intact',
    processCss,
    `p:after {
        content: '"string" is intact'
    }`,
    `p:after{content:'"string" is intact'}`
);

test(
    'should transform escaped single quotation marks if possible',
    processCss,
    `p:after {
        content: '\\'string\\' is intact'
    }`,
    `p:after{content:"'string' is intact"}`
);

test(
    'should transform escaped double quotation marks if possible',
    processCss,
    `p:after {
        content: "\\"string\\" is intact"
    }`,
    `p:after{content:'"string" is intact'}`
);

test(
    'should not transform quotation marks when mixed',
    processCss,
    `p:after {
        content: "\\"string\\" is 'intact'"
    }`,
    `p:after{content:"\\"string\\" is 'intact'"}`
);

test(
    'should not transform quotation marks when mixed',
    processCss,
    `p:after {
        content: '"string" is \\'intact\\''
    }`,
    `p:after{content:'"string" is \\'intact\\''}`
);

test(
    'should transform escaped single quotation marks when mixed',
    processCss,
    `p:after {
        content: '\\'string\\' is \\"intact\\"'
    }`,
    `p:after{content:'\\'string\\' is "intact"'}`
);

test(
    'should transform escaped double quotation marks when mixed',
    processCss,
    `p:after {
        content: "\\'string\\' is \\"intact\\""
    }`,
    `p:after{content:"'string' is \\"intact\\""}`
);

test(
    'should work with the attr function',
    processCss,
    `p:after {
        content: '(' attr(href) ')'
    }`,
    `p:after{content:"(" attr(href) ")"}`
);

/*
 * The whitespace here is kept because it might influence the design
 * e.g. through `white-space: pre;`
 */

test(
    'should join multiple line strings',
    processCss,
    `p:after {
        content: " > this is some really\\
                     long text which is broken\\
                     over several lines.";
    }`,
    `p:after{content:" > this is some really                     long text which is broken                     over several lines."}`
);

test(
    'should work with quotes',
    processCss,
    `q {
        quotes: '«' "»"
    }`,
    `q{quotes:"«" "»"}`
);

test(
    'should work with language overrides',
    processCss,
    `p {
        font-language-override: 'DAN'
    }`,
    `p{font-language-override:"DAN"}`
);

test(
    'should work with css grids',
    processCss,
    `p {
        grid-template: 'a a a' "b b b";
    }`,
    `p{grid-template:"a a a" "b b b"}`
);

test(
    'should work with css grids (2)',
    processCss,
    `p {
        grid-template-areas: 'a a a' "b b b";
    }`,
    `p{grid-template-areas:"a a a" "b b b"}`
);

test(
    'should work with list styles',
    processCss,
    `ul {
        list-style-type: '-';
    }`,
    `ul{list-style-type:"-"}`
);

test(
    'should work with text emphasis styles',
    processCss,
    `p {
        text-emphasis-style: '\\25B2';
    }`,
    `p{text-emphasis-style:"\\25B2"}`
);

test(
    'should work with text overflow',
    processCss,
    `p {
        text-overflow: '…' '…';
    }`,
    `p{text-overflow:"…" "…"}`
);

test(
    'should work with font',
    processCss,
    `p {
        font: 1em/1.5 'slab serif';
    }`,
    `p{font:1em/1.5 "slab serif"}`
);

test(
    'should work with font family',
    processCss,
    `p {
        font-family: 'slab serif';
    }`,
    `p{font-family:"slab serif"}`
);

test(
    'should work with font feature settings',
    processCss,
    `p {
        font-feature-settings: 'frac'
    }`,
    `p{font-feature-settings:"frac"}`
);

test(
    'should work with web fonts',
    processCss,
    `@font-face {
        font-family: 'slab serif';
        src: local('slab serif'), url(slab.ttf) format('truetype');
    }`,
    `@font-face{font-family:"slab serif";src:local("slab serif"),url(slab.ttf) format("truetype")}`,
    {discardUnused: false}
);

test(
    'should remove unnecessary backslashes in urls',
    processCss,
    `p{background:url('http://example.com/foo\\\'bar.jpg')}`,
    `p{background:url("http://example.com/foo\'bar.jpg")}`,
    {normalizeUrl: false}
);

test(
    'should remove unnecessary backslashes in urls',
    processCss,
    `p{background:url("http://example.com/foo\\\"bar.jpg")}`,
    `p{background:url('http://example.com/foo\"bar.jpg')}`,
    {normalizeUrl: false}
);

test(
    'should work in attribute selectors',
    processCss,
    `[rel='external link']{color:#00f}`,
    `[rel="external link"]{color:#00f}`,
);

test(
    'should change strings (1)',
    processCss,
    `[a="escaped quotes \\" h1, h1, h1 \\" h1, h1, h1"]{color:#00f}`,
    `[a='escaped quotes " h1, h1, h1 " h1, h1, h1']{color:#00f}`,
);

test(
    'should change strings (2)',
    processCss,
    `[a='escaped quotes \\' h1, h1, h1 \\' h1, h1, h1']{color:#00f}`,
    `[a="escaped quotes ' h1, h1, h1 ' h1, h1, h1"]{color:#00f}`,
);

test(
    'should work for @import',
    processCss,
    `@import url('foo.css')`,
    `@import url("foo.css")`
);
<commit_msg>Remove extraneous test file.<commit_after><|endoftext|>


<commit_before>/*****************************/
/*         sekshi.js         */
/*         by Sooyou         */
/*                           */
/*  Last Modified: 24/11/14  */
/*  by: Sooyou               */
/*****************************/
/* Bot created for We <3 KPOP*/
/*          on plug.dj.      */
/*                           */
/*          join at:         */
/*    play.welovekpop.club   */
/*****************************/

var mongoose = require("mongoose");
var Plugged = require("plugged");
var redis = require("redis");
var nconf = require("nconf");
var path = require("path");
var util = require("util");
var fs = require("fs");

function Sekshi(args) {
    Sekshi.super_.call(this);

    args = args || {};

    this.config = new nconf.Provider();
    this.config.file(args["config"] || "./config.json") ;

    this.modules = [];
    this.modulePath = args["modules"] || "./modules";
    this.delimiter = this.config.get("delimiter") || "!";

    this.loadModulesSync();
}

util.inherits(Sekshi, Plugged);

Sekshi.prototype.start = function() {
    try {
        this.login(this.config.get("credentials"));
    }
    catch (err) {
        console.error(err.message);
        return;
    }

    this.on(this.CONNECTED, function _onConnect() {

        this.connect(this.config.get("room"), function _onRoomJoin(err) {
            if(!err) {
                this.on(this.CHAT, this.onMessage.bind(this));
            } else {
                console.log(err);
                process.exit(1);
            }
        }.bind(this));

    }.bind(this));
};

Sekshi.prototype.stop = function() {
    this.unloadModulesSync();

    this.logout(function _logout() {
        this.off(this.CHAT);
    });
};

Sekshi.prototype.parseArguments = function(str, args) {
    args = args || [];
    str = str || "";
    var length = str.length;
    var compound = false;   //quoted?
    var sarg = false;       //started argument?
    var sidx = 0;           //start index
    var cidx = 0;           //current index

    //instead of apply the rules ([^"]+)"|(\S+) in an regular expression
    //it seemed to be a quicker approach to apply the rules manually
    //old school style.
    //rule1: every non quoted word is a single argument
    //rule2: quoted words are meant to be a single argument
    while(cidx < length) {
        if(!sarg && str[cidx] !== ' ') {

            if(str[cidx] === '"') {
                sidx = ++cidx;
                compound = true;
            } else {
                sidx = cidx;
            }

            sarg = true;
        } else if(sarg && !compound && str[cidx] === ' ') {
            args.push(str.slice(sidx, cidx));
            sarg = false;
        } else if(sarg && compound && str[cidx] === '"') {
            args.push(str.slice(sidx, cidx));
            compound = false;
            sarg = false;
        }

        cidx++;
    }

    if(sarg)
        args.push(str.slice(sidx, cidx));
};

Sekshi.prototype.onMessage = function(msg) {
    if(msg.message.charAt(0) === this.delimiter) {
        this.deleteMessage(msg.cid);

        var self = this;
        var args = [];
        var func = null;

        this.parseArguments(msg.message, args);

        func = args.shift().replace(this.delimiter, '');
        args.unshift(self.getUserByID(msg.id, true));

        for(var i = 0, l = self.modules.length; i < l; i++) {
            if(self.modules[i].enabled && typeof self.modules[i].module[func] === "function") {
                if(args[0].role >= self.modules[i].module.permissions[func])
                    self.modules[i].module[func].apply(self.modules[i].module, args);
                else
                    self.sendChat(['@', msg.username, " you don't have permission to use this command"].join(''), 5*1000);
                break;
            }
        }
    } else {
        console.log([msg.username, ": ", msg.message].join(''));
    }
};

//delimiter used for chat commands
Sekshi.prototype.setDelimiter = function(delimiter) {
    this.delimiter = delimiter;
};

Sekshi.prototype.reloadmodules = function(modulePath) {
    this.unloadModulesSync(modulePath);
    this.loadModulesSync(modulePath);
};

//get array of module files
Sekshi.prototype.getModuleFiles = function(modulePath, modules) {
    if(!fs.existsSync(modulePath)) {
        console.log(modulePath + " does not exist!");
        return [];
    }

    modules = modules || [];
    var stat = fs.statSync(modulePath);

    if(typeof stat === "undefined") {
        console.log("An error occured while fetching the path");
    } else {
        if(stat.isDirectory()) {
            var files = fs.readdirSync(modulePath);

            if(typeof files !== "undefined") {
                for(var i = 0, l = files.length; i < l; i++)
                    this.getModuleFiles(path.join(modulePath, files[i]), modules);
            }

        } else if(stat.isFile()) {
            if(modulePath.slice(modulePath.indexOf('.') + 1) === "module.js")
                modules.push(["./", modulePath].join(''));
        }
    }

    return modules;
};

//load all modules of a base path
Sekshi.prototype.loadModulesSync = function(modulePath) {
    modulePath = modulePath || this.modulePath;

    var moduleFiles = this.getModuleFiles(modulePath);
    var module = null;

    for(var i = 0, l = moduleFiles.length; i < l; i++) {
        module = require(moduleFiles[i]);

        this.modules.push({
            enabled: true,
            module: new module(this)
        });
    }
};

//unload all modules and delete the cached files
Sekshi.prototype.unloadModulesSync = function(modulePath) {
    modulePath = modulePath || this.modulePath;

    for(var i = 0, l = this.modules.length; i < l; i++) {
        if(typeof this.modules[i].module.destroy !== "undefined")
            this.modules[i].module.destroy();
    }

    this.modules = [];
    var moduleFiles = this.getModuleFiles(modulePath);

    for(var i = 0, l = moduleFiles.length; i < l; i++) {
        delete require.cache[path.resolve(moduleFiles[i])];
    }
};

module.exports = Sekshi;<commit_msg>outsourced nconf<commit_after>/*****************************/
/* Bot created for We <3 KPOP*/
/*          on plug.dj.      */
/*                           */
/*          join at:         */
/*    play.welovekpop.club   */
/*****************************/

var ConfigWrapper = require("./configwrapper");
var mongoose = require("mongoose");
var Plugged = require("plugged");
var redis = require("redis");
var path = require("path");
var util = require("util");
var fs = require("fs");

function Sekshi(args) {
    Sekshi.super_.call(this);

    args = args || {};

    this.config = new ConfigWrapper();
    this.config.file(args["config"] || "./config.json");

    this.modules = [];
    this.modulePath = args["modules"] || "./modules";
    this.delimiter = this.config.get("delimiter") || '!';

    this.loadModulesSync();
}

util.inherits(Sekshi, Plugged);

Sekshi.prototype.start = function() {
    try {
        this.login(this.config.get("credentials"));
    }
    catch (err) {
        console.error(err.message);
        return;
    }

    this.on(this.CONNECTED, function _onConnect() {

        this.connect(this.config.get("room"), function _onRoomJoin(err) {
            if(!err) {
                this.on(this.CHAT, this.onMessage.bind(this));
            } else {
                console.log(err);
                process.exit(1);
            }
        }.bind(this));

    }.bind(this));
};

Sekshi.prototype.stop = function() {
    this.unloadModulesSync();

    this.logout(function _logout() {
        this.off(this.CHAT);
    });
};

Sekshi.prototype.parseArguments = function(str, args) {
    args = args || [];
    str = str || "";
    var length = str.length;
    var compound = false;   //quoted?
    var sarg = false;       //started argument?
    var sidx = 0;           //start index
    var cidx = 0;           //current index

    //instead of apply the rules ([^"]+)"|(\S+) in an regular expression
    //it seemed to be a quicker approach to apply the rules manually
    //old school style.
    //rule1: every non quoted word is a single argument
    //rule2: quoted words are meant to be a single argument
    while(cidx < length) {
        if(!sarg && str[cidx] !== ' ') {

            if(str[cidx] === '"') {
                sidx = ++cidx;
                compound = true;
            } else {
                sidx = cidx;
            }

            sarg = true;
        } else if(sarg && !compound && str[cidx] === ' ') {
            args.push(str.slice(sidx, cidx));
            sarg = false;
        } else if(sarg && compound && str[cidx] === '"') {
            args.push(str.slice(sidx, cidx));
            compound = false;
            sarg = false;
        }

        cidx++;
    }

    if(sarg)
        args.push(str.slice(sidx, cidx));
};

Sekshi.prototype.onMessage = function(msg) {
    if(msg.message.charAt(0) === this.delimiter) {
        this.deleteMessage(msg.cid);

        var self = this;
        var args = [];
        var func = null;

        this.parseArguments(msg.message, args);

        func = args.shift().replace(this.delimiter, '');
        args.unshift(self.getUserByID(msg.id, true));

        for(var i = 0, l = self.modules.length; i < l; i++) {
            if(self.modules[i].enabled && typeof self.modules[i].module[func] === "function") {
                if(args[0].role >= self.modules[i].module.permissions[func])
                    self.modules[i].module[func].apply(self.modules[i].module, args);
                else
                    self.sendChat(['@', msg.username, " you don't have permission to use this command"].join(''), 5*1000);
                break;
            }
        }
    } else {
        console.log([msg.username, ": ", msg.message].join(''));
    }
};

//delimiter used for chat commands
Sekshi.prototype.setDelimiter = function(delimiter) {
    this.delimiter = delimiter;
};

Sekshi.prototype.reloadmodules = function(modulePath) {
    this.unloadModulesSync(modulePath);
    this.loadModulesSync(modulePath);
};

//get array of module files
Sekshi.prototype.getModuleFiles = function(modulePath, modules) {
    if(!fs.existsSync(modulePath)) {
        console.log(modulePath + " does not exist!");
        return [];
    }

    modules = modules || [];
    var stat = fs.statSync(modulePath);

    if(typeof stat === "undefined") {
        console.log("An error occured while fetching the path");
    } else {
        if(stat.isDirectory()) {
            var files = fs.readdirSync(modulePath);

            if(typeof files !== "undefined") {
                for(var i = 0, l = files.length; i < l; i++)
                    this.getModuleFiles(path.join(modulePath, files[i]), modules);
            }

        } else if(stat.isFile()) {
            if(modulePath.slice(modulePath.indexOf('.') + 1) === "module.js")
                modules.push(["./", modulePath].join(''));
        }
    }

    return modules;
};

//load all modules of a base path
Sekshi.prototype.loadModulesSync = function(modulePath) {
    modulePath = modulePath || this.modulePath;

    var moduleFiles = this.getModuleFiles(modulePath);
    var module = null;

    for(var i = 0, l = moduleFiles.length; i < l; i++) {
        module = require(moduleFiles[i]);

        this.modules.push({
            enabled: true,
            module: new module(this)
        });
    }
};

//unload all modules and delete the cached files
Sekshi.prototype.unloadModulesSync = function(modulePath) {
    modulePath = modulePath || this.modulePath;

    for(var i = 0, l = this.modules.length; i < l; i++) {
        if(typeof this.modules[i].module.destroy !== "undefined")
            this.modules[i].module.destroy();
    }

    this.modules = [];
    var moduleFiles = this.getModuleFiles(modulePath);

    for(var i = 0, l = moduleFiles.length; i < l; i++) {
        delete require.cache[path.resolve(moduleFiles[i])];
    }
};

module.exports = Sekshi;<|endoftext|>


<commit_before>$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "http://apis-guru.github.io/api-models/api/v1/list.json",
        dataType: 'json',
        cache: false,
        success: function (data) {
            var fragment = $(document.createDocumentFragment());
            $.each(data, function (name, apis) {
                var preferred = apis.preferred;
                var api = apis.versions[preferred];
                var info = api.info;
                var contact = info.contact || {};
                var logo = info['x-logo'] || {};
                var logoUrl = logo.url || 'no-logo.png';
                var logoBg = logo.backgroundColor || '#eee';

                var card = $(
                    "
\

\

\

\

\

\

\
                                    " + info.title + "\

\

" + marked(info.description || '') + "
\

\

\

OpenAPI(fka Swagger) 2.0
\

\

" + preferred + "
\
                                    \
                                        json \
                                        yaml\
                                    \

\

\

\

");

                var versions;
                var versionsGroup = $(
                    "
\
                        <button class='btn btn-default btn-xs dropdown-toggle' type='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>\
                            \
                        </button>\

\

");
                card.find('.versions').append(versionsGroup);

                $.each(apis.versions, function (version, api) {
                    if (version != preferred) {
                        if (!versions) {
                            versions = card.find('.dropdown-menu');
                        }
                        versions.append(
                            "
\
                                " + version + "\
                                \
                                    json \
                                    yaml\
                                \

");
                    }
                });

                if (!versions) {
                    versionsGroup.css('visibility', 'hidden');
                    versionsGroup.css('width', '0');
                }

                fragment.append(card);
            });

            $('#list').append(fragment);
            $('#footer').show();
        }
    });
});<commit_msg>use externalDocs.url<commit_after>$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "http://apis-guru.github.io/api-models/api/v1/list.json",
        dataType: 'json',
        cache: false,
        success: function (data) {
            var fragment = $(document.createDocumentFragment());
            $.each(data, function (name, apis) {
                var preferred = apis.preferred;
                var api = apis.versions[preferred];
                var info = api.info;
                var externalDocs = api.externalDocs || {};
                var contact = info.contact || {};
                var externalUrl = externalDocs.url || contact.url;
                var logo = info['x-logo'] || {};
                var logoUrl = logo.url || 'no-logo.png';
                var logoBg = logo.backgroundColor || '#eee';

                var card = $(
                    "
\

\

\

\

\

\

\
                                    " + info.title + "\

\

" + marked(info.description || '') + "
\

\

\

OpenAPI(fka Swagger) 2.0
\

\

" + preferred + "
\
                                    \
                                        json \
                                        yaml\
                                    \

\

\

\

");

                var versions;
                var versionsGroup = $(
                    "
\
                        <button class='btn btn-default btn-xs dropdown-toggle' type='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>\
                            \
                        </button>\

\

");
                card.find('.versions').append(versionsGroup);

                $.each(apis.versions, function (version, api) {
                    if (version != preferred) {
                        if (!versions) {
                            versions = card.find('.dropdown-menu');
                        }
                        versions.append(
                            "
\
                                " + version + "\
                                \
                                    json \
                                    yaml\
                                \

");
                    }
                });

                if (!versions) {
                    versionsGroup.css('visibility', 'hidden');
                    versionsGroup.css('width', '0');
                }

                fragment.append(card);
            });

            $('#list').append(fragment);
            $('#footer').show();
        }
    });
});<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes",
  "Merging in private branch",
  "Time machines are real man!"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 10% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.1;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
<commit_msg>Fixed a typo<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes",
  "Merging in private branch",
  "Time machines are real man!"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 10% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.1;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + st<|endoftext|>