<commit_before>'use strict';

var fw = 1;		// make freewall default
var startTime;
var firstAddClicked = 0, firstGenerate = 0;
var wall;

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	var tab = window.location.hash || "#about";
	$("#navbar-collapse .navlink").each(function() {
		if($(this).attr("href") == tab) {
			$(this).parent().addClass("active");
			return false;
		}
	});
	window.location.hash = "";
	$(tab).addClass("active");
	startTime = new Date().getTime();
	initializePage();
});

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	// AJAX to populate list of coupons
	$.get("coupons", {sort: "", popular: 1, freewall: fw}, function(data) {
		$("#popular").append(data);
		$.get("coupons", {sort: "", popular: 0, freewall: fw}, function(data) {
			$("#available").append(data);
			// Add coupon click handler
			$(".addCoupon").click(addCoupon);

			if($("#popular").hasClass("active")) {
				setTimeout(function() {
					organizeCoupons("#popularFreewall");
				}, 400);
			}
			if($("#available").hasClass("active")) {
				setTimeout(function() {
					organizeCoupons("#availableFreewall");
				}, 400);
			}
		});
	});

	$("#checkoutBtn").prop('disabled', true);

	// Click handler for "checkout" i.e. Generate QR Code btn
	$("#checkoutBtn").click(function(e){
		// The button will be disabled when there are no items.
		if(parseInt($("#cartItems").text()) == 0) {
			e.preventDefault();
			return false;
		}
		// hide modal when checkout btn is clicked
		$("#walletModal").modal("hide");
		// remove highlighting of nav tab by removing active class
		$("#navbar-collapse > ul > li.active").removeClass("active");
		if(!firstGenerate)
			ga("send", "timing", "Generate Coupon", "First Generate", new Date().getTime() - startTime, {"page": window.location.pathnam});
		ga("send", "event", "Generate Coupon", "click", {"page": window.location.pathnam});
	});

	// Auto collapse nav menu when link is clicked
	$(".navlink").click(function(e) {
		e.preventDefault();
		if(parseInt($(window).width()) < 768 ) {
			if($("#navbar-collapse").hasClass("in")) {
				$(".navbar-toggle").click();
			}
		}

		// update active tab in menu
		$(".navbar-nav").find(".active").removeClass("active");
		var newActive = $(this).attr("href");
		$(".navbar-nav li a").each(function() {
			if($(this).attr("href") == newActive) {
				var activeTab = $(this).parent();
				setTimeout(function() {
					activeTab.addClass("active");
				}, 400);
				$(this).tab("show");
				if(fw) {
					organizeCoupons(newActive+"Freewall");
					$("#couponFilter").val("");
				}
				return;
			}
		});
	});

	// hide drop down when click outside
	$('.tab-content').click(function(){
		if($("#navbar-collapse").hasClass("in")) {
				$(".navbar-toggle").click();
		}
	});

	// Filtering coupons
	$("#couponFilter").keyup(function(){
		// Retrieve the input field text and reset the count to zero
		var filter = $(this).val();

		var selector = fw? $("#available .brick") : $("#available li");
		selector.each(function(){
			var found = $(this).text().search(new RegExp(filter, "i")) < 0;
			// If the list item does not contain the text phrase fade it out
			if ($(this).text().search(new RegExp(filter, "i")) < 0) {
				if(!fw)
					$(this).fadeOut();
				else
					$(this).removeClass("filterMe");
			} else {
				if(!fw)
					$(this).show();
				else
					$(this).addClass("filterMe");
			}
		});
		if(fw) {
			wall && wall.destroy();// && delete wall;
			wall = new freewall("#availableFreewall");
			wall.reset({
				selector: '.brick',
				animate: true,
				cellW: function(width){return width/2;},
				cellH: 'auto',
				onResize: function() {
					//wall.refresh();
				}
			});
			if (filter) {
				wall.filter(".filterMe");
			} else {
				wall.unFilter();
			}

			wall.fitWidth();
		}
	});

	$(".sortByBtn").click(function(e) {
		e.preventDefault();
		var sortBy = $(this).val();
		getCoupons(sortBy);
	});

	$(".modal .modal-body").css("max-height", parseInt($(window).height()*0.5-50));

	$("#cameraForm").ajaxForm({
		dataType: "json",
		beforeSubmit: checkCouponName,
		success: showCoupon,
		uploadProgress: progressCallback
	});
}

/*
 *	Pre submit callback for upload form
 */
function checkCouponName(formData, jqForm, options) {
	var fileName = jqForm[0].file.value.split(/[\\/]/).pop();
	var couponName = jqForm[0].title.value;
	var generateClassName = function(name) {
				return (name.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~\s]/g, '').toLowerCase());
	}
	var couponClassName = generateClassName(couponName);
	var duplicateFile = false;

	$(".errMsg").hide();
	$(".progress").hide();
	$(".progress-bar").text("0%");
	$(".progress-bar").css("width", "0%");
	ga("send", "event", "Upload Coupon", "Upload Attempt", {"page": window.location.pathnam});
	// No file selected
	if(!jqForm[0].file.value){
		$("#noFileMsg").show();
		return false;
	}
	// No name inputted
	if(!couponName){
		$("#noNameMsg").show();
		return false;
	}
	// Check if name is used
	if($(".coupons").hasClass(couponClassName)) {
		$("#dupCouponNameMsg").show();
		return false;
	}
	// Check if file has been uploaded already
	$(".origFilenames").each(function() {
		if($(this).val() == fileName) {
			duplicateFile = true;
			$("#dupCouponMsg").show();
			return false;
		}
	});

	// Disable upload button when uploading
	if(!duplicateFile) {
		$("#uploadBtn").prop("disabled", true);
		$(".progress").show();
	}
	return !duplicateFile;
}

/*
 *	Post submit callback for upload form
 */
function showCoupon(rspTxt) {
	// Enable upload button when done
	$("#uploadBtn").prop("disabled", false);
	$(".progress-bar").text("100%");
	$(".progress-bar").css("width", "100%");
	if(!rspTxt.result) {
		$("#invalidQRMsg").show();
		return false;
	}
	ga("send", "event", "Upload Coupon", "Upload Success", {"page": window.location.pathnam});
	var str;
	str = '
'
		str += '';
			str += '';
		str += '';
		str += '
';
			str += '
';
			str += rspTxt.title;
			str += '';
			str += '
';
			str += '
' + rspTxt.result + '
';
			str += '<input type="hidden" class="origFilenames" value="' + rspTxt.origFilename + '">';
		str += '
';
	str += '
';
	$("#camera ul").append(str);
	$("#camera ul li").last().find(".addCoupon").click(addCoupon);
}

function progressCallback(e, pos, total, percent) {
	// show 100% only when response recieved from /upload
	$(".progress-bar").text(percent+"%");
	$(".progress-bar").css("width", (percent-1)+"%");
	if(percent == 100) {
		$(".progress-bar").text("Processing");
	}
}

/*
 *	Click handler for adding a coupon to myClip
 */
function addCoupon(e) {
	e.preventDefault();
	if(!firstAddClicked) {
		firstAddClicked = 1;
		ga("send", "timing", "Add Coupon", "First Add Clicked", new Date().getTime() - startTime, {"page": window.location.pathnam});
	}
	ga("send", "event", "Add Coupon", "click", {"page": window.location.pathnam});
	// change cartItems text (num items in myClip)
	var num = parseInt($("#cartItems").text()) + 1;
	$("#cartItems").text(num);

	var isBrick = $(this).closest(".coupon").hasClass("brick");
	// Get the coupon name
	var couponClasses = $(this).closest(".coupon").attr("class").split(" ");
	var couponName = couponClasses[couponClasses.length-1];
	// Get the glyphicon span
	var couponGlyph = $("." + couponName).find(".glyphicon");

	// change + icons to check icons and unbind addCoupon
	couponGlyph.toggleClass("glyphicon-plus glyphicon-check");
	couponGlyph.parent().unbind("click");

	// Clone the coupon to add to myCLip
	var couponClone = $("." + couponName).clone()[0];
	if(isBrick) {
		var str, tmp;
		str = '
'
			str += '';
				str += '';
			str += '';
		str += '
';
		tmp = $(str);
		tmp.append($(couponClone).find(".info"));
		$(tmp).find(".info").removeClass("info").addClass("media-body");
		$(tmp).find("h5").addClass("media-heading");

		couponClone = tmp;
	}
	var couponCloneGlyph = $(couponClone).find(".glyphicon");

	// update clone of coupon in myClip
	couponCloneGlyph.toggleClass("glyphicon-check glyphicon-remove");
	couponCloneGlyph.parent().click(removeCoupon);

	// add item to myClip
	if(num == 1) {
		$("#walletModal .modal-body").html('

');
		$("#checkoutBtn").prop("disabled", false);
	}

	$("#walletModal .modal-body ul").append(couponClone);
}

/*
 *	Click handler for removing a coupon from myClip
 */
function removeCoupon(e) {
	e.preventDefault();

	// change cartItems text (num items in myClip)
	var num = parseInt($("#cartItems").text()) - 1;
	$("#cartItems").text(num);

	var coupon = $(this).closest("li");
	if(num == 0) {
		$("#walletModal .modal-body").html('You have not clipped any coupons.');
		$("#checkoutBtn").prop("disabled", true);
	}
	else {
		coupon.remove();
	}

	// Find coupons to update
	var couponClasses = $(this).closest(".coupon").attr("class").split(" ");
	var couponName = couponClasses[couponClasses.length-1];
	var couponGlyph = $("." + couponName).find(".glyphicon");

	// change check icons to + icons
	couponGlyph.toggleClass("glyphicon-check glyphicon-plus");
	couponGlyph.parent().unbind("click");
	couponGlyph.parent().click(addCoupon);
}

function getCoupons(method) {
	$.get("/coupons",{sort: method, freewall: fw}, function(data) {
		// Update current list of coupons to sorted data
		$("#available .couponlist").remove();
		$("#available").append(data);
		if(fw) {
			setTimeout(function() {
					organizeCoupons("#availableFreewall");
				}, 300);
		}

		// New list of coupons don't have old infomation such as if it were already added or not
		// Check added coupons and fix the list
		var added = [];
		$("#walletModal .modal-body li").each(function() {
			added.push("." + $(this).attr('class').split(' ')[1]);
		});
		added = added.join(", ");

		var availCoupons = $("#available li");
		var addedCouponsGlphySpan = availCoupons.filter(added).find("span");

		availCoupons.not(added).find(".addCoupon").click(addCoupon);
		addedCouponsGlphySpan.removeClass("glyphicon-plus");
		addedCouponsGlphySpan.addClass("glyphicon-check");
	});
}

function organizeCoupons(id) {
	wall && wall.destroy();// && delete wall;
	wall = new freewall(id);
	wall.reset({
		selector: '.brick',
		animate: true,
		cellW: function(width){return width/2;},
		cellH: 'auto',
		onResize: function() {
			//wall.refresh();
		}
	});

	var images = wall.container.find('.brick');
	var length = images.length;
	wall.fitWidth();
}<commit_msg>disable enter keypress on filter<commit_after>'use strict';

var fw = 1;		// make freewall default
var startTime;
var firstAddClicked = 0, firstGenerate = 0;
var wall;

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	var tab = window.location.hash || "#about";
	$("#navbar-collapse .navlink").each(function() {
		if($(this).attr("href") == tab) {
			$(this).parent().addClass("active");
			return false;
		}
	});
	window.location.hash = "";
	$(tab).addClass("active");
	startTime = new Date().getTime();
	initializePage();
});

