<commit_before>$(document).ready(function() {
    // Autoresize textareas
    autosize($('textarea'))

    // Confirm deleting
    $('button.delete').on('click', function() {
        var result = confirm('Do you really want to delete this item?')
        if (!result) return false
    })

    // Prepare studying
    if ($('#study').length != 0) {
        var currentIndex = 0
        var correctOnce = Object.keys(new Int8Array($('#study li').length)).map(function() { return false })

        var showCard = function(index) {
            $('#study').removeClass('reveal').removeClass('revealnotes')
            $('#study li').css('display', 'none').eq(index).css('display', 'block')

            currentIndex = index

            var percent = Math.round(correctOnce.filter(function(x) { return x }).length * 100 / correctOnce.length)
            $('#progress span').css('width', percent + '%')
        }

        var nextCard = function() {
            if (correctOnce.every(function(x) { return x })) {
                $('form').get(0).submit()
                return
            }

            var i = (currentIndex + 1) % correctOnce.length

            while (correctOnce[i]) {
                if (i + 1 == correctOnce.length) i = -1
                i++
            }

            showCard(i)
        }

        $('#study input[type="checkbox"]').attr('checked', '')
        $('#study label, button[type="submit"]').css('display', 'none')
        $('header').after($('<div/>', { id: 'progress' }).append($('<span/>')))

        $('#study + p').append($('<button/>', {
                text: 'Reveal',
                class: 'reveal',
                type: 'button'
            }).on('click', function() {
                $('#study').addClass('reveal')
                return false
        })).append($('<button/>', {
                text: 'Show Notes',
                class: 'shownotes',
                type: 'button'
            }).on('click', function() {
                $('#study').addClass('revealnotes')
                return false
        })).append($('<button/>', {
                text: 'Show Again',
                class: 'showagain',
                type: 'button'
            }).on('click', function() {
                $('#study input[type="checkbox"]').eq(currentIndex).attr('checked', false)
                nextCard()
                return false
        })).append($('<button/>', {
                text: 'Next Card',
                class: 'nextcard',
                type: 'button'
            }).on('click', function() {
                correctOnce[currentIndex] = true
                nextCard()
                return false
        }))

        showCard(0)
    }

    // Infinite adding
    if ($('#addlist').length != 0) {
        var $template = $('#addlist li:last-child').css('display', 'none')

        $('#addlist + p').prepend($('<button/>', {
            text: 'Add Items',
            type: 'button'
        }).on('click', function() {
            for (var i = 0; i < 5; i++) {
                $template.before($template.clone().css('display', 'block'))
            }

            return false
        }))
    }

    // Add edit links to vocabulary page
    if ($('section.back + textarea[name="back"], section.notes + textarea[name="notes"]').length != 0) {
        $('section.back').parents('form').find('button[type="submit"]')
            .css('display', 'none')

        $('section.back, section.notes').each(function() {
            if ($(this).find('.tasks').length != 0) return

            $(this).prepend($('<p/>', {
                class: 'tasks'
            }).append($('<a/>', {
                href: '#',
                text: 'Edit'
            }).on('click', function() {
                $(this).parents('section').css('display', 'none')
                    .next('textarea').css('display', 'block').get(0).focus()
                $(this).parents('form').find('button[type="submit"]')
                    .css('display', 'inline-block')

                return false
            })))
        })

        $('section.back + textarea[name="back"], section.notes + textarea[name="notes"]').css('display', 'none')
    }
})
<commit_msg>Fix autosizer on infinite adding<commit_after>$(document).ready(function() {
    // Autoresize textareas
    autosize($('textarea'))

    // Confirm deleting
    $('button.delete').on('click', function() {
        var result = confirm('Do you really want to delete this item?')
        if (!result) return false
    })

    // Prepare studying
    if ($('#study').length != 0) {
        var currentIndex = 0
        var correctOnce = Object.keys(new Int8Array($('#study li').length)).map(function() { return false })

        var showCard = function(index) {
            $('#study').removeClass('reveal').removeClass('revealnotes')
            $('#study li').css('display', 'none').eq(index).css('display', 'block')

            currentIndex = index

            var percent = Math.round(correctOnce.filter(function(x) { return x }).length * 100 / correctOnce.length)
            $('#progress span').css('width', percent + '%')
        }

        var nextCard = function() {
            if (correctOnce.every(function(x) { return x })) {
                $('form').get(0).submit()
                return
            }

            var i = (currentIndex + 1) % correctOnce.length

            while (correctOnce[i]) {
                if (i + 1 == correctOnce.length) i = -1
                i++
            }

            showCard(i)
        }

        $('#study input[type="checkbox"]').attr('checked', '')
        $('#study label, button[type="submit"]').css('display', 'none')
        $('header').after($('<div/>', { id: 'progress' }).append($('<span/>')))

        $('#study + p').append($('<button/>', {
                text: 'Reveal',
                class: 'reveal',
                type: 'button'
            }).on('click', function() {
                $('#study').addClass('reveal')
                return false
        })).append($('<button/>', {
                text: 'Show Notes',
                class: 'shownotes',
                type: 'button'
            }).on('click', function() {
                $('#study').addClass('revealnotes')
                return false
        })).append($('<button/>', {
                text: 'Show Again',
                class: 'showagain',
                type: 'button'
            }).on('click', function() {
                $('#study input[type="checkbox"]').eq(currentIndex).attr('checked', false)
                nextCard()
                return false
        })).append($('<button/>', {
                text: 'Next Card',
                class: 'nextcard',
                type: 'button'
            }).on('click', function() {
                correctOnce[currentIndex] = true
                nextCard()
                return false
        }))

        showCard(0)
    }

    // Infinite adding
    if ($('#addlist').length != 0) {
        var $template = $('#addlist li:last-child').css('display', 'none')

        $('#addlist + p').prepend($('<button/>', {
            text: 'Add Items',
            type: 'button'
        }).on('click', function() {
            for (var i = 0; i < 5; i++) {
                var $clone = $template.clone()
                $template.before($clone.css('display', 'block'))
                autosize($clone.find('textarea'))
            }

            return false
        }))
    }

    // Add edit links to vocabulary page
    if ($('section.back + textarea[name="back"], section.notes + textarea[name="notes"]').length != 0) {
        $('section.back').parents('form').find('button[type="submit"]')
            .css('display', 'none')

        $('section.back, section.notes').each(function() {
            if ($(this).find('.tasks').length != 0) return

            $(this).prepend($('<p/>', {
                class: 'tasks'
            }).append($('<a/>', {
                href: '#',
                text: 'Edit'
            }).on('click', function() {
                $(this).parents('section').css('display', 'none')
                    .next('textarea').css('display', 'block').get(0).focus()
                $(this).parents('form').find('button[type="submit"]')
                    .css('display', 'inline-block')

                return false
            })))
        })

        $('section.back + textarea[name="back"], section.notes + textarea[name="notes"]').css('display', 'none')
    }
})
<|endoftext|>


<commit_before>// create a mask over the header with the splash.css style
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
	// mobile
	setLogoSize();
	$('.background').css('background-image', 'url(' + getBackgroundString(selectRandomBackground()) + ')');
	$('.splash > .container').css('display', 'table-cell');
	$('.splash').delay(1000).fadeOut(500);
} else {
	// everything else
	setLogoSize();
	window.addEventListener('resize', function(event) {
		setLogoSize();
	});
	$('.splash > .container').css('display', 'table-cell');
	$('.splash > .container').addClass('zoomInEntrance').queue(function(next) {
		var image = getBackgroundString(selectRandomBackground()), img = $('<img />');
		img.bind('load', function() {
			$('.splash > .container').delay(1000).queue(function(next) {
				// show the page after the background has loaded
				if ($(this).hasClass('zoomInEntrance')) {
					$(this).removeClass('zoomInEntrance');
					$(this).delay(500).addClass('zoomInExit').delay(400).parent().fadeOut();
				}
				next();
			});
		});
		img.attr('src', image);
		$('.background').css('background-image', 'url(' + image + ')');
		// if the background takes longer than four seconds to load, show the page anyways.
		$('.background').delay(4000).queue(function(next) {
			if ($(this).hasClass('zoomInEntrance')) {
				$(this).removeClass('zoomInEntrance');
				$(this).delay(500).addClass('zoomInExit').delay(400).parent().fadeOut();
			}
			next();
		});
		next();
	});

}

// loading sequence
function setLogoSize() {
	var height = $(window).height();
	$('.splash .container').css('height', height);
	$('.splash .container').css('max-height', height);
}

function getBackgroundString(image) {
	var size = '320';
	var width = $(window).width();
	if (width <= 640) {
		size = '640';
	} else if (width <= 800) {
		size = '800';
	} else if (width <= 1024) {
		size = '1024';
	} else if (width <= 1600) {
		size = '1600';
	} else {
		size = '2048';
	}
	return './images/backgrounds/' + image + '_' + size + '.jpg';
}