/*
 * Function that is called when the document is ready.
 */
function initializePage() {
	// AJAX to populate list of coupons
	$.get("coupons", {sort: "", popular: 1, freewall: fw}, function(data) {
		$("#popular").append(data);
		$.get("coupons", {sort: "", popular: 0, freewall: fw}, function(data) {
			$("#available").append(data);
			// Add coupon click handler
			$(".addCoupon").click(addCoupon);

			if($("#popular").hasClass("active")) {
				setTimeout(function() {
					organizeCoupons("#popularFreewall");
				}, 400);
			}
			if($("#available").hasClass("active")) {
				setTimeout(function() {
					organizeCoupons("#availableFreewall");
				}, 400);
			}
		});
	});

	$("#checkoutBtn").prop('disabled', true);

	// Click handler for "checkout" i.e. Generate QR Code btn
	$("#checkoutBtn").click(function(e){
		// The button will be disabled when there are no items.
		if(parseInt($("#cartItems").text()) == 0) {
			e.preventDefault();
			return false;
		}
		// hide modal when checkout btn is clicked
		$("#walletModal").modal("hide");
		// remove highlighting of nav tab by removing active class
		$("#navbar-collapse > ul > li.active").removeClass("active");
		if(!firstGenerate)
			ga("send", "timing", "Generate Coupon", "First Generate", new Date().getTime() - startTime, {"page": window.location.pathnam});
		ga("send", "event", "Generate Coupon", "click", {"page": window.location.pathnam});
	});

	// Auto collapse nav menu when link is clicked
	$(".navlink").click(function(e) {
		e.preventDefault();
		if(parseInt($(window).width()) < 768 ) {
			if($("#navbar-collapse").hasClass("in")) {
				$(".navbar-toggle").click();
			}
		}

		// update active tab in menu
		$(".navbar-nav").find(".active").removeClass("active");
		var newActive = $(this).attr("href");
		$(".navbar-nav li a").each(function() {
			if($(this).attr("href") == newActive) {
				var activeTab = $(this).parent();
				setTimeout(function() {
					activeTab.addClass("active");
				}, 400);
				$(this).tab("show");
				if(fw) {
					organizeCoupons(newActive+"Freewall");
					$("#couponFilter").val("");
				}
				return;
			}
		});
	});

	// hide drop down when click outside
	$('.tab-content').click(function(){
		if($("#navbar-collapse").hasClass("in")) {
				$(".navbar-toggle").click();
		}
	});

	// disable enter key press
	$("#couponFilter").keypress(function(e) {
		if(e.which == 13) {
			e.preventDefault();
			return false;
		}
	});

	// Filtering coupons
	$("#couponFilter").keyup(function(){
		// Retrieve the input field text and reset the count to zero
		var filter = $(this).val();

		var selector = fw? $("#available .brick") : $("#available li");
		selector.each(function(){
			var found = $(this).text().search(new RegExp(filter, "i")) < 0;
			// If the list item does not contain the text phrase fade it out
			if ($(this).text().search(new RegExp(filter, "i")) < 0) {
				if(!fw)
					$(this).fadeOut();
				else
					$(this).removeClass("filterMe");
			} else {
				if(!fw)
					$(this).show();
				else
					$(this).addClass("filterMe");
			}
		});
		if(fw) {
			wall && wall.destroy();// && delete wall;
			wall = new freewall("#availableFreewall");
			wall.reset({
				selector: '.brick',
				animate: true,
				cellW: function(width){return width/2;},
				cellH: 'auto',
				onResize: function() {
					//wall.refresh();
				}
			});
			if (filter) {
				wall.filter(".filterMe");
			} else {
				wall.unFilter();
			}

			wall.fitWidth();
		}
	});

	$(".sortByBtn").click(function(e) {
		e.preventDefault();
		var sortBy = $(this).val();
		getCoupons(sortBy);
	});

	$(".modal .modal-body").css("max-height", parseInt($(window).height()*0.5-50));

	$("#cameraForm").ajaxForm({
		dataType: "json",
		beforeSubmit: checkCouponName,
		success: showCoupon,
		uploadProgress: progressCallback
	});
}

/*
 *	Pre submit callback for upload form
 */
function checkCouponName(formData, jqForm, options) {
	var fileName = jqForm[0].file.value.split(/[\\/]/).pop();
	var couponName = jqForm[0].title.value;
	var generateClassName = function(name) {
				return (name.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~\s]/g, '').toLowerCase());
	}
	var couponClassName = generateClassName(couponName);
	var duplicateFile = false;

	$(".errMsg").hide();
	$(".progress").hide();
	$(".progress-bar").text("0%");
	$(".progress-bar").css("width", "0%");
	ga("send", "event", "Upload Coupon", "Upload Attempt", {"page": window.location.pathnam});
	// No file selected
	if(!jqForm[0].file.value){
		$("#noFileMsg").show();
		return false;
	}
	// No name inputted
	if(!couponName){
		$("#noNameMsg").show();
		return false;
	}
	// Check if name is used
	if($(".coupons").hasClass(couponClassName)) {
		$("#dupCouponNameMsg").show();
		return false;
	}
	// Check if file has been uploaded already
	$(".origFilenames").each(function() {
		if($(this).val() == fileName) {
			duplicateFile = true;
			$("#dupCouponMsg").show();
			return false;
		}
	});

	// Disable upload button when uploading
	if(!duplicateFile) {
		$("#uploadBtn").prop("disabled", true);
		$(".progress").show();
	}
	return !duplicateFile;
}

/*
 *	Post submit callback for upload form
 */
function showCoupon(rspTxt) {
	// Enable upload button when done
	$("#uploadBtn").prop("disabled", false);
	$(".progress-bar").text("100%");
	$(".progress-bar").css("width", "100%");
	if(!rspTxt.result) {
		$("#invalidQRMsg").show();
		return false;
	}
	ga("send", "event", "Upload Coupon", "Upload Success", {"page": window.location.pathnam});
	var str;
	str = '
'
		str += '';
			str += '';
		str += '';
		str += '
';
			str += '
';
			str += rspTxt.title;
			str += '';
			str += '
';
			str += '
' + rspTxt.result + '
';
			str += '<input type="hidden" class="origFilenames" value="' + rspTxt.origFilename + '">';
		str += '
';
	str += '
';
	$("#camera ul").append(str);
	$("#camera ul li").last().find(".addCoupon").click(addCoupon);
}

function progressCallback(e, pos, total, percent) {
	// show 100% only when response recieved from /upload
	$(".progress-bar").text(percent+"%");
	$(".progress-bar").css("width", (percent-1)+"%");
	if(percent == 100) {
		$(".progress-bar").text("Processing");
	}
}

/*
 *	Click handler for adding a coupon to myClip
 */
function addCoupon(e) {
	e.preventDefault();
	if(!firstAddClicked) {
		firstAddClicked = 1;
		ga("send", "timing", "Add Coupon", "First Add Clicked", new Date().getTime() - startTime, {"page": window.location.pathnam});
	}
	ga("send", "event", "Add Coupon", "click", {"page": window.location.pathnam});
	// change cartItems text (num items in myClip)
	var num = parseInt($("#cartItems").text()) + 1;
	$("#cartItems").text(num);

	var isBrick = $(this).closest(".coupon").hasClass("brick");
	// Get the coupon name
	var couponClasses = $(this).closest(".coupon").attr("class").split(" ");
	var couponName = couponClasses[couponClasses.length-1];
	// Get the glyphicon span
	var couponGlyph = $("." + couponName).find(".glyphicon");

	// change + icons to check icons and unbind addCoupon
	couponGlyph.toggleClass("glyphicon-plus glyphicon-check");
	couponGlyph.parent().unbind("click");

	// Clone the coupon to add to myCLip
	var couponClone = $("." + couponName).clone()[0];
	if(isBrick) {
		var str, tmp;
		str = '
'
			str += '';
				str += '';
			str += '';
		str += '
';
		tmp = $(str);
		tmp.append($(couponClone).find(".info"));
		$(tmp).find(".info").removeClass("info").addClass("media-body");
		$(tmp).find("h5").addClass("media-heading");

		couponClone = tmp;
	}
	var couponCloneGlyph = $(couponClone).find(".glyphicon");

	// update clone of coupon in myClip
	couponCloneGlyph.toggleClass("glyphicon-check glyphicon-remove");
	couponCloneGlyph.parent().click(removeCoupon);

	// add item to myClip
	if(num == 1) {
		$("#walletModal .modal-body").html('

');
		$("#checkoutBtn").prop("disabled", false);
	}

	$("#walletModal .modal-body ul").append(couponClone);
}

/*
 *	Click handler for removing a coupon from myClip
 */
function removeCoupon(e) {
	e.preventDefault();

	// change cartItems text (num items in myClip)
	var num = parseInt($("#cartItems").text()) - 1;
	$("#cartItems").text(num);

	var coupon = $(this).closest("li");
	if(num == 0) {
		$("#walletModal .modal-body").html('You have not clipped any coupons.');
		$("#checkoutBtn").prop("disabled", true);
	}
	else {
		coupon.remove();
	}

	// Find coupons to update
	var couponClasses = $(this).closest(".coupon").attr("class").split(" ");
	var couponName = couponClasses[couponClasses.length-1];
	var couponGlyph = $("." + couponName).find(".glyphicon");

	// change check icons to + icons
	couponGlyph.toggleClass("glyphicon-check glyphicon-plus");
	couponGlyph.parent().unbind("click");
	couponGlyph.parent().click(addCoupon);
}

function getCoupons(method) {
	$.get("/coupons",{sort: method, freewall: fw}, function(data) {
		// Update current list of coupons to sorted data
		$("#available .couponlist").remove();
		$("#available").append(data);
		if(fw) {
			setTimeout(function() {
					organizeCoupons("#availableFreewall");
				}, 300);
		}

		// New list of coupons don't have old infomation such as if it were already added or not
		// Check added coupons and fix the list
		var added = [];
		$("#walletModal .modal-body li").each(function() {
			added.push("." + $(this).attr('class').split(' ')[1]);
		});
		added = added.join(", ");

		var availCoupons = $("#available li");
		var addedCouponsGlphySpan = availCoupons.filter(added).find("span");

		availCoupons.not(added).find(".addCoupon").click(addCoupon);
		addedCouponsGlphySpan.removeClass("glyphicon-plus");
		addedCouponsGlphySpan.addClass("glyphicon-check");
	});
}

function organizeCoupons(id) {
	wall && wall.destroy();// && delete wall;
	wall = new freewall(id);
	wall.reset({
		selector: '.brick',
		animate: true,
		cellW: function(width){return width/2;},
		cellH: 'auto',
		onResize: function() {
			//wall.refresh();
		}
	});

	var images = wall.container.find('.brick');
	var length = images.length;
	wall.fitWidth();
}<|endoftext|>


<commit_before>//  elmoSlider v0.0.4 by Michal Dolny
//  dependencies: jQuery

(function($){

    $.fn.elmoSlider = function(options){
        var defaults = {
            speed: 500,
            pause: 2500,
            transition: 'slide',
            autoPlay: false,
            complete: null
        };
        var settings = $.extend({}, defaults, options);

        var slider = this;
        var state = [0];
        var i = 0;
        var j = 0;

        slider.find('.slide').each(function(){
            state[j]=-(j * $(this).width());
            j++;
        });

        return this.each(function(){

            // setup css
            if (settings.transition === 'slide'){
                slider.find('.slider-content').css({
                    width: (state.length * 100 + '%')
                });
                slider.find('.slide').css({
                    width: (100 / state.length + '%'),
                    'float': 'left',
                });
            } else if (settings.transition === 'fade'){
                slider.find('.slider-content').css({
                    width: (100 + '%')
                });
                slider.find('.slide').css({
                    width: (100 + '%'),
                    'float': 'none',
                    position: 'absolute',
                    opacity: 0
                });
            }
            $(slider).find('.slide').first().addClass('active-slide').css('opacity', '1');

            if (settings.pause <= settings.speed){
                settings.pause = settings.speed + 100;
            }

            if (settings.autoPlay === false){
                $(slider).on('click', '.slide-left', function(){
                    prevSlide();
                });
                $(slider).on('click', '.slide-right', function(){
                    nextSlide();
                });
            }

            if (settings.autoPlay === true){
                setInterval(function(){
                    nextSlide();
                }, settings.pause);
            }

            function nextSlide(){
                if ( i >= (state.length - 1) ){
                    i = 0;
                } else {
                    i++;
                }

                if (settings.transition === 'fade'){
                    $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, settings.speed);
                    $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, settings.speed);
                } else {
                    $(slider).find('.slider-content').animate({'margin-left': state[i]}, settings.speed);
                }

                if ($.isFunction(settings.complete)){
                    setTimeout(function(){
                        settings.complete.call(this);
                    }, settings.speed);
                }
            }

            function prevSlide(){
                if ( i <= 0 ){
                    i = state.length - 1;
                } else {
                    i--;
                }

                if (settings.transition === 'fade'){
                    $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, settings.speed);
                    $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, settings.speed);
                } else {
                    $(slider).find('.slider-content').animate({'margin-left': state[i]}, settings.speed);
                }

                if ($.isFunction(settings.complete)){
                    setTimeout(function(){
                        settings.complete.call(this);
                    }, settings.speed);
                }
            }

        });

    };

})(jQuery);
<commit_msg>more DRY<commit_after>//  elmoSlider v0.0.4 by Michal Dolny
//  dependencies: jQuery

(function($){

    $.fn.elmoSlider = function(options){
        var defaults = {
            speed: 500,
            pause: 2500,
            transition: 'slide',
            autoPlay: false,
            complete: null
        };
        var settings = $.extend({}, defaults, options);

        var slider = this;
        var state = [0];
        var i = 0;
        var j = 0;

        slider.find('.slide').each(function(){
            state[j]=-(j * $(this).width());
            j++;
        });

        return this.each(function(){

            // setup css
            if (settings.transition === 'slide'){
                slider.find('.slider-content').css({
                    width: (state.length * 100 + '%')
                });
                slider.find('.slide').css({
                    width: (100 / state.length + '%'),
                    'float': 'left',
                });
            } else if (settings.transition === 'fade'){
                slider.find('.slider-content').css({
                    width: (100 + '%')
                });
                slider.find('.slide').css({
                    width: (100 + '%'),
                    'float': 'none',
                    position: 'absolute',
                    opacity: 0
                });
            }
            $(slider).find('.slide').first().addClass('active-slide').css('opacity', '1');

            if (settings.pause <= settings.speed){
                settings.pause = settings.speed + 100;
            }

            if (settings.autoPlay === false){
                $(slider).on('click', '.slide-left', function(){
                    prevSlide();
                });
                $(slider).on('click', '.slide-right', function(){
                    nextSlide();
                });
            }

            if (settings.autoPlay === true){
                setInterval(function(){
                    nextSlide();
                }, settings.pause);
            }

            function switchSlide(){
                if (settings.transition === 'fade'){
                    $('.active-slide').removeClass('active-slide').animate({'opacity': 0}, settings.speed);
                    $('.slide'+(i+1)).addClass('active-slide').animate({'opacity': 1}, settings.speed);
                } else {
                    $(slider).find('.slider-content').animate({'margin-left': state[i]}, settings.speed);
                }
            }

            function nextSlide(){
                if ( i >= (state.length - 1) ){
                    i = 0;
                } else {
                    i++;
                }
                switchSlide();
                afterComplete();
            }

            function prevSlide(){
                if ( i <= 0 ){
                    i = state.length - 1;
                } else {
                    i--;
                }
                switchSlide();
                afterComplete();
            }

            function afterComplete(){
                if ($.isFunction(settings.complete)){
                    setTimeout(function(){
                        settings.complete.call(this);
                    }, settings.speed);
                }
            }

        });

    };

})(jQuery);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015-2016  ChalkPE
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function shuffleArray(array){
    return array.map(function(element){
        return [Math.random(), element];
    }).sort().map(function(element){
        return element[1];
    });
}

function distinctArray(array){
    return array.filter(function(element, index){
        return array.indexOf(element) === index;
    });
}