function selectRandomBackground() {
	var numImages = 11;
	return Math.floor(Math.random() * (numImages + 1));
}<commit_msg>background delay timeout<commit_after>// create a mask over the header with the splash.css style
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
	// mobile
	setLogoSize();
	$('.background').css('background-image', 'url(' + getBackgroundString(selectRandomBackground()) + ')');
	$('.splash > .container').css('display', 'table-cell');
	$('.splash').delay(1000).fadeOut(500);
} else {
	// everything else
	setLogoSize();
	window.addEventListener('resize', function(event) {
		setLogoSize();
	});
	$('.splash > .container').css('display', 'table-cell');
	$('.splash > .container').addClass('zoomInEntrance').queue(function(next) {
		var image = getBackgroundString(selectRandomBackground()), img = $('<img />');
		img.bind('load', function() {
			$('.splash > .container').delay(1000).queue(function(next) {
				// show the page after the background has loaded
				if ($(this).hasClass('zoomInEntrance')) {
					$(this).removeClass('zoomInEntrance');
					$(this).delay(500).addClass('zoomInExit').delay(400).parent().fadeOut();
				}
				next();
			});
		});
		img.attr('src', image);
		$('.background').css('background-image', 'url(' + image + ')');
		// if the background takes longer than four seconds to load, show the page anyways.
		$('.splash > .container').delay(4000).queue(function(next) {
			if ($(this).hasClass('zoomInEntrance')) {
				$(this).removeClass('zoomInEntrance');
				$(this).delay(500).addClass('zoomInExit').delay(400).parent().fadeOut();
			}
			next();
		});
		next();
	});

}

// loading sequence
function setLogoSize() {
	var height = $(window).height();
	$('.splash .container').css('height', height);
	$('.splash .container').css('max-height', height);
}

function getBackgroundString(image) {
	var size = '320';
	var width = $(window).width();
	if (width <= 640) {
		size = '640';
	} else if (width <= 800) {
		size = '800';
	} else if (width <= 1024) {
		size = '1024';
	} else if (width <= 1600) {
		size = '1600';
	} else {
		size = '2048';
	}
	return './images/backgrounds/' + image + '_' + size + '.jpg';
}

function selectRandomBackground() {
	var numImages = 11;
	return Math.floor(Math.random() * (numImages + 1));
}<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var color = require('ansi-color').set;
var hex = require('hexer');
var TypedError = require('error/typed');
var util = require('util');
var Result = require('./result');

var ShortReadError = TypedError({
    type: 'short-read',
    message: 'short read, {remaining} byte left over after consuming {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var ShortWriteError = TypedError({
    type: 'short-write',
    message: 'short write, {remaining} byte left over after writing {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var emptyBuffer = Buffer(0);

function fromBuffer(struct, buffer, offset) {
    return fromBufferResult(struct, buffer, offset).toValue();
}

function byteLength(struct, value) {
    return byteLengthResult(struct, value).toValue();
}

function toBuffer(struct, value) {
    return toBufferResult(struct, value).toValue();
}

function intoBuffer(struct, buffer, value) {
    return intoBufferResult(struct, buffer, value).toValue();
}

// The "Tuple" methods are deprecated

/* istanbul ignore next */
function fromBufferTuple(struct, buffer, offset) {
    return fromBufferResult(struct, buffer, offset).toTuple();
}

/* istanbul ignore next */
function byteLengthTuple(struct, value) {
    return byteLengthResult(struct, value).toTuple();
}

/* istanbul ignore next */
function toBufferTuple(struct, value) {
    return toBufferResult(struct, value).toTuple();
}

/* istanbul ignore next */
function intoBufferTuple(struct, buffer, value) {
    return intoBufferResult(struct, buffer, value).toTuple();
}

function fromBufferResult(struct, buffer, offset) {
    offset = offset || 0;
    var res = struct.readFrom(buffer, offset);
    offset = res.offset;
    var err = res.err;
    if (!err && offset !== buffer.length) {
        err = ShortReadError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        });
    }
    if (err) {
        if (err.offset === undefined) err.offset = offset;
        if (err.buffer === undefined) err.buffer = buffer;
    }
    return new Result(err, res.value);
}

function byteLengthResult(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return new Result(lenRes.err, 0);
    else return new Result(null, lenRes.length);
}

function toBufferResult(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return new Result(lenRes.err, emptyBuffer);
    var length = lenRes.length;
    var buffer = new Buffer(length);
    // buffer.fill(0); TODO option
    return intoBufferResult(struct, buffer, value);
}

function intoBufferResult(struct, buffer, value) {
    var writeRes = struct.writeInto(value, buffer, 0);
    if (writeRes.err) {
        // istanbul ignore else
        if (!Buffer.isBuffer(writeRes.err.buffer)) writeRes.err.buffer = buffer;
        if (typeof writeRes.err.offset !== 'number') writeRes.err.offset = writeRes.offset;
        return new Result(writeRes.err, buffer);
    }
    var offset = writeRes.offset;
    if (offset !== buffer.length) {
        return new Result(ShortWriteError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        }), buffer);
    }
    return new Result(null, buffer);
}

// istanbul ignore next TODO
function formatError(err, options) {
    options = options || {};
    var name = err.name || err.constructor.name;
    var str = util.format('%s: %s\n', name, err.message);
    if (Buffer.isBuffer(err.buffer)) {
        if (options.color) {
            str += formatBufferColored(err, options);
        } else {
            str += formatBufferUncolored(err, options);
        }
        str += '\n';
    }
    return str;
}

// istanbul ignore next TODO
function formatBufferColored(err, options) {
    options = options || {};
    var markColor = options.markColor || 'red+bold';
    var errColor = typeof markColor === 'function' ? markColor : function(str) {
        return color(str, markColor);
    };

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var within = false;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        if (hasEnd) {
        opts.decorateHexen = decorateRangedError;
        opts.decorateHuman = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
            opts.decorateHuman = decorateError;
        }
    }
    return hex(err.buffer, opts);

    function decorateRangedError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            within = totalOffset !== err.endOffset-1;
            return errColor(str);
        } else if (totalOffset === err.endOffset-1) {
            within = false;
            return errColor(str);
        } else if (within) {
            return errColor(str);
        } else {
            return str;
        }
    }

    function decorateError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            return errColor(str);
        } else {
            return str;
        }
    }
}

// istanbul ignore next TODO
function formatBufferUncolored(err, options) {
    options = options || {};

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var markStart = options.markStart || '>';
    var markEnd = options.markEnd || '<';
    var accum = 0;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        opts.groupSeparator = '';
        if (hasEnd) {
            opts.decorateHexen = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
        }
    }
    return hex(err.buffer, opts);

    // TODO: suspected broken across lines, should either test and complete or
    // use some sort of alternate notation such as interstitial lines
    function decorateRangedError(totalOffset, screenOffset, hexen) {
        var s;
        if (totalOffset === err.offset) {
            accum = 1;
            s = markStart + hexen;
            if (totalOffset === err.endOffset-1) {
                s += markEnd;
                accum = 0;
            } else {
                s = ' ' + s;
            }
            return s;
        } else if (totalOffset === err.endOffset-1) {
            s = hexen + markEnd;
            while (accum-- > 0) s += ' ';
            accum = 0;
            return s;
        } else if (accum) {
            accum += 2;
            return hexen;
        } else {
            return ' ' + hexen + ' ';
        }
    }

    function decorateError(totalOffset, screenOffset, hexen) {
        if (totalOffset === err.offset) {
            return markStart + hexen + markEnd;
        } else {
            return ' ' + hexen + ' ';
        }
    }
}

module.exports.fromBuffer = fromBuffer;
module.exports.byteLength = byteLength;
module.exports.toBuffer = toBuffer;
module.exports.intoBuffer = intoBuffer;
module.exports.formatError = formatError;

module.exports.fromBufferTuple = fromBufferTuple;
module.exports.byteLengthTuple = byteLengthTuple;
module.exports.toBufferTuple = toBufferTuple;
module.exports.intoBufferTuple = intoBufferTuple;

module.exports.fromBufferResult = fromBufferResult;
module.exports.byteLengthResult = byteLengthResult;
module.exports.toBufferResult = toBufferResult;
module.exports.intoBufferResult = intoBufferResult;
<commit_msg>interface: fix indentation oversight<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var color = require('ansi-color').set;
var hex = require('hexer');
var TypedError = require('error/typed');
var util = require('util');
var Result = require('./result');

var ShortReadError = TypedError({
    type: 'short-read',
    message: 'short read, {remaining} byte left over after consuming {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var ShortWriteError = TypedError({
    type: 'short-write',
    message: 'short write, {remaining} byte left over after writing {offset}',
    remaining: null,
    buffer: null,
    offset: null
});

var emptyBuffer = Buffer(0);

function fromBuffer(struct, buffer, offset) {
    return fromBufferResult(struct, buffer, offset).toValue();
}

function byteLength(struct, value) {
    return byteLengthResult(struct, value).toValue();
}

function toBuffer(struct, value) {
    return toBufferResult(struct, value).toValue();
}

function intoBuffer(struct, buffer, value) {
    return intoBufferResult(struct, buffer, value).toValue();
}

// The "Tuple" methods are deprecated

/* istanbul ignore next */
function fromBufferTuple(struct, buffer, offset) {
    return fromBufferResult(struct, buffer, offset).toTuple();
}

/* istanbul ignore next */
function byteLengthTuple(struct, value) {
    return byteLengthResult(struct, value).toTuple();
}

/* istanbul ignore next */
function toBufferTuple(struct, value) {
    return toBufferResult(struct, value).toTuple();
}

/* istanbul ignore next */
function intoBufferTuple(struct, buffer, value) {
    return intoBufferResult(struct, buffer, value).toTuple();
}

function fromBufferResult(struct, buffer, offset) {
    offset = offset || 0;
    var res = struct.readFrom(buffer, offset);
    offset = res.offset;
    var err = res.err;
    if (!err && offset !== buffer.length) {
        err = ShortReadError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        });
    }
    if (err) {
        if (err.offset === undefined) err.offset = offset;
        if (err.buffer === undefined) err.buffer = buffer;
    }
    return new Result(err, res.value);
}

function byteLengthResult(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return new Result(lenRes.err, 0);
    else return new Result(null, lenRes.length);
}

function toBufferResult(struct, value) {
    var lenRes = struct.byteLength(value);
    if (lenRes.err) return new Result(lenRes.err, emptyBuffer);
    var length = lenRes.length;
    var buffer = new Buffer(length);
    // buffer.fill(0); TODO option
    return intoBufferResult(struct, buffer, value);
}

function intoBufferResult(struct, buffer, value) {
    var writeRes = struct.writeInto(value, buffer, 0);
    if (writeRes.err) {
        // istanbul ignore else
        if (!Buffer.isBuffer(writeRes.err.buffer)) writeRes.err.buffer = buffer;
        if (typeof writeRes.err.offset !== 'number') writeRes.err.offset = writeRes.offset;
        return new Result(writeRes.err, buffer);
    }
    var offset = writeRes.offset;
    if (offset !== buffer.length) {
        return new Result(ShortWriteError({
            remaining: buffer.length - offset,
            buffer: buffer,
            offset: offset
        }), buffer);
    }
    return new Result(null, buffer);
}

// istanbul ignore next TODO
function formatError(err, options) {
    options = options || {};
    var name = err.name || err.constructor.name;
    var str = util.format('%s: %s\n', name, err.message);
    if (Buffer.isBuffer(err.buffer)) {
        if (options.color) {
            str += formatBufferColored(err, options);
        } else {
            str += formatBufferUncolored(err, options);
        }
        str += '\n';
    }
    return str;
}

// istanbul ignore next TODO
function formatBufferColored(err, options) {
    options = options || {};
    var markColor = options.markColor || 'red+bold';
    var errColor = typeof markColor === 'function' ? markColor : function(str) {
        return color(str, markColor);
    };

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var within = false;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        if (hasEnd) {
            opts.decorateHexen = decorateRangedError;
            opts.decorateHuman = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
            opts.decorateHuman = decorateError;
        }
    }
    return hex(err.buffer, opts);

    function decorateRangedError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            within = totalOffset !== err.endOffset-1;
            return errColor(str);
        } else if (totalOffset === err.endOffset-1) {
            within = false;
            return errColor(str);
        } else if (within) {
            return errColor(str);
        } else {
            return str;
        }
    }

    function decorateError(totalOffset, screenOffset, str) {
        if (totalOffset === err.offset) {
            return errColor(str);
        } else {
            return str;
        }
    }
}

// istanbul ignore next TODO
function formatBufferUncolored(err, options) {
    options = options || {};

    var hasOffset = !(err.offset === undefined || err.offset === null);
    var hasEnd = !(err.endOffset === undefined || err.endOffset === null);
    var markStart = options.markStart || '>';
    var markEnd = options.markEnd || '<';
    var accum = 0;

    var opts = options.hexerOptions ? Object.create(options.hexerOptions) : {};
    if (hasOffset) {
        opts.groupSeparator = '';
        if (hasEnd) {
            opts.decorateHexen = decorateRangedError;
        } else {
            opts.decorateHexen = decorateError;
        }
    }
    return hex(err.buffer, opts);

    // TODO: suspected broken across lines, should either test and complete or
    // use some sort of alternate notation such as interstitial lines
    function decorateRangedError(totalOffset, screenOffset, hexen) {
        var s;
        if (totalOffset === err.offset) {
            accum = 1;
            s = markStart + hexen;
            if (totalOffset === err.endOffset-1) {
                s += markEnd;
                accum = 0;
            } else {
                s = ' ' + s;
            }
            return s;
        } else if (totalOffset === err.endOffset-1) {
            s = hexen + markEnd;
            while (accum-- > 0) s += ' ';
            accum = 0;
            return s;
        } else if (accum) {
            accum += 2;
            return hexen;
        } else {
            return ' ' + hexen + ' ';
        }
    }

    function decorateError(totalOffset, screenOffset, hexen) {
        if (totalOffset === err.offset) {
            return markStart + hexen + markEnd;
        } else {
            return ' ' + hexen + ' ';
        }
    }
}

module.exports.fromBuffer = fromBuffer;
module.exports.byteLength = byteLength;
module.exports.toBuffer = toBuffer;
module.exports.intoBuffer = intoBuffer;
module.exports.formatError = formatError;

module.exports.fromBufferTuple = fromBufferTuple;
module.exports.byteLengthTuple = byteLengthTuple;
module.exports.toBufferTuple = toBufferTuple;
module.exports.intoBufferTuple = intoBufferTuple;

module.exports.fromBufferResult = fromBufferResult;
module.exports.byteLengthResult = byteLengthResult;
module.exports.toBufferResult = toBufferResult;
module.exports.intoBufferResult = intoBufferResult;
<|endoftext|>


<commit_before>require(
    [
        'polygonjs/lib',
        'polygonjs/surfaces/Canvas',
        'polygonjs/entities/OrthographicCamera',
        'polygonjs/entities/PerspectiveCamera',
        'polygonjs/Scene',
        'polygonjs/Renderer',
        'polygonjs/Mesh',
        'polygonjs/geom/Matrix3',
        'polygonjs/meshes/Icosahedron',
        'polygonjs/meshes/Cube',
        'polygonjs/meshes/Sphere',
        'polygonjs/format/object-file-format',
        'polygonjs/Entity',
        'polygonjs/Engine',
        'polygonjs/entities/Model',
        'polygonjs/geom/Vector3',
        'polygonjs/Profiler'
    ],
    function (
        lib,
        Surface,
        OrthographicCamera,
        PerspectiveCamera,
        Scene,
        Renderer,
        Mesh,
        Matrix3,
        Icosahedron,
        Cube,
        Sphere,
        objectFileFormat,
        Entity,
        Engine,
        Model,
        Vector3,
        Profiler
    ) {

        var profiler = new Profiler();

        var cube = Model.createFromMesh(Cube.create());
        // var sphere = Model.createFromMesh(Sphere.create({
        //     levelOfDetail: 1
        // }));
        // sphere.position = Vector3.create(10, 0, 0);

        cube.tags = ['cube'];
        var surface = Surface.create({});
        var scene = Scene.create({});
        var camera = PerspectiveCamera.create({});

        var root = Entity.create();
        root.addChild(cube);
        // root.addChild(sphere);
        root.addChild(camera);
        scene.root = root;
        scene.revalidate();

        var renderer = Renderer.create({
            surface: surface,
            scene: scene
        });

        var eye = Vector3.create(5, 5, 5);
        var target = Vector3.create(0, 0, 0);

        var angle = 0.00;

        var engine = Engine.create({
            onTick: function (delta) {
                scene.update(delta);

                angle += delta / 1000;
                if (angle > 360) angle -= 360;

                profiler.measure();
                profiler.toConsole();

                cube.rotation.setRotationY(angle);

                camera.position = eye;
                camera.lookAt(target);

                renderer.draw(delta);
            }
        });
        engine.start();

        window.setTimeout(function () {
            engine.stop();
        }, 3000);
    }
);<commit_msg>Update the demo. Quite a mess!<commit_after>require(
    [
        'polygonjs/lib',
        'polygonjs/surfaces/Canvas',
        'polygonjs/surfaces/WebGL',
        'polygonjs/entities/OrthographicCamera',
        'polygonjs/entities/PerspectiveCamera',
        'polygonjs/Scene',
        'polygonjs/Renderer',
        'polygonjs/Mesh',
        'polygonjs/geom/Matrix3',
        'polygonjs/meshes/Icosahedron',
        'polygonjs/meshes/Cube',
        'polygonjs/meshes/Sphere',
        'polygonjs/format/object-file-format',
        'polygonjs/Entity',
        'polygonjs/Engine',
        'polygonjs/entities/Model',
        'polygonjs/geom/Vector3',
        'polygonjs/Profiler'
    ],
    function (
        lib,
        Surface,
        WebGLSurface,
        OrthographicCamera,
        PerspectiveCamera,
        Scene,
        Renderer,
        Mesh,
        Matrix3,
        Icosahedron,
        Cube,
        Sphere,
        objectFileFormat,
        Entity,
        Engine,
        Model,
        Vector3,
        Profiler
    ) {
        // var model = Model.createFromMesh(Cube.create());
        var model = Model.createFromMesh(Sphere.create({
            levelOfDetail: 3,
            spikiness: 0.1
        }));

        model.tags = ['sphere'];
        model.scale = Vector3.create(2, 2, 2);
        var surface = Surface.create({});
        var scene = Scene.create({});
        var camera = PerspectiveCamera.create({});

        var root = Entity.create();
        root.addChild(model);
        // root.addChild(sphere);
        root.addChild(camera);
        scene.root = root;
        scene.revalidate();

        // Test style
        var colourIndex = 0;
        scene.polygons.forEach(function (polygon) {
            var colours = [
                'aliceblue',
                'antiquewhite',
                'aqua',
                'aquamarine',
                'azure',
                'beige',
                'bisque',
                'black',
                'blanchedalmond',
                'blue',
                'blueviolet',
                'brown',
                'burlywood',
                'cadetblue',
                'chartreuse',
                'chocolate',
                'coral',
                'cornflowerblue',
                'cornsilk',
                'crimson',
                'cyan',
                'darkblue',
                'darkcyan',
                'darkgoldenrod',
                'darkgray',
                'darkgreen',
                'darkkhaki',
                'darkmagenta',
                'darkolivegreen',
                'darkorange',
                'darkorchid',
                'darkred',
                'darksalmon',
                'darkseagreen',
                'darkslateblue',
                'darkslategray',
                'darkturquoise',
                'darkviolet',
                'deeppink',
                'deepskyblue',
                'dimgray',
                'dodgerblue',
                'firebrick',
                'floralwhite',
                'forestgreen',
                'fuchsia',
                'gainsboro',
                'ghostwhite',
                'gold',
                'goldenrod',
                'gray',
                'green',
                'greenyellow',
                'honeydew',
                'hotpink',
                'indianred',
                'indigo',
                'ivory',
                'khaki',
                'lavender',
                'lavenderblush',
                'lawngreen',
                'lemonchiffon',
                'lightblue',
                'lightcoral',
                'lightcyan',
                'lightgoldenrodyellow',
                'lightgray',            // IE6 breaks on this color
                'lightgreen',
                'lightpink',
                'lightsalmon',
                'lightseagreen',
                'lightskyblue',
                'lightslategray',
                'lightsteelblue',
                'lightyellow',
                'lime',
                'limegreen',
                'linen',
                'magenta',
                'maroon',
                'mediumaquamarine',
                'mediumblue',
                'mediumorchid',
                'mediumpurple',
                'mediumseagreen',
                'mediumslateblue',
                'mediumspringgreen',
                'mediumturquoise',
                'mediumvioletred',
                'midnightblue',
                'mintcream',
                'mistyrose',
                'moccasin',
                'navajowhite',
                'navy',
                'oldlace',
                'olive',
                'olivedrab',
                'orange',
                'orangered',
                'orchid',
                'palegoldenrod',
                'palegreen',
                'paleturquoise',
                'palevioletred',
                'papayawhip',
                'peachpuff',
                'peru',
                'pink',
                'plum',
                'powderblue',
                'purple',
                'red',
                'rosybrown',
                'royalblue',
                'saddlebrown',
                'salmon',
                'sandybrown',
                'seagreen',
                'seashell',
                'sienna',
                'silver',
                'skyblue',
                'slateblue',
                'slategray',
                'snow',
                'springgreen',
                'steelblue',
                'tan',
                'teal',
                'thistle',
                'tomato',
                'turquoise',
                'violet',
                'wheat',
                'white',
                'whitesmoke',
                'yellow',
                'yellowgreen'
            ];
            colourIndex = (++colourIndex) % colours.length;
            polygon.style = colours[colourIndex]; //Math.floor(Math.random() * colours.length)];
        });

        var renderer = Renderer.create({
            surface: surface,
            scene: scene
        });

        var eye = Vector3.create(5, 5, 5);
        var target = Vector3.create(0, 0, 0);

        var angle = 0.00;

        var profiler = Profiler.create({scene: scene});

        profiler.measure();
        profiler.toConsole();

        var engine = Engine.create({
            onTick: function (delta) {
                scene.update(delta);

                angle += delta / 1000;
                if (angle > 360) angle -= 360;

                // profiler.measure();
                // profiler.toConsole();

                model.rotation.setRotationY(angle);

                camera.position = eye;
                camera.lookAt(target);

                renderer.draw(delta);
            }
        });
        engine.start();

        window.setTimeout(function () {
            engine.stop();
        }, 10000);
    }
);<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import createStyles from '../styles/createStyles';