function hashCode(str){
    return str ? str.split("").reduce(function(a,b){ a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0) : 0;
}

var colors = shuffleArray([
    "red",
    "pink",
    "purple",
    "deep-purple",
    "indigo",
    "blue",
    "light-blue",
    "cyan",
    "teal",
    "green",
    "light-green",
    //"lime",
    //"yellow",
    "amber",
    "orange",
    //"deep-orange",
    "brown",
    //"grey",
    "blue-grey"
]);

$.fn.toHTML = function(element){
    return $('<span>').append(this.clone()).html();
};

function escape(text){
    return $('<span>').text(text).html();
}

function createUserSpan(user){
    return !user ? '' : $('<span>').addClass(colors[Math.abs(hashCode(user.username)) % colors.length] + "-text username tooltipped").attr('data-tooltip', "@" + user.username).text(user.displayName).toHTML();
}

function createDateSpan(date){
    return !date ? '' : $('<span>').addClass("grey-text date tooltipped").attr('data-tooltip', moment(date).format('YYYY-MM-DD HH:mm:ss')).text(moment(date).format("HH:mm")).toHTML();
}

function onConnect(){
    socket.emit('login');
}

function onLogin(data){
    console.log(data);

    appendMessage(createUserSpan(data) + "님, 안녕하세요!", ['grey', 'lighten-3']);
    $("#messageInput").focus();
}

// 메시지를 수신할 경우
function onMessage(message){
    appendMessage(createUserSpan(message.sender) + ' ' + escape(message.text) + ' ' + createDateSpan(message.date));
}

// 입장 메시지를 수신하는 경우
function onUserJoin(user){
    appendMessage(createUserSpan(user) + '님이 입장하셨습니다.');
}

// 퇴장 메시지를 수신하는 경우
function onUserLeft(user){
    appendMessage(createUserSpan(user) + '님이 퇴장하셨습니다.');
}

// 명령를 전송하는 경우
function onCommand(data){
    if(data.command) appendMessage(createUserSpan(data.command.sender) + ' ' + data.command.text, ['grey', 'lighten-3']);

    switch(data.name){
        case 'online':
            // 접속자 확인
            appendMessage("온라인: " + distinctArray(data.response.map(createUserSpan)).join(', '), ['grey', 'lighten-3']);
            break;

        case 'clear':
            // 청소
            $("#chatRoom").empty();
            appendMessage("방을 청소했습니다.", ['grey', 'lighten-3']);
            break;

        case 'invalid':
            // 명령어 오류
            appendMessage("존재하지 않는 명령어입니다.", ['grey', 'lighten-3']);
            break;

        case 'alert plaster':
            // 채팅금지 시간 전송 (도배)
            appendMessage("반복적인 메시지 전송으로 " + (data.response / 1000).toFixed(1).toString() + "초 동안 채팅이 차단되어 있습니다.", ['grey', 'lighten-3']);
            break;
    }
}

function onDisconnected(){
    appendMessage("이런, 서버와의 연결이 끊겼습니다.", ['red', 'lighten-3']);
}

function onReconnecting(){
    appendMessage("재연결을 시도하는 중입니다….", ['amber', 'lighten-3']);
}

function sendMessage(){
    var text = $("#messageInput").val();
    if(text){
        socket.emit('message', { text: text });
        $("#messageInput").val('');
    }
    $("#messageInput").focus();
}

// 챗방 메시지 목록에 메시지 축가
function appendMessage(text, otherClasses){
    var item = $('<li>').html(text).addClass("collection-item" + ((otherClasses && (' ' + otherClasses.join(' '))) || ''));
    $("#chatRoom").append(item).find('.tooltipped').tooltip({ delay: 50 });
    if(hasScrolledToBottom) scrollToBottom();
}

var socket = io.connect({
    'port': 671, 'force new connection': true, 'reconnect': true,
    'reconnection delay': 1000, 'max reconnection attempts': 60
});

socket.on('connect', onConnect);
socket.on('login', onLogin);
socket.on('message', onMessage);
socket.on('command', onCommand);
socket.on('user join', onUserJoin);
socket.on('user left', onUserLeft);
socket.on('disconnect', onDisconnected);
socket.on('reconnecting', onReconnecting);

var hasScrolledToBottom = true;
$(window).scroll(function(){
    hasScrolledToBottom = ($(window).scrollTop() + $(window).height()) > ($(document).height() - ($("#messageBox").outerHeight() + 32));
});

function scrollToBottom(){
    $("html, body").scrollTop($(document).height());
}

$(function(){
    $("#chatRoom").css('margin-bottom', ($("#messageBox").outerHeight() + 8) + "px");
    $("#messageInput").keydown(function(e){ if(e.keyCode === 13) $("#messageSendButton").click(); });
    $("#messageSendButton").click(sendMessage);
});
<commit_msg>Removed duplicate initialization<commit_after>/*
 * Copyright (C) 2015-2016  ChalkPE
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function shuffleArray(array){
    return array.map(function(element){
        return [Math.random(), element];
    }).sort().map(function(element){
        return element[1];
    });
}

function distinctArray(array){
    return array.filter(function(element, index){
        return array.indexOf(element) === index;
    });
}

function hashCode(str){
    return str ? str.split("").reduce(function(a,b){ a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0) : 0;
}

var colors = shuffleArray([
    "red",
    "pink",
    "purple",
    "deep-purple",
    "indigo",
    "blue",
    "light-blue",
    "cyan",
    "teal",
    "green",
    "light-green",
    //"lime",
    //"yellow",
    "amber",
    "orange",
    //"deep-orange",
    "brown",
    //"grey",
    "blue-grey"
]);

$.fn.toHTML = function(element){
    return $('<span>').append(this.clone()).html();
};

function escape(text){
    return $('<span>').text(text).html();
}

function createUserSpan(user){
    return !user ? '' : $('<span>').addClass(colors[Math.abs(hashCode(user.username)) % colors.length] + "-text username tooltipped").attr('data-tooltip', "@" + user.username).text(user.displayName).toHTML();
}

function createDateSpan(date){
    return !date ? '' : $('<span>').addClass("grey-text date tooltipped").attr('data-tooltip', moment(date).format('YYYY-MM-DD HH:mm:ss')).text(moment(date).format("HH:mm")).toHTML();
}

function onConnect(){
    socket.emit('login');
}

function onLogin(data){
    console.log(data);

    appendMessage(createUserSpan(data) + "님, 안녕하세요!", ['grey', 'lighten-3']);
    $("#messageInput").focus();
}

// 메시지를 수신할 경우
function onMessage(message){
    appendMessage(createUserSpan(message.sender) + ' ' + escape(message.text) + ' ' + createDateSpan(message.date));
}

// 입장 메시지를 수신하는 경우
function onUserJoin(user){
    appendMessage(createUserSpan(user) + '님이 입장하셨습니다.');
}

// 퇴장 메시지를 수신하는 경우
function onUserLeft(user){
    appendMessage(createUserSpan(user) + '님이 퇴장하셨습니다.');
}

// 명령를 전송하는 경우
function onCommand(data){
    if(data.command) appendMessage(createUserSpan(data.command.sender) + ' ' + data.command.text, ['grey', 'lighten-3']);

    switch(data.name){
        case 'online':
            // 접속자 확인
            appendMessage("온라인: " + distinctArray(data.response.map(createUserSpan)).join(', '), ['grey', 'lighten-3']);
            break;

        case 'clear':
            // 청소
            $("#chatRoom").empty();
            appendMessage("방을 청소했습니다.", ['grey', 'lighten-3']);
            break;

        case 'invalid':
            // 명령어 오류
            appendMessage("존재하지 않는 명령어입니다.", ['grey', 'lighten-3']);
            break;

        case 'alert plaster':
            // 채팅금지 시간 전송 (도배)
            appendMessage("반복적인 메시지 전송으로 " + (data.response / 1000).toFixed(1).toString() + "초 동안 채팅이 차단되어 있습니다.", ['grey', 'lighten-3']);
            break;
    }
}

function onDisconnected(){
    appendMessage("이런, 서버와의 연결이 끊겼습니다.", ['red', 'lighten-3']);
}

function onReconnecting(){
    appendMessage("재연결을 시도하는 중입니다….", ['amber', 'lighten-3']);
}

function sendMessage(){
    var text = $("#messageInput").val();
    if(text){
        socket.emit('message', { text: text });
        $("#messageInput").val('');
    }
    $("#messageInput").focus();
}

// 챗방 메시지 목록에 메시지 축가
function appendMessage(text, otherClasses){
    var item = $('<li>').html(text).addClass("collection-item" + ((otherClasses && (' ' + otherClasses.join(' '))) || ''))
    item.find('.tooltipped').tooltip({ delay: 50 });

    $("#chatRoom").append(item);
    if(hasScrolledToBottom) scrollToBottom();
}

var socket = io.connect({
    'port': 671, 'force new connection': true, 'reconnect': true,
    'reconnection delay': 1000, 'max reconnection attempts': 60
});

socket.on('connect', onConnect);
socket.on('login', onLogin);
socket.on('message', onMessage);
socket.on('command', onCommand);
socket.on('user join', onUserJoin);
socket.on('user left', onUserLeft);
socket.on('disconnect', onDisconnected);
socket.on('reconnecting', onReconnecting);

var hasScrolledToBottom = true;
$(window).scroll(function(){
    hasScrolledToBottom = ($(window).scrollTop() + $(window).height()) > ($(document).height() - ($("#messageBox").outerHeight() + 32));
});

function scrollToBottom(){
    $("html, body").scrollTop($(document).height());
}

$(function(){
    $("#chatRoom").css('margin-bottom', ($("#messageBox").outerHeight() + 8) + "px");
    $("#messageInput").keydown(function(e){ if(e.keyCode === 13) $("#messageSendButton").click(); });
    $("#messageSendButton").click(sendMessage);
});
<|endoftext|>


<commit_before>/**
 * Log timeline and event viewer.
 *
 * Relies on app/ui.js for backbone.js syncs.
 * index.html provides the layout that includes #backbone-view used below.
 * content.html is injected into #content that's also in index.html.
 */

'use strict';

$(function() {
  window.diana = window.diana || {};
  var diana = window.diana;

  // Parent element for all backbone.js views.
  diana.viewContainer = '#backbone-view';

  // localStorage cache for items like /event/:id responses.
  diana.cache = new clientsiiide('Diana');

  // Feature switches.
  diana.features = {
    // Conditionally enabled later only for compatible search conditions.
    timelineUpdate: false
  };

  // Ephemeral view HTML cache.
  diana.viewCache = {};

  /**
   * Custom routing used to allow 'context' attributes to support behaviors
   * like sidebar toggling per URL pattern.
   */
  var Router = Backbone.Router.extend({
    initialize: function(options) {
      /**
        * 'context' options:
        * - cache: {Boolean} Cache view HTML between route changes. (ephemeral)
        * - sidebar {Boolean} Display sidebar in layout.
        * - tab {String} DOM ID of active navigation tab.
        */
      var routes = {
        '': {
          handler: diana.controllers.ViewIndex,
          context: {cache: true, sidebar: false, tab: 'nav-home'}
       },
        'timeline': {
          handler: diana.controllers.ViewTimeline,
          context: {cache: true, sidebar: false, tab: 'nav-timeline'}
       },
        'timeline/:options': {
          handler: diana.controllers.ViewTimeline,
          context: {cache: true, sidebar: false, tab: 'nav-timeline'}
       },
        'event/:id': {
          handler: diana.controllers.ViewEvent,
          context: {cache: true, sidebar: false, tab: 'nav-timeline'}
        }
      };

      var router = this;
      _.each(routes, function(config, route) {
        // Register route.
        router.route(route, config.handler, function() {
          var routeParams = arguments;
          // Apply 'context' options to the 'content' template, ex. show sidebar.
          dust.render(
            'content',
            config.context,
            function(err, out) {
              // Allow observers to tweak the layout based on configuration.
              $('#content').trigger('ContentPreRender', config.context);

              // Display the rendered content container.
              $('#content').html(out);

              if (config.context.cache) {
                var cachedView = diana.helpers.ViewCache.get(route, routeParams);
                if (cachedView) {
                  $(diana.viewContainer).append(cachedView);
                  return;
                }

                config.context.cacheSetter = diana.helpers.ViewCache.createSetter(route, routeParams);
              }

              // Pass the matched route parameters to the actual handler.
              config.handler.apply(config.context, routeParams);
            }
          );
        });
      });
    }
  });

  new Router();
  Backbone.history.start();
});
<commit_msg>Add Router notes. Rename routeParams.<commit_after>/**
 * Log timeline and event viewer.
 *
 * Relies on app/ui.js for backbone.js syncs.
 * index.html provides the layout that includes #backbone-view used below.
 * content.html is injected into #content that's also in index.html.
 */

'use strict';

$(function() {
  window.diana = window.diana || {};
  var diana = window.diana;

  // Parent element for all backbone.js views.
  diana.viewContainer = '#backbone-view';

  // localStorage cache for items like /event/:id responses.
  diana.cache = new clientsiiide('Diana');

  // Feature switches.
  diana.features = {
    // Conditionally enabled later only for compatible search conditions.
    timelineUpdate: false
  };

  // Ephemeral view HTML cache.
  diana.viewCache = {};

  /**
   * Custom routing used to allow 'context' attributes to support behaviors
   * like sidebar toggling per URL pattern.
   */
  var Router = Backbone.Router.extend({
    initialize: function(options) {
      /**
        * 'context' options:
        * - cache: {Boolean} Cache view HTML between route changes. (ephemeral)
        * - sidebar {Boolean} Display sidebar in layout.
        * - tab {String} DOM ID of active navigation tab.
        */
      var routes = {
        '': {
          handler: diana.controllers.ViewIndex,
          context: {cache: true, sidebar: false, tab: 'nav-home'}
       },
        'timeline': {
          handler: diana.controllers.ViewTimeline,
          context: {cache: true, sidebar: false, tab: 'nav-timeline'}
       },
        'timeline/:options': {
          handler: diana.controllers.ViewTimeline,
          context: {cache: true, sidebar: false, tab: 'nav-timeline'}
       },
        'event/:id': {
          handler: diana.controllers.ViewEvent,
          context: {cache: true, sidebar: false, tab: 'nav-timeline'}
        }
      };

      var router = this;
      _.each(routes, function(config, route) {
        // Register route.
        router.route(route, config.handler, function() {
          var routeArgs = arguments;
          // Apply 'context' options to the 'content' template, ex. show sidebar.
          dust.render(
            'content',
            config.context,
            function(err, out) {
              // Allow observers to tweak the layout based on configuration.
              $('#content').trigger('ContentPreRender', config.context);

              // Display the rendered content container.
              $('#content').html(out);

              if (config.context.cache) {
                var cachedView = diana.helpers.ViewCache.get(route, routeArgs);
                if (cachedView) {
                  $(diana.viewContainer).append(cachedView);
                  return;
                }

                // Customize a view cache API for the current route.
                config.context.cacheSetter = diana.helpers.ViewCache.createSetter(
                  route, routeArgs
                );
              }

              // Pass the matched route parameters to the actual handler.
              config.handler.apply(config.context, routeArgs);
            }
          );
        });
      });
    }
  });

  new Router();
  Backbone.history.start();
});
<|endoftext|>


<commit_before>// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

define(['lodash'],
    function(_) {
        'use strict';

        var ObjectUtilities = function(){};

        ObjectUtilities.prototype.pickNonFalsy = function(source) {
            //var self = this;

            return  _.pickBy(source, function(x){ return x && !_.isEmpty(x); });
        };

        ObjectUtilities.prototype.pickInBoth = function(source, otherSource) {
            //var self = this;

            return _.pickBy(source, function(value, key /*, object*/ ) {
                return _.has(otherSource, key);
            });
        };

        ObjectUtilities.prototype.traverse = function(o, func) {
            var self = this;

            for (var i in o) {
                func.apply(this, [i, o[i]]);
                if (o[i] !== null && typeof(o[i]) === 'object') {
                    //going on step down in the object tree!!
                    self.traverse(o[i], func);
                }
            }
        };

        return new ObjectUtilities();
    });
<commit_msg>Fixed pickNonFalsy: numbers were not picked<commit_after>// Copyright (c) CBC/Radio-Canada. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

define(['lodash'],
    function(_) {
        'use strict';

        var ObjectUtilities = function(){};

        ObjectUtilities.prototype.pickNonFalsy = function(source) {
            return  _.pickBy(source, function(value) { return !isFalsyOrEmpty(value); });
        };

        function isFalsyOrEmpty(value) {
            if (!value) {
                return true;
            }

            if (_.isObject(value) && _.isEmpty(value)) {
                return true;
            }

            return false;
        }

        ObjectUtilities.prototype.pickInBoth = function(source, otherSource) {
            return _.pickBy(source, function(value, key /*, object*/ ) {
                return _.has(otherSource, key);
            });
        };

        ObjectUtilities.prototype.traverse = function(o, func) {
            for (var i in o) {
                func.apply(this, [i, o[i]]);
                if (o[i] !== null && typeof(o[i]) === 'object') {
                    //going on step down in the object tree!!
                    this.traverse(o[i], func);
                }
            }
        };

        return new ObjectUtilities();
    });
<|endoftext|>


<commit_before>window.prefs = {};

window.prefs.openModal = function(feature) {
	$("#prefs-feature-name").text(window.utils.getLongNameForFeature(feature));
	$(".prefs-modal-body").addClass("hidden");
	$("#prefs-" + feature + "-body").removeClass("hidden");
	$("#prefs-modal").attr("data-feature", feature);
	$("#prefs-modal").modal({
		backdrop: "static",
		keyboard: false
	});
};

window.prefs.get = function(name, callback) {
	window.api.get("prefs/get/" + name, function(data) {
		callback(data.val);
	});
};

window.prefs.checkToggle = function($checkbox, prefsId) {
	window.prefs.get(prefsId, function(result) {
		var toggled = false;
		if (parseInt(result) == 1) {
			toggled = true;
		}
		$checkbox.prop("checked", toggled);
		$checkbox.change(function() {
			var prefsVal = ($(this).prop("checked") ? "1" : "0");
			window.api.post("prefs/set", { name: prefsId, value: prefsVal}, function() {});
		});
	});
};
window.prefs.getJSONPref = function(name, callback) {
    window.prefs.get(name, function(val) {
    	if (val === undefined) {
    		callback(undefined);
    		return;
    	}
        callback(JSON.parse(val));
    });
};
$(document).ready(function() {
	$("#prefs-done").click(function() {
		$("#prefs-modal").modal("hide");
		setPage($("#prefs-modal").attr("data-feature"));
	});
	$("#usr-btn").click(function() {
		var usrname = $("#usr-name").val();
		window.api.post("prefs/setName", { name: usrname }, function() {
			window.page.showLoading();
			window.location.reload();
		});
	});
	$("#title-new").click(function() {
		$inputBox = '<input></input>'
			$inputBox.val("title");
			$inputBox.change(function(){
				$(this).parent().attr("id", $(this).val());
				var setList = JSON.stringify($("#title-sorting").sortable("toArray"));
				window.api.post("prefs/set", {name: "titleOrder", value:setList}, function() {});
			});
		$liThingy = ('

');
		$liThingy.attr("id", "title");
		$liThingy.append($inputBox);
	});
	window.prefs.getJSONPref("titleOrder", function(val) {
		if(val == undefined) {
			val = ["HW","Read","Reading","Project","Report","Essay","Paper","Quiz","Test","Final","Exam","Midterm","Lab","Study","DocID","None","NoHW","subjectName"]
		}
		for(title in val) {
			var $titleLi = $('

');
				$titleLi.attr("id", val[title]);
				var $titleWord = $('<input></input>');
					$titleWord.val(val[title]);
					$titleWord.change(function() {
						$(this).parent().attr("id", $(this).val());
						var setList = JSON.stringify($("#title-sorting").sortable("toArray"));
						window.api.post("prefs/set", {name: "titleOrder", value:setList}, function() {});
					});
				$titleLi.append($titleWord);
			$("#title-sorting").append($titleLi);
		};
		$("#title-sorting").sortable({
			stop: function (event, ui) {
				var setList = JSON.stringify($("#title-sorting").sortable("toArray"));
				window.api.post("prefs/set", {name: "titleOrder", value:setList}, function() {});
			}
		});
		$("#title-sorting").disableSelection();
	});
	// Homework View
	window.prefs.checkToggle($("#prefs-hwView-swap"), "name-subj");
	window.prefs.checkToggle($("#prefs-hwView-color"), "titleclr");
	window.prefs.checkToggle($("#prefs-hwView-checkboxes"), "hwView-checkboxes");
});
<commit_msg>yay<commit_after>window.prefs = {};

window.prefs.openModal = function(feature) {
	$("#prefs-feature-name").text(window.utils.getLongNameForFeature(feature));
	$(".prefs-modal-body").addClass("hidden");
	$("#prefs-" + feature + "-body").removeClass("hidden");
	$("#prefs-modal").attr("data-feature", feature);
	$("#prefs-modal").modal({
		backdrop: "static",
		keyboard: false
	});
};

window.prefs.get = function(name, callback) {
	window.api.get("prefs/get/" + name, function(data) {
		callback(data.val);
	});
};

window.prefs.checkToggle = function($checkbox, prefsId) {
	window.prefs.get(prefsId, function(result) {
		var toggled = false;
		if (parseInt(result) == 1) {
			toggled = true;
		}
		$checkbox.prop("checked", toggled);
		$checkbox.change(function() {
			var prefsVal = ($(this).prop("checked") ? "1" : "0");
			window.api.post("prefs/set", { name: prefsId, value: prefsVal}, function() {});
		});
	});
};
window.prefs.getJSONPref = function(name, callback) {
    window.prefs.get(name, function(val) {
    	if (val === undefined) {
    		callback(undefined);
    		return;
    	}
        callback(JSON.parse(val));
    });
};
$(document).ready(function() {
	$("#prefs-done").click(function() {
		$("#prefs-modal").modal("hide");
		setPage($("#prefs-modal").attr("data-feature"));
	});
	$("#usr-btn").click(function() {
		var usrname = $("#usr-name").val();
		window.api.post("prefs/setName", { name: usrname }, function() {
			window.page.showLoading();
			window.location.reload();
		});
	});
	$("#title-new").click(function() {
		$liThingy = ('

');
			$liThingy.attr("id", "title");
			$inputBox = '<input></input>'
				$inputBox.val("title");
				$inputBox.change(function(){
					$(this).parent().attr("id", $(this).val());
					var setList = JSON.stringify($("#title-sorting").sortable("toArray"));
					window.api.post("prefs/set", {name: "titleOrder", value:setList}, function() {});
				});
			$liThingy.append($inputBox);
		$("#title-new").append($liThingy)
	});
	window.prefs.getJSONPref("titleOrder", function(val) {
		if(val == undefined) {
			val = ["HW","Read","Reading","Project","Report","Essay","Paper","Quiz","Test","Final","Exam","Midterm","Lab","Study","DocID","None","NoHW","subjectName"]
		}
		for(title in val) {
			var $titleLi = $('

');
				$titleLi.attr("id", val[title]);
				var $titleWord = $('<input></input>');
					$titleWord.val(val[title]);
					$titleWord.change(function() {
						$(this).parent().attr("id", $(this).val());
						var setList = JSON.stringify($("#title-sorting").sortable("toArray"));
						window.api.post("prefs/set", {name: "titleOrder", value:setList}, function() {});
					});
				$titleLi.append($titleWord);
			$("#title-sorting").append($titleLi);
		};
		$("#title-sorting").sortable({
			stop: function (event, ui) {
				var setList = JSON.stringify($("#title-sorting").sortable("toArray"));
				window.api.post("prefs/set", {name: "titleOrder", value:setList}, function() {});
			}
		});
		$("#title-sorting").disableSelection();
	});
	// Homework View
	window.prefs.checkToggle($("#prefs-hwView-swap"), "name-subj");
	window.prefs.checkToggle($("#prefs-hwView-color"), "titleclr");
	window.prefs.checkToggle($("#prefs-hwView-checkboxes"), "hwView-checkboxes");
});
<|endoftext|>


<commit_before>// 使用 superagent 模块 代理请求网页 + cheerio爬取节点数据
const request = require('superagent');
const cheerio = require('cheerio');
var mongoose = require('./model/db');
// var mongoose = require('mongoose');
var Article_Model = mongoose.model('Article'); // 使用User模型
var ArticleDetail = mongoose.model('ArticleDetail');

// TODO:爬取简书7日热门
function getPage() {
    request
        .get('http://www.jianshu.com/trending/weekly')
        // .query({ action: 'edit', city: 'London' }) // query string
        // .use(prefix) // Prefixes *only* this request
        // .use(nocache) // Prevents caching of *only* this request
        .end(function (err, res) {
            // Do something
            if (err) {
                console.log('request failed.' + err);
            } else {
                // 返回的text
                var show = contentFilter(res.text);
                // 遍历本地数据爬取详情页
                crawler2detail(show);
                console.log(`首页(head/request/response/html):` + res);
                console.log('\n\n\n========================all response divider =============================\n\n\n');
                console.log(show);
                // console.log(page);
            }
        });
}

function contentFilter(page) {
    var $ = cheerio.load(page);
    // 文章列表
    var list = $('.note-list');

    var data = [];

    // 注意: 必须find出note-list下的每一个 li 节点, 再each取值
    // 遍历每个item, 取出 作者, 标题, 概要, 日期, 头像
    list.find('li').each(function (item) {
        var article = $(this);
        var content = article.find('.content');
        // console.log(content + '\n')

        // var author = content.find('.author').text();
        // #note-13049926 > div > div.author > a
        var avatar = content.find('.author a img').prop('src');
        // $('.apple', '#fruits').text()
        var author = content.find('.author .name a').text().trim();
        var time = content.find('.author .name .time').prop('data-shared-at');
        // $('#fruits').children().last().text();

        // #note-13072607 > div > div.author > div > span
        // console.log(author + '\n')

        var title = content.find('.title').text().trim();
        // console.log(title + '\n')

        var abstract = content.find('.abstract').text().trim();
        // console.log(abstract + '\n')

        var href = content.find('.meta a').prop('href');
        console.log(href);

        // 对象赋值
        var articleData = {
            Author: author,
            Title: title,
            Abstract: abstract,
            Date: time,
            Avatar: avatar,
            href: href
        };
        data.push(articleData);
        // 更具Model创建数据实体
        new Article_Model({
            author: author,
            title: title,
            abstract: abstract,
            date: time,
            avatar: avatar,
            href: href
        }).save(function (err, user, count) {
            // ctx.redirect('/');
            console.log('简书7日热门 入库成功...')
        });
    });

    return data;
}

function articleFilter(articleData, href) {
    var $ = cheerio.load(articleData);
    // 文章列表
    // body > div.note > div.post > div.article > h1
    var list = $('div.note');
    // console.log(list);

    var data = [];
    var title = list.find('div.post div.article h1').text().trim();
    console.log('标题: ' + title);
    // body > div.note > div.post > div.article > div.author > a > img
    var avatar = list.find('div.post div.article div.author a img').prop('src');
    console.log('头像: ' + avatar);
    // body > div.note > div.post > div.article > div.author > div > span.name > a
    var name = list.find('div.post div.article div.author div span.name a').text().trim();
    console.log('昵称: ' + name);
    // body > div.note > div.post > div.article > div.show-content
    var content = list.find('div.post div.article div.show-content').find('p').text();
    // parse2chnChar(content);
    // .html().text();
    console.log('================================================');
    console.log('正文: ' + content);
    console.log("================================================");
    // 发表时间, 字数
    var pub_time = list.find('div.post div.article div.author div div span.publish-time').text();
    console.log(pub_time);
    var wordage = list.find('div.post div.article div.author div div span.wordage').text();
    console.log(wordage);

    new ArticleDetail({
        author: name,
        title: title,
        text: content,
        date: pub_time,
        avatar: avatar,
        wordage: wordage,
        href:href
    }).save(function (err, res, count) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log(res);
            console.log(count);
        }
    });
}

function crawler2detail(collection) {
    for (v of collection) {
        console.log('========== page_href: ' + v.href + ' ==============');
        const href = v.href;
        request.get('http://www.jianshu.com' + v.href)
            .end(function (err, resp) {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    // console.log(resp.text);
                    articleFilter(resp.text, href);
                }
            });
    }
}

function queryDatabase() {
    ArticleDetail.find(function (err, list) {
        if (err)
            console.log('failed...')
        else {
            console.log('result:' + list);
        }
    });
}

function countArtical() {
    Article_Model.count(function (err, num) {
        if (err)
            console.log('failed...')
        else {
            console.log('count:' + num);
        }
    });
}

function countArticalDetail() {
    ArticleDetail.count(function (err, num) {
        if (err)
            console.log('failed...')
        else {
            console.log('count:' + num);
        }
    });
}

function queryArticleDetailByAuthor(author) {
    ArticleDetail.findOne({'author': author}, function (err, item) {
        if (err)
            console.log('failed...');
        else
            console.log('result: ' + item);
    })
}

function queryArticleDetailByhref(href) {
    ArticleDetail.findOne({'href': href}, function (err, item) {
        if (err)
            console.log('failed...');
        else
            console.log('result: ' + item);
    })
}

// 根据 href字段 查询单条信息
function queryByhref(href) {

    Article_Model.findOne({"href": href}, (err, item) => {
        if (err)
            console.log('failed...')
        else
            console.log('result: ' + item)
    })
}

function clearDatabase() {
    // 移除整个collection数据表
    ArticleDetail.remove({}, function (err) {
        if (err)
            console.log(err);
        else
            console.log('drop collection success...');
    });
    Article_Model.remove({}, function (err) {
        if (err)
            console.log(err);
        else
            console.log('drop collection success...');
    });
}

function removeByAuthor(str) {
    if (!str)
        return;
    else
        var author = str;
    var condition = {
        $or: [{"author": author}]  // 条件满足其一
        // $and: [{"username": usr}, {"goodAt": good}]  // 同时满足条件
    }
    Article_Model.findOneAndRemove({"author": author}, function (err, doc) {
        if (err) {
            console.log(err)
            return;
        }
        console.log('remove success...');
    })
}

// getPage();
// clearDatabase();
// 查看 db.articles.find()
// 删除collections    CLI: db.articles.drop()
// removeByAuthor('阿阳sunny');
// queryDatabase();
// countArtical();
// countArticalDetail();
// queryByhref('/p/742167c2a2e8');
// queryByhref('/p/d315a19a991a');

// queryArticleDetailByAuthor('瓯南');
// queryArticleDetailByhref('/p/c5bc31531ecb');<commit_msg>爬取文章详情页完整排版内容<commit_after>// 使用 superagent 模块 代理请求网页 + cheerio爬取节点数据
const request = require('superagent');
var htmlparser = require("htmlparser2");

const cheerio = require('cheerio');
var mongoose = require('./model/db');
// var mongoose = require('mongoose');
var Article_Model = mongoose.model('Article'); // 使用User模型
var ArticleDetail = mongoose.model('ArticleDetail');

// TODO:爬取简书7日热门
function getPage() {
    request
        .get('http://www.jianshu.com/trending/weekly')
        // .query({ action: 'edit', city: 'London' }) // query string
        // .use(prefix) // Prefixes *only* this request
        // .use(nocache) // Prevents caching of *only* this request
        .end(function (err, res) {
            // Do something
            if (err) {
                console.log('request failed.' + err);
            } else {
                // 返回的text
                var show = contentFilter(res.text);
                // 遍历本地数据爬取详情页
                crawler2detail(show);
                console.log(`首页(head/request/response/html):` + res);
                console.log('\n\n\n========================all response divider =============================\n\n\n');
                console.log(show);
            }
        });
}

function contentFilter(page) {
    var $ = cheerio.load(page);
    // 文章列表
    var list = $('.note-list');

    var data = [];

    // 注意: 必须find出note-list下的每一个 li 节点, 再each取值
    // 遍历每个item, 取出 作者, 标题, 概要, 日期, 头像
    list.find('li').each(function (item) {
        var article = $(this);
        var content = article.find('.content');
        // console.log(content + '\n')

        // var author = content.find('.author').text();
        // #note-13049926 > div > div.author > a
        var avatar = content.find('.author a img').prop('src');
        // $('.apple', '#fruits').text()
        var author = content.find('.author .name a').text().trim();
        var time = content.find('.author .name .time').prop('data-shared-at');
        // $('#fruits').children().last().text();

        // #note-13072607 > div > div.author > div > span
        // console.log(author + '\n')

        var title = content.find('.title').text().trim();
        // console.log(title + '\n')

        var abstract = content.find('.abstract').text().trim();
        // console.log(abstract + '\n')

        var href = content.find('.meta a').prop('href');
        console.log(href);

        // 对象赋值
        var articleData = {
            Author: author,
            Title: title,
            Abstract: abstract,
            Date: time,
            Avatar: avatar,
            href: href
        };
        data.push(articleData);
        // 更具Model创建数据实体
        new Article_Model({
            author: author,
            title: title,
            abstract: abstract,
            date: time,
            avatar: avatar,
            href: href
        }).save(function (err, user, count) {
            // ctx.redirect('/');
            console.log('简书7日热门 入库成功...')
        });
    });

    return data;
}

function articleFilter(articleData, href) {
    var $ = cheerio.load(articleData);
    // 文章列表
    // body > div.note > div.post > div.article > h1
    var list = $('div.note');
    // console.log(list);

    var data = [];
    var title = list.find('div.post div.article h1').text().trim();
    console.log('标题: ' + title);
    // body > div.note > div.post > div.article > div.author > a > img
    var avatar = list.find('div.post div.article div.author a img').prop('src');
    console.log('头像: ' + avatar);
    // body > div.note > div.post > div.article > div.author > div > span.name > a
    var name = list.find('div.post div.article div.author div span.name a').text().trim();
    console.log('昵称: ' + name);
    // body > div.note > div.post > div.article > div.show-content
    // var content = list.find('div.post div.article div.show-content').find('p');
    var content = list.find('div.post div.article div.show-content');
        var parseContent = '';
    var parser = new htmlparser.Parser({
        onopentag: function (name, attribs) {
            // if(name === "script" && attribs.type === "text/javascript"){
            //     console.log("JS! Hooray!");
            // }
            if (name === "p") {
                console.log("p tag!");
                parseContent = parseContent + '
';
            } else if (name == 'i') {
                parseContent = parseContent + '';
            } else if (name == 'div') {
                parseContent = parseContent + '
';
            } else if (name == 'img') {
                parseContent = parseContent + '';
            } else if (name == 'h1') {
                parseContent = parseContent + '
';
            } else if (name == 'b') {
                parseContent = parseContent + '';
            } else if (name == 'br') {
                parseContent = parseContent + '
';
            }
        },
        ontext: function (text) {
            console.log("-->", text);
            parseContent = parseContent + text;
        },
        onclosetag: function (tagname) {
            if (tagname === "p") {
                console.log("p tag end!");
                parseContent = parseContent + '
';
            } else if (name == 'i') {
                parseContent = parseContent + '';
            } else if (name == 'h1') {
                parseContent = parseContent + '
';
            } else if (name == 'b') {
                parseContent = parseContent + '';
            } else if (name == 'br') {
                parseContent = parseContent + '
';
            }
        }
    }, {decodeEntities: true});
    // parser.write(content);
    // parser.end();
    // console.log(`===========================\n` + parseContent + `=============================\n`);

    // console.log('================================================');
    // console.log('正文: ' + content);
    // console.log("================================================");
    // 发表时间, 字数
    var pub_time = list.find('div.post div.article div.author div div span.publish-time').text();
    console.log(pub_time);
    var wordage = list.find('div.post div.article div.author div div span.wordage').text();
    console.log(wordage);

    new ArticleDetail({
        author: name,
        title: title,
        text: content,
        date: pub_time,
        avatar: avatar,
        wordage: wordage,
        href: href
    }).save(function (err, res, count) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log(res);
            console.log(count);
        }
    });
}