/**
 * A short description of the object values.
 * Can be used to render tree node in ObjectInspector
 * or render objects in TableInspector.
 */
const ObjectValue = ({ object, styles }, { theme }) => {
  const themeStyles = createStyles('ObjectValue', theme);

  const mkStyle = key => ({ ...themeStyles[key], ...styles });

  switch (typeof object) {
    case 'number':
      return (

          {String(object)}

      );
    case 'string':
      return (

          "{object}"

      );
    case 'boolean':
      return (

          {String(object)}

      );
    case 'undefined':
      return undefined;
    case 'object':
      if (object === null) {
        return null;
      }
      if (object instanceof Date) {
        return (

            {object.toString()}

        );
      }
      if (object instanceof RegExp) {
        return (

            {object.toString()}

        );
      }
      if (Array.isArray(object)) {
        return {`Array[${object.length}]`};
      }

      if (!object.constructor) {
        return Object;
      }

      return (

          {object.constructor.name}

      );
    case 'function':
      return (

          function

             {object.name}()

      );
    case 'symbol':
      return (

          {object.toString()}

      );
    default:
      return ;
  }
};

ObjectValue.propTypes = {
  /** the object to describe */
  object: PropTypes.any,
};

ObjectValue.contextTypes = {
  theme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
};

export default ObjectValue;
<commit_msg>Show buffers as `Buffer[${buffer.length}]`<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import createStyles from '../styles/createStyles';

/**
 * A short description of the object values.
 * Can be used to render tree node in ObjectInspector
 * or render objects in TableInspector.
 */
const ObjectValue = ({ object, styles }, { theme }) => {
  const themeStyles = createStyles('ObjectValue', theme);

  const mkStyle = key => ({ ...themeStyles[key], ...styles });

  switch (typeof object) {
    case 'number':
      return (

          {String(object)}

      );
    case 'string':
      return (

          "{object}"

      );
    case 'boolean':
      return (

          {String(object)}

      );
    case 'undefined':
      return undefined;
    case 'object':
      if (object === null) {
        return null;
      }
      if (object instanceof Date) {
        return (

            {object.toString()}

        );
      }
      if (object instanceof RegExp) {
        return (

            {object.toString()}

        );
      }
      if (Array.isArray(object)) {
        return {`Array[${object.length}]`};
      }
      if (!object.constructor) {
        return Object;
      }
      if (object.constructor.isBuffer && object.constructor.isBuffer(object)) {
        return {`Buffer[${object.length}]`};
      }

      return (

          {object.constructor.name}

      );
    case 'function':
      return (

          function

             {object.name}()

      );
    case 'symbol':
      return (

          {object.toString()}

      );
    default:
      return ;
  }
};

ObjectValue.propTypes = {
  /** the object to describe */
  object: PropTypes.any,
};

ObjectValue.contextTypes = {
  theme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
};

export default ObjectValue;
<|endoftext|>


<commit_before>var pull   = require('pull-stream')
var toPull = require('stream-to-pull-stream')

var qs = require('querystring')
var URL = require('url')
      //host blobs
module.exports = function (blobs, url) {
  return function (req, res, next) {

    next = next || function (err) {
      res.writeHead(404, {'Content-Type': 'application/json'})
      res.end(JSON.stringify({error: true, status: 404}))
    }

    if(req.url === url+'/add')
      pull(
        toPull(req),
        blobs.add(function (err, hash) {
          res.end(hash)
        })
      )
    else if(req.url.indexOf(url+'/get/') == 0) {
      var u = URL.parse('http://makeurlparseright.com'+req.url)
      var hash = u.pathname.substring((url+'/get/').length)
      var q = qs.parse(u.query)
      //Response.AddHeader("content-disposition", "inline; filename=File.doc")
      if(q.filename)
        res.setHeader('Content-Discosition', 'inline; filename='+q.filename)

      pull(
        blobs.get(hash),
        //since this is an http stream, handle error the http way.
        pull.through(null, function (err) {
          if(err) next(err)
        }),
        toPull(res))
    }
    else next()
  }
}

<commit_msg>check if blob actually exists in store, and set correct status code<commit_after>var pull   = require('pull-stream')
var toPull = require('stream-to-pull-stream')

var qs = require('querystring')
var URL = require('url')
      //host blobs
module.exports = function (blobs, url) {
  return function (req, res, next) {

    next = next || function (err) {
      res.writeHead(404, {'Content-Type': 'application/json'})
      res.end(JSON.stringify({error: true, status: 404}))
    }

    if(req.url === url+'/add')
      pull(
        toPull(req),
        blobs.add(function (err, hash) {
          res.end(hash)
        })
      )
    else if(req.url.indexOf(url+'/get/') == 0) {
      var u = URL.parse('http://makeurlparseright.com'+req.url)
      var hash = u.pathname.substring((url+'/get/').length)
      var q = qs.parse(u.query)

      if(q.filename)
        res.setHeader('Content-Discosition', 'inline; filename='+q.filename)

      blobs.has(hash, function (err, has) {
        if(err) return next(err)

        res.writeHead(200)
        pull(
          blobs.get(hash),
          //since this is an http stream, handle error the http way.
          pull.through(null, function (err) {
            if(err) throw err //DEBUG
            if(err) next(err)
          }),
          toPull(res)
        )
      })
    }
    else next()
  }
}

<|endoftext|>


<commit_before>'use strict';

var ClearCMS = Window.ClearCMS || {};

ClearCMS.e = function() {
  return {
    FORM_FIELDS_MODIFIED: "form fields modified"
  }
}();

// Manages the content type metadata / form switching for edit pages
ClearCMS.ContentTypes = function() {
  var $typeSelect,
      currentType,
      allType = 'ClearCMS::Content';

  function displayMetaFields(thing) {
    var type = (typeof thing == 'string') ? thing : $(this).val();

    // loop though fieldset.general li and inspect the data('types') array
    // TBD: this may not be the final method of identifying these fields/areas
    $('.general li[data-types]').each(function(i) {

      if ((-1 != $.inArray(type, $(this).data('types'))) || (-1 != $.inArray(allType, $(this).data('types')))) {
        $(this).show();
      } else {
        $(this).hide();
      }

    });
  };

  return {
    initialize: function() {
      $typeSelect = $('#content__type');

      // STEP 0: Decide we're on a content edit page
      if ($typeSelect.length) {
        // STEP 1: Grab Types field and current value
        currentType = $typeSelect.val();

        // STEP 2: Set initial
        displayMetaFields(currentType);
        // STEP 3: Watch Chage of type field
        $typeSelect.on('change',displayMetaFields)

        }
      // TBD: what do we do with content in dropped fields - are those hidden and not submitted? zerod out?
    }
  }
}(); // ClearCMS.Types

ClearCMS.Form = function() {
  var warnBeforeUnload = false;

  function warn() {
    if (warnBeforeUnload) {
      return 'There are unsaved changes.';
    }
  };

  function activateMarkItUp() {
    // quick hack to make sure we don't double initialize
    $('textarea.markitup').not('.markItUpEditor').markItUp(markItUpSettings);
  };

  return {
    setUnsavedWarning: function() {
      ClearCMS.Interface.setStatus('unsaved','true');
      warnBeforeUnload = true;
    },

    initialize: function() {
      // watch window events for unload / unsaved changes
      $('input,select,textarea').on('change keyup',function(e) {
        if (!$(this).is('.hidefromstatus')) {
          ClearCMS.Interface.setStatus('unsaved','true');
          warnBeforeUnload = true;
        }
      });
      // watch for (SUCCESSFUL?) submit to clear warning
      $('form').on('submit',function(e) {
        ClearCMS.Interface.setStatus('unsaved','false');
        warnBeforeUnload = false;
      });

      window.onbeforeunload = warn;

      // watch for ctrl-s to trigger save
      if ($('form#edit_content').length) {
        $('body').on('keydown',function(e) {
          if (e.ctrlKey || e.metaKey) {
            if (String.fromCharCode(e.which).toLowerCase() == 's') {
              e.preventDefault();
              if (confirm('Save your changes?')) {
                $('form#edit_content').submit();
              }
            }
          }
        });
      }

      // TODO: abstract this all
      // initialize sortable widgets - linked content
      $('#linkedContentSortable').sortable({
        revert: true,
        update: function() {
          // loop thorugh items and update order field
          $('#linkedContentSortable .draggable').each(function(i) {
            $(this).find('[id$=_order]').val(i);
          });
        }
      });
      $( ".draggable","#linkedContentSortable").draggable({
        connectToSortable: "#linkedContentSortable",
        helper: "original",
        axis: "x",
        revert: "invalid",
        stop: function() {
          //alert('done');
        }
      });

      // initialize sortable widgets - media items
      $( "#asset-sortable" ).sortable({
        revert: true,
        update: function() {

          // loop thorugh items and update order field
          $('#asset-sortable .draggable').each(function(i) {
            $(this).find('[id$=_order]').val(i); //content[content_blocks_attributes][0][content_assets_attributes][0][order])
          });

        }
      });
      $( ".draggable","#asset-sortable").draggable({
        connectToSortable: "#asset-sortable",
        helper: "original",
        axis: "x",
        revert: "invalid",
        stop: function() {
          //alert('done');
        }
      });

      // "Disabling text selection is bad. Don't use this." http://api.jqueryui.com/disableSelection/
      $( ".draggabke ul" ).disableSelection();

      // activate markitup widgets
      activateMarkItUp();
      //$(document).on(ClearCMS.e.FORM_FIELDS_MODIFIED,activateMarkItUp);
      $(document).on('nested:fieldAdded',activateMarkItUp);

      // activate field counters
      $('textarea').textcount();

      // activate special datetimepickers
      // hack to make date field format so datepicker sees it
      $('.datetime_picker').each(function(i){
        var datetime = moment($(this).val()),
            datetime_reformatted = "";

        if (datetime) {
          datetime_reformatted = datetime.format('YYYY-MM-DDTHH:mm:00');
        }
        $(this).val(datetime_reformatted);
      })

      $('.datetime_picker').datetimepicker({
        format: 'yyyy-mm-ddThh:ii',
        autoclose: true,
        showMeridian: true,
        todayBtn: true,
        pickerPosition: "bottom-left"
      });

      // hack to convert date to utc before submission
      $('form').on('submit',function(e) {
        $('.datetime_picker').each(function(i){
          var datetime = moment($(this).val()),
            datetime_unformatted = "";

          if (datetime) {
            datetime_unformatted = datetime.format('YYYY-MM-DDTHH:mm:00Z');
          }
          $(this).val(datetime_unformatted);
        });

      });
      //$('.datetime_picker').

      // activate "save as next state" button (TODO: refactor)
      $(".form-action.next-state").bind('click', function(e) {
        //alert($(this).attr('data-next-state'));
        // console.log('save as next state');
        $('#content_state').val($(this).attr('data-next-state'));
        $('form.content').submit();
      });
    }
  }
}(); // ClearCMS.Form

ClearCMS.Interface = function() {
  function drawStatus(uploads,unsaved) {
    var uploads = uploads ? uploads : "0",
        unsaved = unsaved ? "yes" : "no";

    if ($('#template-status-bar').length) {
      $('body').append(tmpl('template-status-bar',{"uploads": uploads,"unsaved": unsaved}));
    }
  };

  function updateStatus(which, val) {
    $('#status-bar .val-'+which).html(val);
  };

  return {
    setStatus: function(which, val) {
      updateStatus(which, val);
    },

    initialize: function() {
      // activate tooltips
      $('.category_listings').tooltip({trigger: 'hover'});

      // initialize status bar
      drawStatus();

      // initialize type ahead find dialogs
      // $('#linkedLookup').typeahead({
      //   source: function(query, process) {
      //     return $.ajax({
      //       //url: $(this)[0].$element[0].data.link,
      //       url: '/clear_cms/sites/51e59961b50f1e24db000002/contents.json',
      //       type: 'get',
      //       data: {
      //         'filters[type]': 'Product',
      //         query: query
      //       },
      //       dataType: 'json',
      //       success: function(json) {
      //         return typeof json.options == 'undefined' ? false : process(json.options);
      //       }
      //     });
      //   }
      // });

      // re-route lookup field form submission to adding content item
      // $('#linkedLookup').on('keyup',function(e) {
      //   if (e.keyCode == 13) {
      //     e.stopPropagation();
      //     e.preventDefault();
      //   }
      // });

      // $('#linkedLookup')
    }
  }
}(); // ClearCMS.UI

ClearCMS.Linking = function() {
  var _dataCache,
      _lastOrderIndex = 50;

  // adds a new record to the collection of linked items
  // $block = .lookupWrap block
  // ui == jQuery UI autocomplete output
  function _addTemplate($block,ui) {
    var which,
        data,
        img_src = null;

    // circuitous route to image thumb
    if (ui.item.all.content_blocks[0].content_assets) {
      img_src = ui.item.all.content_blocks[0].content_assets[0].mounted_file.thumb.url;
    }

    //val = $block.find('input').val();
    which = $block.data('lookup-success-tmpl');
    data = {
      //'fiters[type]': $block.data('lookup-filter-type'),
      content_id: ui.item.all._id,
      title: ui.item.all.title,
      media_src: img_src,
      order: _lastOrderIndex++
    }
    $block.prev('.lookupSuccessTarget').append(tmpl(which,data));
    // TODO: why does this get delated? or overwritten by autocomplete plugin race conditions
    $block.find('.lookupField').val('');
  };

  // updates the filter type based on selection
  // NOTE: currently dumb, changes ALL linked content blocks on a page
  function _updateFitlerType(val) {
    $('.lookupWrap').data('lookup-filter-type',val);
  };

  return {
    initialize: function() {
      var $blocks,
          $field,
          $button;

      // look up linkage blocks and attach needed event handlers
      $blocks = $('.lookupWrap');

      // prevent some edge cases / form submits
      $('input',$blocks).addClass('hidefromstatus').on('keyup',function(e) {
        if (e.keyCode == 13) {
          //_addTemplate($(this).parents('.lookupWrap'));
          e.preventDefault();
          e.stopPropagation();
        }
      });

      // manage button events
      $('button',$blocks).on('click',function(e) {
        e.preventDefault();
        if ($(this).siblings('input').val()) {
          //_addTemplate($(this).parents('.lookupWrap'));
        }
      });

      // watch type selector for changes
      $('.linkedFiltersTypeMonitor').on('change',function(e) {
        _updateFitlerType(linkedFiltersType[$(this).val()]);
      });

      // initialize jquery autocomplete widget and outputs
      $('input',$blocks).each(function(i) {
        var $input = $(this),
            $block = $input.parents('.lookupWrap');

        $input.autocomplete({
          source: function(request, response) {
            $.ajax({
              url: $block.data('lookup-url'),
              data: {
                'filter[types]': $block.data('lookup-filter-type'),
                q: request.term
              }
            }).success(function(data){
              var results = $.map(data, function(content) {
                return {
                  label: content.title,
                  value: content._id,
                  all: content
                }
              });
              _dataCache = data;
              response(results);
            });
          },
          minLength: 4,
          select: function( event, ui ) {
            event.preventDefault();
            // console.log(ui);
            // TBD: auto _addTemplate on selection?
            _addTemplate($(this).parents('.lookupWrap'),ui);
          }
        });
      });
    }
  }
}(); // ClearCMS.Linking

ClearCMS.Image = function() {

  function internal_sample() {

  };

  return {
    initialize: function() {
      //sample
    },

    insert: function(imageInsertButton) {
      //alert(this);
      //console.log($(image).parent('.content-form-asset'));
      //var modal=$(imageInsertButton).parent('#modal-image-insert');
/*

      var src=modal.find('#image-url').html();
      var alt=src;

*/
      var modal=$('#modal-image-insert');
      var src=$.trim($(modal).find('#image-url').html());

      var alignment=$(modal).find('input[name=image_alignment]:checked').val();
      var image_size=$(modal).find('input[name=image_size]:checked').val();

      var path=$(modal).find('input[name=path]').val();
      var file=$(modal).find('input[name=file]').val();

      var srchost = $('<a>').prop('href', src).prop('hostname');
      /* var alt=src; */
      var alt='';

      //var title=
      //var caption=
      //var description=

      $.markItUp({ replaceWith:'<img src="http://'+srchost+'/'+path+'/'+image_size+'_'+file+'" alt="'+alt+'" class="'+alignment+'" />' });
      modal.modal('hide');
      return false;
    },
    insertWizard: function(imageInsertButton) {
      var assetDiv=$(imageInsertButton).parent('.content-form-asset');
      var src=$(assetDiv).find('img').attr('src');
      var path=$(assetDiv).find('input.path').val();
      var file=$(assetDiv).find('input.file').val();
      $('#modal-image-insert > .modal-body').html(tmpl('template-insert-wizard',{"url": src,"path": path, "file": file}));
      $('#modal-image-insert').modal();
      return false;
    }
  }

}(); // ClearCMS.Image