function crawler2detail(collection) {
    for (v of collection) {
        console.log('========== page_href: ' + v.href + ' ==============');
        const href = v.href;
        request.get('http://www.jianshu.com' + v.href)
            .end(function (err, resp) {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    // console.log(resp.text);
                    articleFilter(resp.text, href);
                }
            });
    }
}

function queryDatabase() {
    ArticleDetail.find(function (err, list) {
        if (err)
            console.log('failed...')
        else {
            console.log('result:' + list);
        }
    });
}

function countArtical() {
    Article_Model.count(function (err, num) {
        if (err)
            console.log('failed...')
        else {
            console.log('count:' + num);
        }
    });
}

function countArticalDetail() {
    ArticleDetail.count(function (err, num) {
        if (err)
            console.log('failed...')
        else {
            console.log('count:' + num);
        }
    });
}

function queryArticleDetailByAuthor(author) {
    ArticleDetail.findOne({'author': author}, function (err, item) {
        if (err)
            console.log('failed...');
        else
            console.log('result: ' + item);
    })
}

function queryArticleDetailByhref(href) {
    ArticleDetail.findOne({'href': href}, function (err, item) {
        if (err)
            console.log('failed...');
        else
            console.log('result: ' + item);
    })
}

// 根据 href字段 查询单条信息
function queryByhref(href) {

    Article_Model.findOne({"href": href}, (err, item) => {
        if (err)
            console.log('failed...')
        else
            console.log('result: ' + item)
    })
}