ClearCMS.ImageQueue = function() {
  var assetList={},
      _lastOrderIndex = 50;

  return {
    addAsset: function(asset,upload_data){
      assetList[asset._id]={asset: asset, upload_data: upload_data};
      window.setTimeout(function(){ ClearCMS.ImageQueue.checkProcessing(asset._id); },2000);
      // TDDO: update this:
      ClearCMS.Form.setUnsavedWarning();
      //window.warnBeforeUnload=true;
      return assetList;
    },
    getAssets: function() {
      return assetList;
    },
    checkProcessing: function(asset_id) {
      $.ajax('/clear_cms/assets/'+asset_id,{
        success: function(data) {
          if(data.processed_at) {
            if(assetList[data._id]['upload_data'].context) {
              assetList[data._id]['upload_data'].context.remove();
            }

            $.extend(data,{order: _lastOrderIndex++});
            $('#asset-sortable').append(tmpl('template-asset-form',data));
            delete assetList[data._id];
            window.uploadsCount--;
            ClearCMS.Interface.setStatus('uploads',window.uploadsCount);
          } else {
            window.setTimeout(function(){ ClearCMS.ImageQueue.checkProcessing(data._id); },2000);
          }
        }
      });
    }

  }

}(); // ClearCMS.ImageQueue

// On Load, Initilize sites
(function($){
  ClearCMS.Form.initialize();
  ClearCMS.Interface.initialize();
  ClearCMS.ContentTypes.initialize();
  ClearCMS.Linking.initialize()

})(jQuery);

<commit_msg>[#56928030] warn about unsaved changes if linked content is added<commit_after>'use strict';

var ClearCMS = Window.ClearCMS || {};

ClearCMS.e = function() {
  return {
    FORM_FIELDS_MODIFIED: "form fields modified"
  }
}();

// Manages the content type metadata / form switching for edit pages
ClearCMS.ContentTypes = function() {
  var $typeSelect,
      currentType,
      allType = 'ClearCMS::Content';

  function displayMetaFields(thing) {
    var type = (typeof thing == 'string') ? thing : $(this).val();

    // loop though fieldset.general li and inspect the data('types') array
    // TBD: this may not be the final method of identifying these fields/areas
    $('.general li[data-types]').each(function(i) {

      if ((-1 != $.inArray(type, $(this).data('types'))) || (-1 != $.inArray(allType, $(this).data('types')))) {
        $(this).show();
      } else {
        $(this).hide();
      }

    });
  };

  return {
    initialize: function() {
      $typeSelect = $('#content__type');

      // STEP 0: Decide we're on a content edit page
      if ($typeSelect.length) {
        // STEP 1: Grab Types field and current value
        currentType = $typeSelect.val();

        // STEP 2: Set initial
        displayMetaFields(currentType);
        // STEP 3: Watch Chage of type field
        $typeSelect.on('change',displayMetaFields)

        }
      // TBD: what do we do with content in dropped fields - are those hidden and not submitted? zerod out?
    }
  }
}(); // ClearCMS.Types

ClearCMS.Form = function() {
  var warnBeforeUnload = false;

  function warn() {
    if (warnBeforeUnload) {
      return 'There are unsaved changes.';
    }
  };

  function activateMarkItUp() {
    // quick hack to make sure we don't double initialize
    $('textarea.markitup').not('.markItUpEditor').markItUp(markItUpSettings);
  };

  return {
    setUnsavedWarning: function() {
      ClearCMS.Interface.setStatus('unsaved','true');
      warnBeforeUnload = true;
    },

    initialize: function() {
      // watch window events for unload / unsaved changes
      $('input,select,textarea').on('change keyup',function(e) {
        if (!$(this).is('.hidefromstatus')) {
          ClearCMS.Interface.setStatus('unsaved','true');
          warnBeforeUnload = true;
        }
      });
      // watch for (SUCCESSFUL?) submit to clear warning
      $('form').on('submit',function(e) {
        ClearCMS.Interface.setStatus('unsaved','false');
        warnBeforeUnload = false;
      });

      window.onbeforeunload = warn;

      // watch for ctrl-s to trigger save
      if ($('form#edit_content').length) {
        $('body').on('keydown',function(e) {
          if (e.ctrlKey || e.metaKey) {
            if (String.fromCharCode(e.which).toLowerCase() == 's') {
              e.preventDefault();
              if (confirm('Save your changes?')) {
                $('form#edit_content').submit();
              }
            }
          }
        });
      }

      // TODO: abstract this all
      // initialize sortable widgets - linked content
      $('#linkedContentSortable').sortable({
        revert: true,
        update: function() {
          // loop thorugh items and update order field
          $('#linkedContentSortable .draggable').each(function(i) {
            $(this).find('[id$=_order]').val(i);
          });
        }
      });
      $( ".draggable","#linkedContentSortable").draggable({
        connectToSortable: "#linkedContentSortable",
        helper: "original",
        axis: "x",
        revert: "invalid",
        stop: function() {
          //alert('done');
        }
      });

      // initialize sortable widgets - media items
      $( "#asset-sortable" ).sortable({
        revert: true,
        update: function() {

          // loop thorugh items and update order field
          $('#asset-sortable .draggable').each(function(i) {
            $(this).find('[id$=_order]').val(i); //content[content_blocks_attributes][0][content_assets_attributes][0][order])
          });

        }
      });
      $( ".draggable","#asset-sortable").draggable({
        connectToSortable: "#asset-sortable",
        helper: "original",
        axis: "x",
        revert: "invalid",
        stop: function() {
          //alert('done');
        }
      });

      // "Disabling text selection is bad. Don't use this." http://api.jqueryui.com/disableSelection/
      $( ".draggabke ul" ).disableSelection();

      // activate markitup widgets
      activateMarkItUp();
      //$(document).on(ClearCMS.e.FORM_FIELDS_MODIFIED,activateMarkItUp);
      $(document).on('nested:fieldAdded',activateMarkItUp);

      // activate field counters
      $('textarea').textcount();

      // activate special datetimepickers
      // hack to make date field format so datepicker sees it
      $('.datetime_picker').each(function(i){
        var datetime = moment($(this).val()),
            datetime_reformatted = "";

        if (datetime) {
          datetime_reformatted = datetime.format('YYYY-MM-DDTHH:mm:00');
        }
        $(this).val(datetime_reformatted);
      })

      $('.datetime_picker').datetimepicker({
        format: 'yyyy-mm-ddThh:ii',
        autoclose: true,
        showMeridian: true,
        todayBtn: true,
        pickerPosition: "bottom-left"
      });

      // hack to convert date to utc before submission
      $('form').on('submit',function(e) {
        $('.datetime_picker').each(function(i){
          var datetime = moment($(this).val()),
            datetime_unformatted = "";

          if (datetime) {
            datetime_unformatted = datetime.format('YYYY-MM-DDTHH:mm:00Z');
          }
          $(this).val(datetime_unformatted);
        });

      });
      //$('.datetime_picker').

      // activate "save as next state" button (TODO: refactor)
      $(".form-action.next-state").bind('click', function(e) {
        //alert($(this).attr('data-next-state'));
        // console.log('save as next state');
        $('#content_state').val($(this).attr('data-next-state'));
        $('form.content').submit();
      });
    }
  }
}(); // ClearCMS.Form

ClearCMS.Interface = function() {
  function drawStatus(uploads,unsaved) {
    var uploads = uploads ? uploads : "0",
        unsaved = unsaved ? "yes" : "no";

    if ($('#template-status-bar').length) {
      $('body').append(tmpl('template-status-bar',{"uploads": uploads,"unsaved": unsaved}));
    }
  };

  function updateStatus(which, val) {
    $('#status-bar .val-'+which).html(val);
  };

  return {
    setStatus: function(which, val) {
      updateStatus(which, val);
    },

    initialize: function() {
      // activate tooltips
      $('.category_listings').tooltip({trigger: 'hover'});

      // initialize status bar
      drawStatus();

      // initialize type ahead find dialogs
      // $('#linkedLookup').typeahead({
      //   source: function(query, process) {
      //     return $.ajax({
      //       //url: $(this)[0].$element[0].data.link,
      //       url: '/clear_cms/sites/51e59961b50f1e24db000002/contents.json',
      //       type: 'get',
      //       data: {
      //         'filters[type]': 'Product',
      //         query: query
      //       },
      //       dataType: 'json',
      //       success: function(json) {
      //         return typeof json.options == 'undefined' ? false : process(json.options);
      //       }
      //     });
      //   }
      // });

      // re-route lookup field form submission to adding content item
      // $('#linkedLookup').on('keyup',function(e) {
      //   if (e.keyCode == 13) {
      //     e.stopPropagation();
      //     e.preventDefault();
      //   }
      // });

      // $('#linkedLookup')
    }
  }
}(); // ClearCMS.UI

ClearCMS.Linking = function() {
  var _dataCache,
      _lastOrderIndex = 50;

  // adds a new record to the collection of linked items
  // $block = .lookupWrap block
  // ui == jQuery UI autocomplete output
  function _addTemplate($block,ui) {
    var which,
        data,
        img_src = null;

    // circuitous route to image thumb
    if (ui.item.all.content_blocks[0].content_assets) {
      img_src = ui.item.all.content_blocks[0].content_assets[0].mounted_file.thumb.url;
    }

    //val = $block.find('input').val();
    which = $block.data('lookup-success-tmpl');
    data = {
      //'fiters[type]': $block.data('lookup-filter-type'),
      content_id: ui.item.all._id,
      title: ui.item.all.title,
      media_src: img_src,
      order: _lastOrderIndex++
    }
    $block.prev('.lookupSuccessTarget').append(tmpl(which,data));

    $block.find('.lookupField').val('');

    ClearCMS.Form.setUnsavedWarning();
  };

  // updates the filter type based on selection
  // NOTE: currently dumb, changes ALL linked content blocks on a page
  function _updateFitlerType(val) {
    $('.lookupWrap').data('lookup-filter-type',val);
  };

  return {
    initialize: function() {
      var $blocks,
          $field,
          $button;

      // look up linkage blocks and attach needed event handlers
      $blocks = $('.lookupWrap');

      // prevent some edge cases / form submits
      $('input',$blocks).addClass('hidefromstatus').on('keyup',function(e) {
        if (e.keyCode == 13) {
          //_addTemplate($(this).parents('.lookupWrap'));
          e.preventDefault();
          e.stopPropagation();
        }
      });

      // manage button events
      $('button',$blocks).on('click',function(e) {
        e.preventDefault();
        if ($(this).siblings('input').val()) {
          //_addTemplate($(this).parents('.lookupWrap'));
        }
      });

      // watch type selector for changes
      $('.linkedFiltersTypeMonitor').on('change',function(e) {
        _updateFitlerType(linkedFiltersType[$(this).val()]);
      });

      // initialize jquery autocomplete widget and outputs
      $('input',$blocks).each(function(i) {
        var $input = $(this),
            $block = $input.parents('.lookupWrap');

        $input.autocomplete({
          source: function(request, response) {
            $.ajax({
              url: $block.data('lookup-url'),
              data: {
                'filter[types]': $block.data('lookup-filter-type'),
                q: request.term
              }
            }).success(function(data){
              var results = $.map(data, function(content) {
                return {
                  label: content.title,
                  value: content._id,
                  all: content
                }
              });
              _dataCache = data;
              response(results);
            });
          },
          minLength: 4,
          select: function( event, ui ) {
            event.preventDefault();
            // console.log(ui);
            // TBD: auto _addTemplate on selection?
            _addTemplate($(this).parents('.lookupWrap'),ui);
          }
        });
      });
    }
  }
}(); // ClearCMS.Linking

ClearCMS.Image = function() {

  function internal_sample() {

  };

  return {
    initialize: function() {
      //sample
    },

    insert: function(imageInsertButton) {
      //alert(this);
      //console.log($(image).parent('.content-form-asset'));
      //var modal=$(imageInsertButton).parent('#modal-image-insert');
/*

      var src=modal.find('#image-url').html();
      var alt=src;

*/
      var modal=$('#modal-image-insert');
      var src=$.trim($(modal).find('#image-url').html());

      var alignment=$(modal).find('input[name=image_alignment]:checked').val();
      var image_size=$(modal).find('input[name=image_size]:checked').val();

      var path=$(modal).find('input[name=path]').val();
      var file=$(modal).find('input[name=file]').val();

      var srchost = $('<a>').prop('href', src).prop('hostname');
      /* var alt=src; */
      var alt='';

      //var title=
      //var caption=
      //var description=

      $.markItUp({ replaceWith:'<img src="http://'+srchost+'/'+path+'/'+image_size+'_'+file+'" alt="'+alt+'" class="'+alignment+'" />' });
      modal.modal('hide');
      return false;
    },
    insertWizard: function(imageInsertButton) {
      var assetDiv=$(imageInsertButton).parent('.content-form-asset');
      var src=$(assetDiv).find('img').attr('src');
      var path=$(assetDiv).find('input.path').val();
      var file=$(assetDiv).find('input.file').val();
      $('#modal-image-insert > .modal-body').html(tmpl('template-insert-wizard',{"url": src,"path": path, "file": file}));
      $('#modal-image-insert').modal();
      return false;
    }
  }

}(); // ClearCMS.Image

ClearCMS.ImageQueue = function() {
  var assetList={},
      _lastOrderIndex = 50;

  return {
    addAsset: function(asset,upload_data){
      assetList[asset._id]={asset: asset, upload_data: upload_data};
      window.setTimeout(function(){ ClearCMS.ImageQueue.checkProcessing(asset._id); },2000);
      // TDDO: update this:
      ClearCMS.Form.setUnsavedWarning();
      //window.warnBeforeUnload=true;
      return assetList;
    },
    getAssets: function() {
      return assetList;
    },
    checkProcessing: function(asset_id) {
      $.ajax('/clear_cms/assets/'+asset_id,{
        success: function(data) {
          if(data.processed_at) {
            if(assetList[data._id]['upload_data'].context) {
              assetList[data._id]['upload_data'].context.remove();
            }

            $.extend(data,{order: _lastOrderIndex++});
            $('#asset-sortable').append(tmpl('template-asset-form',data));
            delete assetList[data._id];
            window.uploadsCount--;
            ClearCMS.Interface.setStatus('uploads',window.uploadsCount);
          } else {
            window.setTimeout(function(){ ClearCMS.ImageQueue.checkProcessing(data._id); },2000);
          }
        }
      });
    }

  }

}(); // ClearCMS.ImageQueue

// On Load, Initilize sites
(function($){
  ClearCMS.Form.initialize();
  ClearCMS.Interface.initialize();
  ClearCMS.ContentTypes.initialize();
  ClearCMS.Linking.initialize()

})(jQuery);

<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

// Handle basic reqest at this path
router.get('/', function(req, res) {
  res.render('initialize', {db_path: '<i>none</i>'});
});

module.exports = router;
<commit_msg>no uses the config file for references to the database path<commit_after>var express = require('express');
var router = express.Router();
var config = require('../config.js');

// Handle basic reqest at this path
router.get('/', function(req, res) {
  res.render('initialize', {db_path: config.path});
});

module.exports = router;
<|endoftext|>


<commit_before>(function (define) {
    define([
        'underscore',
        'backbone',
        'js/discovery/models/course_discovery',
        'js/discovery/collections/filters'
    ], function (_, Backbone, CourseDiscovery, Filters) {
        'use strict';

        return Backbone.Model.extend({

            page: 0,
            pageSize: 20,
            searchTerm: '',
            terms: {},
            jqhxr: null,

            initialize: function () {
                this.discovery = new CourseDiscovery();
                this.listenTo(this.discovery, 'sync', this.onSync, this);
                this.listenTo(this.discovery, 'error', this.onError, this);
            },
            performSearch: function (searchTerm, otherTerms) {
                // main 태그에 data-param 이 있으면 데이터에 값을 추가하고 선택된 형태르 변경후 data-param을 삭제
                let k, v;
                $("#main input[name='default_term']").each(function () {
                    k = $(this).data('key');
                    v = $(this).data('value');
                    var obj = new Object();
                    obj[k] = v;

                    _.extend(otherTerms, obj);

                    $(this).remove();
                });

                // 검색박스 표시
                if (k && v){
                    let e = this;
                    setTimeout(function(){

                        switch (v){
                            case 'fourth_industry_y':
                                k = 'fourth_industry_yn';
                                v = 'Y';
                                break;
                            case 'job_edu_y':
                                k = 'job_edu_yn'
                                v = 'Y';
                                break;
                            case 'linguistics_y':
                                k = 'linguistics';
                                v = 'Y';
                                break;
                        }

                        console.log("k:" + k  + " v:" + v + " size:" +  $("button[data-facet='"+ k +"'][data-value='"+ v +"']").size());
                        if ($("button[data-facet='"+ k +"'][data-value='"+ v +"']").size() > 0){
                            e.trigger(
                                'selectedOption',
                                k,
                                v,
                                gettext(v)
                            );
                        } else {
                            console.debug('선택된 검색어가 존재 하지 않습니다.' + k + " : " + v);
                        }
                    }, 200);
                }

                this.reset();
                this.searchTerm = searchTerm;
                if (otherTerms) {
                    this.terms = otherTerms;
                }
                this.sendQuery(this.buildQuery(0));
            },

            refineSearch: function (terms) {
                this.reset();
                this.terms = terms;
                this.sendQuery(this.buildQuery(0));
            },

            loadNextPage: function () {
                if (this.hasNextPage()) {
                    this.sendQuery(this.buildQuery(this.page + 1));
                }
            },

            // private

            hasNextPage: function () {
                var total = this.discovery.get('totalCount');
                return total - ((this.page + 1) * this.pageSize) > 0;
            },

            sendQuery: function (data) {
                this.jqhxr && this.jqhxr.abort();
                this.jqhxr = this.discovery.fetch({
                    type: 'POST',
                    data: data
                });

                return this.jqhxr;
            },

            getTermParameter: function (sParam) {
                var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                    sURLVariables = sPageURL.split('&'),
                    sParameterName,
                    i;

                for (i = 0; i < sURLVariables.length; i++) {
                    sParameterName = sURLVariables[i].split('=');

                    if (sParameterName[0] === sParam) {
                        return sParameterName[1] === undefined ? true : sParameterName[1];
                    }
                }
            },
            buildQuery: function (pageIndex) {
                var data = {
                    search_string: this.searchTerm,
                    page_size: this.pageSize,
                    page_index: pageIndex
                };
                console.log('buildQuery --- s');
                console.log(this.terms);
                console.log('buildQuery --- e');
                _.extend(data, this.terms);

                /* 대분류 검사 */
                var get_term = this.getTermParameter('term');
                if (get_term) {
                    _.extend(data, {"classfy": get_term});
                }
                /* 중분류 검사 */
                var get_mterm = this.getTermParameter('mterm')
                if (get_mterm) {
                    _.extend(data, {"middle_classfy": get_mterm});
                }

                /* 언어학 부분 검사 */
                var linguistics = this.getTermParameter('linguistics');
                if (linguistics) {
                    _.extend(data, {"linguistics": linguistics});

                }

                /* 강의기간 분류류 */
                var course_period = this.getTermParameter('course_period');
                if (course_period) {
                    _.extend(data, {"course_period": course_period});
                }

                /**
                 * 강의 종류 검색
                 * range=e : 종료된 강의
                 * range=i : 진행중 강의
                 * range=t : 진행예정 강의
                 */
                var range = this.getTermParameter('range');

                if (range) {
                    _.extend(data, {'range': range});
                }

                return data;
            },

            reset: function () {
                this.discovery.reset();
                this.page = 0;
                this.errorMessage = '';
            },

            onError: function (collection, response, options) {
                if (response.statusText !== 'abort') {
                    this.errorMessage = response.responseJSON.error;
                    this.trigger('error');
                }
            },

            onSync: function (collection, response, options) {

                var total = this.discovery.get('totalCount');
                var originalSearchTerm = this.searchTerm;
                if (options.data.page_index === 0) {
                    if (total === 0) {
                        // list all courses
                        this.cachedDiscovery().done(function (cached) {
                            this.discovery.courseCards.reset(cached.courseCards.toJSON());
                            this.discovery.facetOptions.reset(cached.facetOptions.toJSON());
                            this.discovery.set('latestCount', cached.get('latestCount'));
                            this.trigger('search', originalSearchTerm, total);
                        });
                        this.searchTerm = '';
                        this.terms = {};
                    } else {
                        _.each(this.terms, function (term, facet) {
                            if (facet !== 'search_query') {
                                var option = this.discovery.facetOptions.findWhere({
                                    facet: facet,
                                    term: term
                                });
                                if (option) {
                                    option.set('selected', true);
                                }
                            }
                        }, this);
                        this.trigger('search', this.searchTerm, total);
                    }
                } else {
                    this.page = options.data.page_index;
                    this.trigger('next');
                }
            },

            // lazy load
            cachedDiscovery: function () {

                var deferred = $.Deferred();
                var self = this;

                if (this.cached) {
                    deferred.resolveWith(this, [this.cached]);
                } else {
                    this.cached = new CourseDiscovery();
                    this.cached.fetch({
                        type: 'POST',
                        data: {
                            search_string: '',
                            page_size: this.pageSize,
                            page_index: 0
                        },
                        success: function (model, response, options) {
                            deferred.resolveWith(self, [model]);
                        }
                    });
                }
                return deferred.promise();
            }

        });
    });
}(define || RequireJS.define));
<commit_msg>링크 선택 기능 수정<commit_after>(function (define) {
    define([
        'underscore',
        'backbone',
        'js/discovery/models/course_discovery',
        'js/discovery/collections/filters'
    ], function (_, Backbone, CourseDiscovery, Filters) {
        'use strict';

        return Backbone.Model.extend({

            page: 0,
            pageSize: 20,
            searchTerm: '',
            terms: {},
            jqhxr: null,

            initialize: function () {
                this.discovery = new CourseDiscovery();
                this.listenTo(this.discovery, 'sync', this.onSync, this);
                this.listenTo(this.discovery, 'error', this.onError, this);
            },
            performSearch: function (searchTerm, otherTerms) {
                // main 태그에 data-param 이 있으면 데이터에 값을 추가하고 선택된 형태르 변경후 data-param을 삭제
                let k, v, t;
                $("#main input[name='default_term']").each(function () {
                    k = $(this).data('key');
                    v = $(this).data('value');
                    var obj = new Object();
                    obj[k] = v;

                    _.extend(otherTerms, obj);

                    $(this).remove();
                });

                // 검색박스 표시
                if (k && v){
                    let e = this;
                    setTimeout(function(){

                        switch (v){
                            case 'fourth_industry_y':
                                k = 'fourth_industry_yn';
                                v = 'Y';
                                t = 'fourth_industry_y';
                                break;
                            case 'job_edu_y':
                                k = 'job_edu_yn'
                                v = 'Y';
                                t = 'job_edu_y';
                                break;
                            case 'linguistics_y':
                                k = 'linguistics';
                                v = 'Y';
                                t = 'linguistics_y';
                                break;
                        }

                        console.log("k:" + k  + " v:" + v + " size:" +  $("button[data-facet='"+ k +"'][data-value='"+ v +"']").size());
                        if ($("button[data-facet='"+ k +"'][data-value='"+ v +"']").size() > 0){
                            e.trigger(
                                'selectedOption',
                                k,
                                v,
                                gettext(t)
                            );
                        } else {
                            console.debug('선택된 검색어가 존재 하지 않습니다.' + k + " : " + v);
                        }
                    }, 200);
                }

                this.reset();
                this.searchTerm = searchTerm;
                if (otherTerms) {
                    this.terms = otherTerms;
                }
                this.sendQuery(this.buildQuery(0));
            },

            refineSearch: function (terms) {
                this.reset();
                this.terms = terms;
                this.sendQuery(this.buildQuery(0));
            },

            loadNextPage: function () {
                if (this.hasNextPage()) {
                    this.sendQuery(this.buildQuery(this.page + 1));
                }
            },

            // private

            hasNextPage: function () {
                var total = this.discovery.get('totalCount');
                return total - ((this.page + 1) * this.pageSize) > 0;
            },

            sendQuery: function (data) {
                this.jqhxr && this.jqhxr.abort();
                this.jqhxr = this.discovery.fetch({
                    type: 'POST',
                    data: data
                });

                return this.jqhxr;
            },

            getTermParameter: function (sParam) {
                var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                    sURLVariables = sPageURL.split('&'),
                    sParameterName,
                    i;

                for (i = 0; i < sURLVariables.length; i++) {
                    sParameterName = sURLVariables[i].split('=');

                    if (sParameterName[0] === sParam) {
                        return sParameterName[1] === undefined ? true : sParameterName[1];
                    }
                }
            },
            buildQuery: function (pageIndex) {
                var data = {
                    search_string: this.searchTerm,
                    page_size: this.pageSize,
                    page_index: pageIndex
                };
                console.log('buildQuery --- s');
                console.log(this.terms);
                console.log('buildQuery --- e');
                _.extend(data, this.terms);

                /* 대분류 검사 */
                var get_term = this.getTermParameter('term');
                if (get_term) {
                    _.extend(data, {"classfy": get_term});
                }
                /* 중분류 검사 */
                var get_mterm = this.getTermParameter('mterm')
                if (get_mterm) {
                    _.extend(data, {"middle_classfy": get_mterm});
                }

                /* 언어학 부분 검사 */
                var linguistics = this.getTermParameter('linguistics');
                if (linguistics) {
                    _.extend(data, {"linguistics": linguistics});

                }

                /* 강의기간 분류류 */
                var course_period = this.getTermParameter('course_period');
                if (course_period) {
                    _.extend(data, {"course_period": course_period});
                }

                /**
                 * 강의 종류 검색
                 * range=e : 종료된 강의
                 * range=i : 진행중 강의
                 * range=t : 진행예정 강의
                 */
                var range = this.getTermParameter('range');

                if (range) {
                    _.extend(data, {'range': range});
                }

                return data;
            },

            reset: function () {
                this.discovery.reset();
                this.page = 0;
                this.errorMessage = '';
            },

            onError: function (collection, response, options) {
                if (response.statusText !== 'abort') {
                    this.errorMessage = response.responseJSON.error;
                    this.trigger('error');
                }
            },

            onSync: function (collection, response, options) {

                var total = this.discovery.get('totalCount');
                var originalSearchTerm = this.searchTerm;
                if (options.data.page_index === 0) {
                    if (total === 0) {
                        // list all courses
                        this.cachedDiscovery().done(function (cached) {
                            this.discovery.courseCards.reset(cached.courseCards.toJSON());
                            this.discovery.facetOptions.reset(cached.facetOptions.toJSON());
                            this.discovery.set('latestCount', cached.get('latestCount'));
                            this.trigger('search', originalSearchTerm, total);
                        });
                        this.searchTerm = '';
                        this.terms = {};
                    } else {
                        _.each(this.terms, function (term, facet) {
                            if (facet !== 'search_query') {
                                var option = this.discovery.facetOptions.findWhere({
                                    facet: facet,
                                    term: term
                                });
                                if (option) {
                                    option.set('selected', true);
                                }
                            }
                        }, this);
                        this.trigger('search', this.searchTerm, total);
                    }
                } else {
                    this.page = options.data.page_index;
                    this.trigger('next');
                }
            },

            // lazy load
            cachedDiscovery: function () {

                var deferred = $.Deferred();
                var self = this;

                if (this.cached) {
                    deferred.resolveWith(this, [this.cached]);
                } else {
                    this.cached = new CourseDiscovery();
                    this.cached.fetch({
                        type: 'POST',
                        data: {
                            search_string: '',
                            page_size: this.pageSize,
                            page_index: 0
                        },
                        success: function (model, response, options) {
                            deferred.resolveWith(self, [model]);
                        }
                    });
                }
                return deferred.promise();
            }

        });
    });
}(define || RequireJS.define));
<|endoftext|>