function clearDatabase() {
    // 移除整个collection数据表
    ArticleDetail.remove({}, function (err) {
        if (err)
            console.log(err);
        else
            console.log('drop collection success...');
    });
    Article_Model.remove({}, function (err) {
        if (err)
            console.log(err);
        else
            console.log('drop collection success...');
    });
}

function removeByAuthor(str) {
    if (!str)
        return;
    else
        var author = str;
    var condition = {
        $or: [{"author": author}]  // 条件满足其一
        // $and: [{"username": usr}, {"goodAt": good}]  // 同时满足条件
    }
    Article_Model.findOneAndRemove({"author": author}, function (err, doc) {
        if (err) {
            console.log(err)
            return;
        }
        console.log('remove success...');
    })
}

getPage();
// clearDatabase();
// 查看 db.articles.find()
// 删除collections    CLI: db.articles.drop()
// removeByAuthor('阿阳sunny');
// queryDatabase();
// countArtical();
// countArticalDetail();
// queryByhref('/p/d315a19a991a');

// queryArticleDetailByAuthor('瓯南');
// queryArticleDetailByhref('/p/c5bc31531ecb');<|endoftext|>


<commit_before>import SelectItem from "@/objects/SelectItem";

export default {
  id: 0,
  company_id: 0,
  company: SelectItem,
  company_name: "",
  kind_id: 0,
  kind: SelectItem,
  kind_name: "",
  date_of_practice: "",
  topic: "",
  note: ""
};
<commit_msg>remove unused fields<commit_after>import SelectItem from "@/objects/SelectItem";

export default {
  id: 0,
  company_id: 0,
  company: SelectItem,
  kind_id: 0,
  kind: SelectItem,
  date_of_practice: "",
  topic: "",
  note: ""
};
<|endoftext|>


<commit_before>// Global prototypes & extensions
String.prototype.lines = function() { return this.split(/\r|\r\n|\n/); };
String.prototype.lineCount = function() { return this.lines().length; };
jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});

/* Constants */
var delimiters = new RegExp("[ ,.]");
var modifiers = [ 9, 13, 16, 17, 18 ];
var minimum_score = 260;

/* Globals */
var rhymes_cache = [];
var last_line_num = -1;
var rhyme_scheme = "AABB";

function words_from_line(line)
{
  var words = line.split(delimiters);
  var output = [];
  for (var i = 0; i < words.length; i++) {
    var word = words[i].toLowerCase().replace(/[^a-z]/g,"");
    if (word.length > 0) {
      output.push(word);
    }
  }
  return output;
}

function getRhymes(word, callback, line_values) {
  if (word === undefined || word.length < 1) {
    return;
  }
  //console.log("CALLING RHYMEBRAIN");
  var rhymeURL = "http://rhymebrain.com/talk?function=getRhymes&word=";

  $.ajax({
    type: 'GET',
    dataType: 'jsonp',
    jsonp: 'jsonp',
    url: (rhymeURL + word),
    success: function(response){
      var rhymes = [word]; /* Include the word in the suggestion list. */
      var j = response.length;
      response.sort(function(a,b){return b.score-a.score;});
      var firstbad = true;
      var total = 15;

      rhymes.push("#Matches");

      for (var i = 0;  i < j && i < total; i++) {
        if (response[i].word.length < 2) {
          total++;
          continue;
        }

        if (response[i].score < minimum_score && firstbad) {
          firstbad = false;
          rhymes.push("#Near Matches");
        }
        rhymes.push(response[i].word); /* word, syllables, score, freq flags */
      }
      callback = callback || function(rhymewords){console.log(rhymewords);};
      callback(rhymes, line_values);
    }
  });
}

function getLineCount() {
  var numlines = 0;
  var text = $('.poetry-text').val().lines();

  $.each(text, function(){
    alert(getSyllableCount(this));
  });
}

function getSyllableCount(word) {
  if (word.length === 0){
    return 0;
  }

  var syllableCount = 0,
  prefixSuffixCount = 0,
  wordPartCount = 0;

  // Prepare word - make lower case and remove non-word characters
  word = word.toLowerCase().replace(/[^a-z]/g,"");

  // Specific common exceptions that don't follow the rule set below are handled individually
  // Array of problem words (with word as key, syllable count as value)
  var problemWords = {
    "simile":   3,
    "forever":    3,
    "shoreline":  2
  };

  // Return if we've hit one of those...
  if (problemWords[word]) {
    return problemWords[word];
  }

  // These syllables would be counted as two but should be one
  var subSyllables = [
    /cial/,
    /tia/,
    /cius/,
    /cious/,
    /giu/,
    /ion/,
    /iou/,
    /sia$/,
    /[^aeiuoyt]{2,}ed$/,
    /.ely$/,
    /[cg]h?e[rsd]?$/,
    /rved?$/,
    /[aeiouy][dt]es?$/,
    /[aeiouy][^aeiouydt]e[rsd]?$/,
    /^[dr]e[aeiou][^aeiou]+$/, // Sorts out deal, deign etc
    /[aeiouy]rse$/ // Purse, hearse
  ];

  // These syllables would be counted as one but should be two
  var addSyllables = [
    /ia/,
    /riet/,
    /dien/,
    /iu/,
    /io/,
    /ii/,
    /[aeiouym]bl$/,
    /[aeiou]{3}/,
    /^mc/,
    /ism$/,
    /([^aeiouy])\1l$/,
    /[^l]lien/,
    /^coa[dglx]./,
    /[^gq]ua[^auieo]/,
    /dnt$/,
    /uity$/,
    /ie(r|st)$/
  ];

  // Single syllable prefixes and suffixes
  var prefixSuffix = [
    /^un/,
    /^fore/,
    /ly$/,
    /less$/,
    /ful$/,
    /ers?$/,
    /ings?$/
  ];

  // Remove prefixes and suffixes and count how many were taken
  prefixSuffix.forEach(function(regex) {
    if (word.match(regex)) {
      word = word.replace(regex,"");
      prefixSuffixCount ++;
    }
  });

  wordPartCount = word
    .split(/[^aeiouy]+/ig)
    .filter(function(wordPart) {
      return !!wordPart.replace(/\s+/ig,"").length;
    })
    .length;

  // Get preliminary syllable count...
  syllableCount = wordPartCount + prefixSuffixCount;

  // Some syllables do not follow normal rules - check for them
  subSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount --;
    }
  });

  addSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount ++;
    }
  });

  return syllableCount || 1;
}

// Given a cursor position & the string value of the input text area,
// return the line number on which the cursor in the text area resides.
function get_line(pos, text)
{
  var lines = text.lines();
  var count = 0;
  var i = 0;
  while (i < pos) {
    i+=lines[count].length+1;
    if (i > pos){
      break;
    }
    count++;
  }
  return count;
}

// Respond to changes in the  Rhyme Scheme
$("#scheme").change(function(event)
{
  var raw_scheme = $("#scheme").val();
  rhyme_scheme = raw_scheme.toUpperCase().replace(/[^A-Z]/g,"");
  if (raw_scheme !== rhyme_scheme) {
    $("#scheme").val(rhyme_scheme);
  }
});

// Respond to changes in the textarea
$(window).keyup(function(event)
{
  // Ignore events triggered when the textarea doesn't have focus, and from modifiers.
  if (!jQuery("textarea.poetry-text").is(":focus") ||
      modifiers.indexOf(event.keyCode) >= 0) {
    return;
  }
  var text = jQuery("textarea.poetry-text").val();
  var syllable_area = "";
  var lines = text.lines();
  var iter;
  for (iter = 0; iter < lines.length; iter++) {
    var words = words_from_line(lines[iter]);
    var word_iter;
    var syllable_count = 0;
    for (word_iter = 0; word_iter < words.length; word_iter++){
      syllable_count+=getSyllableCount(words[word_iter]);
    }
    syllable_area += syllable_count+"
";
  }
  $('div.syllable_counts').html(syllable_area);
  // After finding the syllable count, find all matching words
  var pattern = rhyme_scheme;
  var caret_pos = jQuery("textarea.poetry-text")[0].selectionStart;
  var line_num = get_line(caret_pos, text);
  if (line_num === last_line_num) {
    return;
  }
  last_line_num = line_num;
  var word = get_word_to_rhyme(line_num, pattern, lines);
  populate_rhymes(word, lines);
});

function get_word_to_rhyme(line_num, pattern, lines)
{
  if (line_num < 1) {
    return undefined;
  }
  var associations = [];
  var pattern_iter = 0;
  for (var i = 0; i <= line_num; i++) {
    if (lines[i].length < 1) {
      associations.push(undefined);
      continue;
    }
    associations.push(pattern[pattern_iter % pattern.length ]);
    pattern_iter++;
  }

  var ident = associations[line_num];
  var match = associations.lastIndexOf(ident, line_num-1);
  if (match < 0) {
    return undefined;
  }
  var words = words_from_line(lines[match]);
  return words[words.length - 1];
}

function populate_rhymes(word, lines)
{
  if (word === undefined) {
    populate_rhyme_list(undefined,undefined,true); // Clear list
    return;
  }

  var rhymes = get_cached_rhymes(word);
  if (rhymes !== undefined) {
    populate_rhyme_list(remove_used_words(rhymes, lines),lines,true);
    return;
  }

  getRhymes(word, populate_rhyme_list, lines);
}

function get_cached_rhymes(word)
{
  for (var i = 0; i < rhymes_cache.length; i++) {
    var current_list = rhymes_cache[i];
    for (var j = 0; j < current_list.length; j++) {
      if (word === current_list[j]) {
        return current_list;
      }
    }
  }
  return undefined;
}

function populate_rhyme_list(rhymes, lines, already_cached)
{
  /* Javascript version of default args */
  var cached = false;
  if (typeof(already_cached) !== undefined && already_cached === true) {
    cached = true;
  }

  var rhymes_div = "";
  if (rhymes !== undefined && rhymes.length > 0) {
    if (!cached) {
      rhymes_cache.push(rhymes);
      rhymes = remove_used_words(rhymes, lines);
    }
    for (var i = 0; i < rhymes.length; i++) {
      var start_tag = "";
      var end_tag = "
";
      if (rhymes[i].indexOf("#") === 0) {
        start_tag+="
";
        end_tag="
";
        rhymes[i] = rhymes[i].substr(1);
      }
      rhymes_div += start_tag + rhymes[i] + end_tag;
    }
  }
  $('div.sidebar').html(rhymes_div);
}

function remove_used_words(rhymes, lines)
{
  var unique_rhymes = [];
  for (var i = 0; i < rhymes.length; i++) {
    var unique = true;
    var rhyme = rhymes[i];
    for (var j = 0; j < lines.length; j++) {
      var words = words_from_line(lines[j]);
      if (words.indexOf(rhyme) >= 0) {
        unique = false;
        break;
      }
    }
    if (unique) {
      unique_rhymes.push(rhyme);
    }
  }
  return unique_rhymes;
}

$('.linked').scroll(function(){
    $('.linked').scrollTop($(this).scrollTop());
});

//var poem = $('.poetry-text')[0];
//function get_sentiment(){
  //var text = poem.value;
  //console.log("POEM: " + text);
  //$.ajax({
    //type: 'GET',
    //data: {poem: text},
    //url: 'home/sentiment/'+text,
    //success: function(response) {
      //console.log(response);
    //}
  //});
//}
//get_sentiment();
<commit_msg>Added more problem words to list<commit_after>// Global prototypes & extensions
String.prototype.lines = function() { return this.split(/\r|\r\n|\n/); };
String.prototype.lineCount = function() { return this.lines().length; };
jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});

/* Constants */
var delimiters = new RegExp("[ ,.]");
var modifiers = [ 9, 13, 16, 17, 18 ];
var minimum_score = 260;

/* Globals */
var rhymes_cache = [];
var last_line_num = -1;
var rhyme_scheme = "AABB";

function words_from_line(line)
{
  var words = line.split(delimiters);
  var output = [];
  for (var i = 0; i < words.length; i++) {
    var word = words[i].toLowerCase().replace(/[^a-z]/g,"");
    if (word.length > 0) {
      output.push(word);
    }
  }
  return output;
}

function getRhymes(word, callback, line_values) {
  if (word === undefined || word.length < 1) {
    return;
  }
  //console.log("CALLING RHYMEBRAIN");
  var rhymeURL = "http://rhymebrain.com/talk?function=getRhymes&word=";

  $.ajax({
    type: 'GET',
    dataType: 'jsonp',
    jsonp: 'jsonp',
    url: (rhymeURL + word),
    success: function(response){
      var rhymes = [word]; /* Include the word in the suggestion list. */
      var j = response.length;
      response.sort(function(a,b){return b.score-a.score;});
      var firstbad = true;
      var total = 15;

      rhymes.push("#Matches");

      for (var i = 0;  i < j && i < total; i++) {
        if (response[i].word.length < 2) {
          total++;
          continue;
        }

        if (response[i].score < minimum_score && firstbad) {
          firstbad = false;
          rhymes.push("#Near Matches");
        }
        rhymes.push(response[i].word); /* word, syllables, score, freq flags */
      }
      callback = callback || function(rhymewords){console.log(rhymewords);};
      callback(rhymes, line_values);
    }
  });
}

function getLineCount() {
  var numlines = 0;
  var text = $('.poetry-text').val().lines();

  $.each(text, function(){
    alert(getSyllableCount(this));
  });
}

function getSyllableCount(word) {
  if (word.length === 0){
    return 0;
  }

  var syllableCount = 0,
  prefixSuffixCount = 0,
  wordPartCount = 0;

  // Prepare word - make lower case and remove non-word characters
  word = word.toLowerCase().replace(/[^a-z]/g,"");

  // Specific common exceptions that don't follow the rule set below are handled individually
  // Array of problem words (with word as key, syllable count as value)
  var problemWords = {
    "simile":   3,
    "forever":    3,
    "shoreline":  2,
    "anyone":     3,
    "watch":      1,
    "false":      1,
    "poetry":     3
  };

  // Return if we've hit one of those...
  if (problemWords[word]) {
    return problemWords[word];
  }

  // These syllables would be counted as two but should be one
  var subSyllables = [
    /cial/,
    /tia/,
    /cius/,
    /cious/,
    /giu/,
    /ion/,
    /iou/,
    /sia$/,
    /[^aeiuoyt]{2,}ed$/,
    /.ely$/,
    /[cg]h?e[rsd]?$/,
    /rved?$/,
    /[aeiouy][dt]es?$/,
    /[aeiouy][^aeiouydt]e[rsd]?$/,
    /^[dr]e[aeiou][^aeiou]+$/, // Sorts out deal, deign etc
    /[aeiouy]rse$/ // Purse, hearse
  ];

  // These syllables would be counted as one but should be two
  var addSyllables = [
    /ia/,
    /riet/,
    /dien/,
    /iu/,
    /io/,
    /ii/,
    /[aeiouym]bl$/,
    /[aeiou]{3}/,
    /^mc/,
    /ism$/,
    /([^aeiouy])\1l$/,
    /[^l]lien/,
    /^coa[dglx]./,
    /[^gq]ua[^auieo]/,
    /dnt$/,
    /uity$/,
    /ie(r|st)$/
  ];

  // Single syllable prefixes and suffixes
  var prefixSuffix = [
    /^un/,
    /^fore/,
    /ly$/,
    /less$/,
    /ful$/,
    /ers?$/,
    /ings?$/
  ];

  // Remove prefixes and suffixes and count how many were taken
  prefixSuffix.forEach(function(regex) {
    if (word.match(regex)) {
      word = word.replace(regex,"");
      prefixSuffixCount ++;
    }
  });

  wordPartCount = word
    .split(/[^aeiouy]+/ig)
    .filter(function(wordPart) {
      return !!wordPart.replace(/\s+/ig,"").length;
    })
    .length;

  // Get preliminary syllable count...
  syllableCount = wordPartCount + prefixSuffixCount;

  // Some syllables do not follow normal rules - check for them
  subSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount --;
    }
  });

  addSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount ++;
    }
  });

  return syllableCount || 1;
}

// Given a cursor position & the string value of the input text area,
// return the line number on which the cursor in the text area resides.
function get_line(pos, text)
{
  var lines = text.lines();
  var count = 0;
  var i = 0;
  while (i < pos) {
    i+=lines[count].length+1;
    if (i > pos){
      break;
    }
    count++;
  }
  return count;
}

// Respond to changes in the  Rhyme Scheme
$("#scheme").change(function(event)
{
  var raw_scheme = $("#scheme").val();
  rhyme_scheme = raw_scheme.toUpperCase().replace(/[^A-Z]/g,"");
  if (raw_scheme !== rhyme_scheme) {
    $("#scheme").val(rhyme_scheme);
  }
});

// Respond to changes in the textarea
$(window).keyup(function(event)
{
  // Ignore events triggered when the textarea doesn't have focus, and from modifiers.
  if (!jQuery("textarea.poetry-text").is(":focus") ||
      modifiers.indexOf(event.keyCode) >= 0) {
    return;
  }
  var text = jQuery("textarea.poetry-text").val();
  var syllable_area = "";
  var lines = text.lines();
  var iter;
  for (iter = 0; iter < lines.length; iter++) {
    var words = words_from_line(lines[iter]);
    var word_iter;
    var syllable_count = 0;
    for (word_iter = 0; word_iter < words.length; word_iter++){
      syllable_count+=getSyllableCount(words[word_iter]);
    }
    syllable_area += syllable_count+"
";
  }
  $('div.syllable_counts').html(syllable_area);
  // After finding the syllable count, find all matching words
  var pattern = rhyme_scheme;
  var caret_pos = jQuery("textarea.poetry-text")[0].selectionStart;
  var line_num = get_line(caret_pos, text);
  if (line_num === last_line_num) {
    return;
  }
  last_line_num = line_num;
  var word = get_word_to_rhyme(line_num, pattern, lines);
  populate_rhymes(word, lines);
});

function get_word_to_rhyme(line_num, pattern, lines)
{
  if (line_num < 1) {
    return undefined;
  }
  var associations = [];
  var pattern_iter = 0;
  for (var i = 0; i <= line_num; i++) {
    if (lines[i].length < 1) {
      associations.push(undefined);
      continue;
    }
    associations.push(pattern[pattern_iter % pattern.length ]);
    pattern_iter++;
  }

  var ident = associations[line_num];
  var match = associations.lastIndexOf(ident, line_num-1);
  if (match < 0) {
    return undefined;
  }
  var words = words_from_line(lines[match]);
  return words[words.length - 1];
}

function populate_rhymes(word, lines)
{
  if (word === undefined) {
    populate_rhyme_list(undefined,undefined,true); // Clear list
    return;
  }

  var rhymes = get_cached_rhymes(word);
  if (rhymes !== undefined) {
    populate_rhyme_list(remove_used_words(rhymes, lines),lines,true);
    return;
  }

  getRhymes(word, populate_rhyme_list, lines);
}

function get_cached_rhymes(word)
{
  for (var i = 0; i < rhymes_cache.length; i++) {
    var current_list = rhymes_cache[i];
    for (var j = 0; j < current_list.length; j++) {
      if (word === current_list[j]) {
        return current_list;
      }
    }
  }
  return undefined;
}

function populate_rhyme_list(rhymes, lines, already_cached)
{
  /* Javascript version of default args */
  var cached = false;
  if (typeof(already_cached) !== undefined && already_cached === true) {
    cached = true;
  }

  var rhymes_div = "";
  if (rhymes !== undefined && rhymes.length > 0) {
    if (!cached) {
      rhymes_cache.push(rhymes);
      rhymes = remove_used_words(rhymes, lines);
    }
    for (var i = 0; i < rhymes.length; i++) {
      var start_tag = "";
      var end_tag = "
";
      if (rhymes[i].indexOf("#") === 0) {
        start_tag+="
";
        end_tag="
";
        rhymes[i] = rhymes[i].substr(1);
      }
      rhymes_div += start_tag + rhymes[i] + end_tag;
    }
  }
  $('div.sidebar').html(rhymes_div);
}

function remove_used_words(rhymes, lines)
{
  var unique_rhymes = [];
  for (var i = 0; i < rhymes.length; i++) {
    var unique = true;
    var rhyme = rhymes[i];
    for (var j = 0; j < lines.length; j++) {
      var words = words_from_line(lines[j]);
      if (words.indexOf(rhyme) >= 0) {
        unique = false;
        break;
      }
    }
    if (unique) {
      unique_rhymes.push(rhyme);
    }
  }
  return unique_rhymes;
}

$('.linked').scroll(function(){
    $('.linked').scrollTop($(this).scrollTop());
});

//var poem = $('.poetry-text')[0];
//function get_sentiment(){
  //var text = poem.value;
  //console.log("POEM: " + text);
  //$.ajax({
    //type: 'GET',
    //data: {poem: text},
    //url: 'home/sentiment/'+text,
    //success: function(response) {
      //console.log(response);
    //}
  //});
//}
//get_sentiment();
<|endoftext|>