<commit_before>(function (a) {

var pageScriptsDone = false;
var wikiRootRgx = new RegExp((adminifier.wikiRoot + '/').replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));

// this is for if pageScriptsDone event is added
// and the page scripts are already done
Element.Events.pageScriptsLoaded = {
	onAdd: function (fn) {
		if (pageScriptsDone)
            fn.call(this);
	}
};

Element.implement('onEnter', function (func) {
    this.addEvent('keyup', function (e) {
        if (e.key != 'enter')
            return;
        func.call(this, e);
    });
});

function SSV (str) {
    if (typeof str != 'string' || !str.length)
        return [];
    return str.split(' ');
}

// EXPORTS

// update page title
a.updatePageTitle = function (title, titleTagOnly) {
    if (!titleTagOnly)
        $('page-title').getElement('span').innerText = title;
    document.title = title + ' | ' + a.wikiName;
};

// update page icon
a.updateIcon = function (icon) {
	$('page-title').getElement('i').set('class', 'fa fa-' + icon);
};

// safe page/category name
a.safeName = function (name) {
    return name.replace(/[^\w\.\-]/g, '_');
};

// load a script
a.loadScript = function (src) {
	a.loadScripts([src]);
};

var scriptsToLoad = [], firedPageScriptsLoaded;
function scriptLoaded () {
	if (typeof jQuery != 'undefined')
		jQuery.noConflict();

	// there are still more to load
	if (scriptsToLoad.length) {
		loadNextScript();
		return;
	}

	// this was the last one
	$('content').setStyle('user-select', 'all');
	a.updateIcon(a.currentData['data-icon']);
	pageScriptsDone = true;
	if (firedPageScriptsLoaded) return;
	document.fireEvent('pageScriptsLoaded');
	firedPageScriptsLoaded = true;
}

function loadNextScript () {
	var script = scriptsToLoad.shift();
	if (!script)
		return;
	document.head.appendChild(script);
}

// load several scripts
a.loadScripts = function (srcs) {
	srcs.each(function (src) {
		if (!src.length) return;

		if (src == 'ace')
			src = adminifier.staticRoot + '/ext/ace/src-min/ace.js';
		else if (src == 'pikaday')
			src = adminifier.staticRoot + '/ext/pikaday/pikaday.js';
		else if (src == 'jquery')
			src = '//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js';
		else if (src == 'diff2html')
			src = adminifier.staticRoot + '/ext/diff2html/dist/diff2html.js';
		else if (src == 'colorpicker')
			src = adminifier.staticRoot + '/ext/colorpicker/DynamicColorPicker.js';
		else if (src == 'prettify')
			src = 'https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js';
		else
			src = adminifier.staticRoot + '/script/' + src + '.js';

        var script = new Element('script', {
			src:   src,
			class: 'dynamic'
		});
		script.addEvent('load', scriptLoaded);
		scriptsToLoad.push(script);
	});

	// call once in case there are no scripts
	scriptLoaded();
}

// adopts an element to an invisible container in the DOM so that dimension
// properties become available before displaying it
a.fakeAdopt = function (child) {
    var parent = $('fake-parent');
    if (!parent) {
        parent = new Element('div', {
            id: 'fake-parent',
            styles: { display: 'none' }
        });
        document.body.appendChild(parent);
    }
    parent.appendChild(child);
};

document.addEvent('domready', 	loadURL);
document.addEvent('domready',	searchHandler);
document.addEvent('domready',   addFrameClickHandler)
document.addEvent('keyup',		handleEscapeKey);

// PAGE LOADING

// clicking a frame link
function addFrameClickHandler () {
    $$('a.frame-click').each(function (a) {
        a.addEvent('click', function (e) {
            e.preventDefault();
            var page = a.href.replace(/^.*\/\/[^\/]+/, '').replace(wikiRootRgx, '');
            console.log("href", a.href, "root+page", adminifier.wikiRoot + '/' + page);
            history.pushState(page, '', adminifier.wikiRoot + '/' + page);
            loadURL();
        });
    })
}

// load a page
function frameLoad (page) {

	// same page
    if (a.currentPage == page)
        return;

	// unload old page
    document.fireEvent('pageUnloaded');
    a.currentPage = page;
    console.log("Loading " + page);

	a.updateIcon('circle-o-notch fa-spin');
    var request = new Request({
        url: 'frame/' + page,
        onSuccess: function (html) {

            // the page may start with JSON metadata...
            if (!html.indexOf('<!--JSON')) {
                var json = JSON.parse(html.split('\n', 3)[1]);
                a.currentJSONMetadata = json;
            }

            // set the content
            $('content').innerHTML = html;

            // find HTML metadata
            var meta = $('content').getElement('meta');
            if (meta) {
                var attrs = meta.attributes;
				[].forEach.call(meta.attributes, function(attr) {
				    if (/^data-/.test(attr.name))
				        attrs[attr.name] = attr.value;
				});

                // // Tools for all pages
                // 'data-redirect',    // javascript frame redirect
                // 'data-wredirect',   // window redirect
                // 'data-nav',         // navigation item identifier to highlight
                // 'data-title',       // page title for top bar
                // 'data-icon',        // page icon name for top bar
                // 'data-scripts',     // SSV script names w/o extensions
                // 'data-styles',      // SSV css names w/o extensions
                // 'data-flags',       // SSV page flags
				// 'data-search', 		// name of function to call on search
				// 'data-buttons', 	// buttons to display in top bar
				//
                // // Used by specific pages
				//
                // 'data-sort'         // pages

                handlePageData(attrs);
            }
        },
        onFail: function (html) {
        }
    });
    request.get();
}

// load frame based on the current URL
function loadURL() {
    var loc = window.location.pathname
    frameLoad(loc.replace(wikiRootRgx, ''));
}

// page options
var flagOptions = {
    'no-margin': {
        init: function () {
            $('content').addClass('no-margin');
        },
        destroy: function () {
            $('content').removeClass('no-margin');
        }
    },
    'compact-sidebar': {
        init: function () {
			document.getElement('span.wiki-title').tween('min-width', '75px');
            $('navigation-sidebar').tween('width', '50px');
            $('content').tween('margin-left', '50px');
            $$('#navigation-sidebar li a').each(function (a) {
                a.getElement('span').fade('out');
                a.addEvents({
                    mouseenter: handleCompactSidebarMouseenter,
                    mouseleave: handleCompactSidebarMouseleave
                });
            });
        },
        destroy: function () {
			document.getElement('span.wiki-title').tween('min-width', '140px');
            $('navigation-sidebar').tween('width', '170px');
            $('content').tween('margin-left', '170px');
            $$('#navigation-sidebar li a').each(function (a) {
                a.getElement('span').fade('in');
                a.removeEvents({
                    mouseenter: handleCompactSidebarMouseenter,
                    mouseleave: handleCompactSidebarMouseleave
                });
            });
            $$('div.navigation-popover').each(function (p) {
                p.parentElement.eliminate('popover');
                p.parentElement.removeChild(p);
            });
        }
    },
	search: {
		init: function () {
			$('top-search').set('value', '');
			$('top-search').setStyle('display', 'inline-block');
			searchUpdate();
		},
		destroy: function () {
			$('top-search').setStyle('display', 'none');
		}
	},
	buttons: {
		init: function () {
			if (!a.currentData || !a.currentData['data-buttons'])
				return;
			SSV(a.currentData['data-buttons']).each(function (buttonID) {

				// find opts
				var buttonStuff = a.currentData['data-button-' + buttonID];
				if (!buttonStuff) {
					console.warn('Button ' + buttonID + ' is not configured');
					return;
				}

				// parse psuedo-JSON
				buttonStuff = JSON.decode(buttonStuff.replace(/'/g, '"'));
				if (!buttonStuff) {
					console.warn('Failed to parse JSON for button ' + buttonID);
					return;
				}

				var but = new Element('span', {
					id:		'top-button-' + buttonID,
					class: 	'top-title top-button injected'
				});

				// hide
				if (buttonStuff.hide)
					but.setStyle('display', 'none');

				// title
				var anchor = new Element('a', {
					href: buttonStuff.href || '#'
				});
				anchor.set('text', buttonStuff.title);
				but.appendChild(anchor);

				// icon
				if (buttonStuff.icon) {
					anchor.set('text', ' ' + anchor.get('text'));
					var i = new Element('i', {
						'class': 'fa fa-' + buttonStuff.icon
					});
					i.inject(anchor, 'top');
				}

				// click event if func is provided
				if (buttonStuff.func) anchor.addEvent('click', function (e) {
					e.preventDefault();
					var func = window[buttonStuff.func];
					if (!func) {
						console.warn(
							'Button ' + buttonID + ' function ' +
							buttonStuff.func + ' does not exist'
						);
						return;
					}
					func();
				});

				but.inject($$('.top-button').getLast(), 'after');
			});
		},
		destroy: function () {
			$$('.top-button.injected').each(function (but) {
				but.destroy();
			});
		}
	}
};

// handle page data on request completion
function handlePageData (data) {
    pageScriptsDone = false;

    console.log(data);
    a.currentData = data;
    $('content').setStyle('user-select', 'none');

    // window redirect
    var target = data['data-wredirect'];
    if (target) {
        console.log('Redirecting to ' + target);
        window.location = target;
        return;
    }

    // page redirect
    target = data['data-redirect'];
    if (target) {
        var newHash = '#!/' + target;
        console.log('Redirecting to ' + newHash);
        window.location.hash = newHash;
        return;
    }

    // page title and icon
    a.updatePageTitle(data['data-title']);
    window.scrollTo(0, 0);
    // ^ not sure if scrolling necessary when setting display: none

    // highlight navigation item
    var li = $$('li[data-nav="' + data['data-nav'] + '"]')[0];
    if (li) {
        $$('li.active').each(function (li) { li.removeClass('active') });
        li.addClass('active');
    }

    // inject scripts
    $$('script.dynamic').each(function (script) { script.destroy(); });
	firedPageScriptsLoaded = false;
    a.loadScripts(SSV(data['data-scripts']));

    // inject styles
    $$('link.dynamic').each(function (link) { link.destroy(); });
    SSV(data['data-styles']).each(function (style) {
        if (!style.length) return;

		var href;
		if (style == 'colorpicker')
			href = 'ext/colorpicker/colorpicker.css';
		else if (style == 'diff2html')
			href = 'ext/diff2html/dist/diff2html.css';
		else if (style == 'pikaday')
			href = 'ext/pikaday-custom.css';
		else
			href = 'style/' + style + '.css';

        var link = new Element('link', {
            href:   adminifier.staticRoot + '/' + href,
            class: 'dynamic',
            type:  'text/css',
            rel:   'stylesheet'
        });
		// link.addEvent('load', scriptLoaded);
        document.head.appendChild(link);
    });

    // handle page flags
    if (a.currentFlags)
        a.currentFlags.each(function (flag) {
            if (flag.destroy)
                flag.destroy();
        });
    a.currentFlags = [];
    SSV(data['data-flags']).each(function (flagName) {
        var flag = flagOptions[flagName];
        if (!flag) return;
        a.currentFlags.push(flag);
        flag.init();
    });
}

// escape key pressed
function handleEscapeKey (e) {
    if (e.key != 'esc')
        return;
    var container = document.getElement('.modal-container');
    if (container)
        container.retrieve('modal').destroy();
}

// SEARCH

function searchHandler () {
	$('top-search').addEvent('input', searchUpdate);
}

function searchUpdate () {
	var text = $('top-search').get('value');
	if (!a.currentData || !a.currentData['data-search'])
		return;
	var searchFunc = window[a.currentData['data-search']];
	if (!searchFunc)
		return;
	searchFunc(text);
}

// COMPACT SIDEBAR

function handleCompactSidebarMouseenter (e) {
    var a = e.target;
    var p = a.retrieve('popover');
    if (!p) {
        p = new Element('div', { class: 'navigation-popover' });
        p.innerHTML = a.getElement('span').innerHTML;
        a.appendChild(p);
        p.set('morph', { duration: 150 });
        a.store('popover', p);
    }
    a.setStyle('overflow', 'visible');
    p.setStyle('background-color', '#444');
    p.morph({
        width: '90px',
        paddingLeft: '10px'
    });
}

function handleCompactSidebarMouseleave (e) {
    var a = e.target;
    var p = a.retrieve('popover');
    if (!p) return;
    p.setStyle('background-color', '#333');
    p.morph({
        width: '0px',
        paddingLeft: '0px'
    });
    setTimeout(function () {
        a.setStyle('overflow', 'hidden');
    }, 200);
}

})(adminifier);
<commit_msg>no more hashes<commit_after>(function (a) {

var pageScriptsDone = false;
var wikiRootRgx = new RegExp((adminifier.wikiRoot + '/').replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));

// this is for if pageScriptsDone event is added
// and the page scripts are already done
Element.Events.pageScriptsLoaded = {
	onAdd: function (fn) {
		if (pageScriptsDone)
            fn.call(this);
	}
};

Element.implement('onEnter', function (func) {
    this.addEvent('keyup', function (e) {
        if (e.key != 'enter')
            return;
        func.call(this, e);
    });
});

function SSV (str) {
    if (typeof str != 'string' || !str.length)
        return [];
    return str.split(' ');
}

// EXPORTS

// update page title
a.updatePageTitle = function (title, titleTagOnly) {
    if (!titleTagOnly)
        $('page-title').getElement('span').innerText = title;
    document.title = title + ' | ' + a.wikiName;
};

// update page icon
a.updateIcon = function (icon) {
	$('page-title').getElement('i').set('class', 'fa fa-' + icon);
};

// safe page/category name
a.safeName = function (name) {
    return name.replace(/[^\w\.\-]/g, '_');
};

// load a script
a.loadScript = function (src) {
	a.loadScripts([src]);
};

var scriptsToLoad = [], firedPageScriptsLoaded;
function scriptLoaded () {
	if (typeof jQuery != 'undefined')
		jQuery.noConflict();

	// there are still more to load
	if (scriptsToLoad.length) {
		loadNextScript();
		return;
	}

	// this was the last one
	$('content').setStyle('user-select', 'all');
	a.updateIcon(a.currentData['data-icon']);
	pageScriptsDone = true;
	if (firedPageScriptsLoaded) return;
	document.fireEvent('pageScriptsLoaded');
	firedPageScriptsLoaded = true;
}

function loadNextScript () {
	var script = scriptsToLoad.shift();
	if (!script)
		return;
	document.head.appendChild(script);
}

// load several scripts
a.loadScripts = function (srcs) {
	srcs.each(function (src) {
		if (!src.length) return;

		if (src == 'ace')
			src = adminifier.staticRoot + '/ext/ace/src-min/ace.js';
		else if (src == 'pikaday')
			src = adminifier.staticRoot + '/ext/pikaday/pikaday.js';
		else if (src == 'jquery')
			src = '//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js';
		else if (src == 'diff2html')
			src = adminifier.staticRoot + '/ext/diff2html/dist/diff2html.js';
		else if (src == 'colorpicker')
			src = adminifier.staticRoot + '/ext/colorpicker/DynamicColorPicker.js';
		else if (src == 'prettify')
			src = 'https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js';
		else
			src = adminifier.staticRoot + '/script/' + src + '.js';

        var script = new Element('script', {
			src:   src,
			class: 'dynamic'
		});
		script.addEvent('load', scriptLoaded);
		scriptsToLoad.push(script);
	});

	// call once in case there are no scripts
	scriptLoaded();
}

// adopts an element to an invisible container in the DOM so that dimension
// properties become available before displaying it
a.fakeAdopt = function (child) {
    var parent = $('fake-parent');
    if (!parent) {
        parent = new Element('div', {
            id: 'fake-parent',
            styles: { display: 'none' }
        });
        document.body.appendChild(parent);
    }
    parent.appendChild(child);
};

document.addEvent('domready', 	loadURL);
document.addEvent('domready',	searchHandler);
document.addEvent('domready',   addFrameClickHandler)
document.addEvent('keyup',		handleEscapeKey);

// PAGE LOADING

// clicking a frame link
function addFrameClickHandler () {
    $$('a.frame-click').each(function (a) {
        a.addEvent('click', function (e) {
            e.preventDefault();
            var page = a.href.replace(/^.*\/\/[^\/]+/, '').replace(wikiRootRgx, '');
            history.pushState(page, '', adminifier.wikiRoot + '/' + page);
            loadURL();
        });
    })
}

// load a page
function frameLoad (page) {

	// same page
    if (a.currentPage == page)
        return;

	// unload old page
    document.fireEvent('pageUnloaded');
    a.currentPage = page;
    console.log("Loading " + page);

	a.updateIcon('circle-o-notch fa-spin');
    var request = new Request({
        url: 'frame/' + page,
        onSuccess: function (html) {

            // the page may start with JSON metadata...
            if (!html.indexOf('<!--JSON')) {
                var json = JSON.parse(html.split('\n', 3)[1]);
                a.currentJSONMetadata = json;
            }

            // set the content
            $('content').innerHTML = html;

            // find HTML metadata
            var meta = $('content').getElement('meta');
            if (meta) {
                var attrs = meta.attributes;
				[].forEach.call(meta.attributes, function(attr) {
				    if (/^data-/.test(attr.name))
				        attrs[attr.name] = attr.value;
				});

                // // Tools for all pages
                // 'data-redirect',    // javascript frame redirect
                // 'data-wredirect',   // window redirect
                // 'data-nav',         // navigation item identifier to highlight
                // 'data-title',       // page title for top bar
                // 'data-icon',        // page icon name for top bar
                // 'data-scripts',     // SSV script names w/o extensions
                // 'data-styles',      // SSV css names w/o extensions
                // 'data-flags',       // SSV page flags
				// 'data-search', 		// name of function to call on search
				// 'data-buttons', 	// buttons to display in top bar
				//
                // // Used by specific pages
				//
                // 'data-sort'         // sort option, used by file lists

                handlePageData(attrs);
            }
        },
        onFail: function (html) {
        }
    });
    request.get();
}

// load frame based on the current URL
function loadURL() {
    var loc = window.location.pathname
    frameLoad(loc.replace(wikiRootRgx, ''));
}

// page options
var flagOptions = {
    'no-margin': {
        init: function () {
            $('content').addClass('no-margin');
        },
        destroy: function () {
            $('content').removeClass('no-margin');
        }
    },
    'compact-sidebar': {
        init: function () {
			document.getElement('span.wiki-title').tween('min-width', '75px');
            $('navigation-sidebar').tween('width', '50px');
            $('content').tween('margin-left', '50px');
            $$('#navigation-sidebar li a').each(function (a) {
                a.getElement('span').fade('out');
                a.addEvents({
                    mouseenter: handleCompactSidebarMouseenter,
                    mouseleave: handleCompactSidebarMouseleave
                });
            });
        },
        destroy: function () {
			document.getElement('span.wiki-title').tween('min-width', '140px');
            $('navigation-sidebar').tween('width', '170px');
            $('content').tween('margin-left', '170px');
            $$('#navigation-sidebar li a').each(function (a) {
                a.getElement('span').fade('in');
                a.removeEvents({
                    mouseenter: handleCompactSidebarMouseenter,
                    mouseleave: handleCompactSidebarMouseleave
                });
            });
            $$('div.navigation-popover').each(function (p) {
                p.parentElement.eliminate('popover');
                p.parentElement.removeChild(p);
            });
        }
    },
	search: {
		init: function () {
			$('top-search').set('value', '');
			$('top-search').setStyle('display', 'inline-block');
			searchUpdate();
		},
		destroy: function () {
			$('top-search').setStyle('display', 'none');
		}
	},
	buttons: {
		init: function () {
			if (!a.currentData || !a.currentData['data-buttons'])
				return;
			SSV(a.currentData['data-buttons']).each(function (buttonID) {

				// find opts
				var buttonStuff = a.currentData['data-button-' + buttonID];
				if (!buttonStuff) {
					console.warn('Button ' + buttonID + ' is not configured');
					return;
				}

				// parse psuedo-JSON
				buttonStuff = JSON.decode(buttonStuff.replace(/'/g, '"'));
				if (!buttonStuff) {
					console.warn('Failed to parse JSON for button ' + buttonID);
					return;
				}

				var but = new Element('span', {
					id:		'top-button-' + buttonID,
					class: 	'top-title top-button injected'
				});

				// hide
				if (buttonStuff.hide)
					but.setStyle('display', 'none');

				// title
				var anchor = new Element('a', {
					href: buttonStuff.href || '#'
				});
				anchor.set('text', buttonStuff.title);
				but.appendChild(anchor);

				// icon
				if (buttonStuff.icon) {
					anchor.set('text', ' ' + anchor.get('text'));
					var i = new Element('i', {
						'class': 'fa fa-' + buttonStuff.icon
					});
					i.inject(anchor, 'top');
				}

				// click event if func is provided
				if (buttonStuff.func) anchor.addEvent('click', function (e) {
					e.preventDefault();
					var func = window[buttonStuff.func];
					if (!func) {
						console.warn(
							'Button ' + buttonID + ' function ' +
							buttonStuff.func + ' does not exist'
						);
						return;
					}
					func();
				});

				but.inject($$('.top-button').getLast(), 'after');
			});
		},
		destroy: function () {
			$$('.top-button.injected').each(function (but) {
				but.destroy();
			});
		}
	}
};

// handle page data on request completion
function handlePageData (data) {
    pageScriptsDone = false;

    console.log(data);
    a.currentData = data;
    $('content').setStyle('user-select', 'none');

    // window redirect
    var target = data['data-wredirect'];
    if (target) {
        console.log('Redirecting to ' + target);
        window.location = target;
        return;
    }

    // page redirect
    target = data['data-redirect'];
    if (target) {
        console.log('Redirecting to ' + target);
        history.pushState(page, '', adminifier.wikiRoot + '/' + target);
        loadURL();
        return;
    }

    // page title and icon
    a.updatePageTitle(data['data-title']);
    window.scrollTo(0, 0);
    // ^ not sure if scrolling necessary when setting display: none

    // highlight navigation item
    var li = $$('li[data-nav="' + data['data-nav'] + '"]')[0];
    if (li) {
        $$('li.active').each(function (li) { li.removeClass('active') });
        li.addClass('active');
    }

    // inject scripts
    $$('script.dynamic').each(function (script) { script.destroy(); });
	firedPageScriptsLoaded = false;
    a.loadScripts(SSV(data['data-scripts']));

    // inject styles
    $$('link.dynamic').each(function (link) { link.destroy(); });
    SSV(data['data-styles']).each(function (style) {
        if (!style.length) return;

		var href;
		if (style == 'colorpicker')
			href = 'ext/colorpicker/colorpicker.css';
		else if (style == 'diff2html')
			href = 'ext/diff2html/dist/diff2html.css';
		else if (style == 'pikaday')
			href = 'ext/pikaday-custom.css';
		else
			href = 'style/' + style + '.css';

        var link = new Element('link', {
            href:   adminifier.staticRoot + '/' + href,
            class: 'dynamic',
            type:  'text/css',
            rel:   'stylesheet'
        });
		// link.addEvent('load', scriptLoaded);
        document.head.appendChild(link);
    });

    // handle page flags
    if (a.currentFlags)
        a.currentFlags.each(function (flag) {
            if (flag.destroy)
                flag.destroy();
        });
    a.currentFlags = [];
    SSV(data['data-flags']).each(function (flagName) {
        var flag = flagOptions[flagName];
        if (!flag) return;
        a.currentFlags.push(flag);
        flag.init();
    });
}

// escape key pressed
function handleEscapeKey (e) {
    if (e.key != 'esc')
        return;
    var container = document.getElement('.modal-container');
    if (container)
        container.retrieve('modal').destroy();
}

// SEARCH

function searchHandler () {
	$('top-search').addEvent('input', searchUpdate);
}

function searchUpdate () {
	var text = $('top-search').get('value');
	if (!a.currentData || !a.currentData['data-search'])
		return;
	var searchFunc = window[a.currentData['data-search']];
	if (!searchFunc)
		return;
	searchFunc(text);
}

// COMPACT SIDEBAR

function handleCompactSidebarMouseenter (e) {
    var a = e.target;
    var p = a.retrieve('popover');
    if (!p) {
        p = new Element('div', { class: 'navigation-popover' });
        p.innerHTML = a.getElement('span').innerHTML;
        a.appendChild(p);
        p.set('morph', { duration: 150 });
        a.store('popover', p);
    }
    a.setStyle('overflow', 'visible');
    p.setStyle('background-color', '#444');
    p.morph({
        width: '90px',
        paddingLeft: '10px'
    });
}

function handleCompactSidebarMouseleave (e) {
    var a = e.target;
    var p = a.retrieve('popover');
    if (!p) return;
    p.setStyle('background-color', '#333');
    p.morph({
        width: '0px',
        paddingLeft: '0px'
    });
    setTimeout(function () {
        a.setStyle('overflow', 'hidden');
    }, 200);
}

})(adminifier);
<|endoftext|>


<commit_before>define(['jquery',
    'underscore',
    'knockout',
    'views/forms/base',
    'views/forms/sections/validation',
    'views/forms/sections/branch-list',
    'bootstrap-datetimepicker',
    'summernote'],
    function ($, _, ko, BaseForm, ValidationTools, BranchList, datetimepicker, summernote) {

        var vt = new ValidationTools;

        function isValidDate(dateString){

            console.log("validating: "+dateString);
            justDate = dateString.split("T")[0]

            // Change to acceptable db format
            var replaceDate = justDate.replace(/\//g,"-");

            // Create output array
            var output = new Array(
                false,
                replaceDate
            );

            // Deal with empty dates (they're ok!)
            if(output[1] == ""){
                output[0] = true;
                console.log("blank date ok");
                return output;
            }

            // First check for the pattern
            if(!/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(replaceDate)){
                console.log("pattern fail");
                return output;
            }

            // Parse the date parts, rebuild replaceDate
            var parts = replaceDate.split("-");
            for (i=1; i==2; i++) {
                console.log(i);
                if (parts[i].length == i) {
                    parts[i] = "0"+parts[i];
                }
            }
            replaceDate = parts.join("-");

            // make parts into integers for processing
            var day = parseInt(parts[2], 10);
            var month = parseInt(parts[1], 10);
            var year = parseInt(parts[0], 10);

            // Check the ranges of month and year
            if(year > 3000 || month == 0 || month > 12){
                return output;
            }
            var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

            // Adjust for leap years
            if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
                monthLength[1] = 29;
            }

            // Check the range of the day
            output[0] = day > 0 && day <= monthLength[month - 1];
            output[1] = replaceDate;
            console.log(output);
            return output;
        };

        //insert validation functions here

        return BaseForm.extend({

            initialize: function() {

                $('.totalscore').change(function() {
                    var sum = 0;
                    $('.totalscore').each(function(){
                        sum += parseFloat(this.value);
                    });
                    var comp = document.getElementById("comp");
                    comp.value = sum;
                    $(comp).trigger('change');
                    //comp.innerHTML = sum;
                });

                BaseForm.prototype.initialize.apply(this);

                var date_picker = $('.datetimepicker').datetimepicker({pickTime: false});
                date_picker.on('dp.change', function(evt){
                    $(this).find('input').trigger('change');
                });

                this.addBranchList(new BranchList({
                    el: this.$el.find('#afrh-hd-status-section')[0],
                    data: this.data,
                    dataKey: 'AFRH_W_HISTORIC_DISTRICT_STATE.E3',
                    validateBranch: function (nodes) {
                        var ck1 = vt.isValidDate(nodes,'AFRH_W_HISTORIC_DISTRICT_STATUS_DATE.E50');
                        var ck2 = this.validateHasValues(nodes);
                        return ck1 == true && ck2 == true;
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#period-of-significance-section')[0],
                    data: this.data,
                    dataKey: 'PERIOD_OF_SIGNIFICANCE.E55',
                    validateBranch: function (nodes) {
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#area-of-significance-section')[0],
                    data: this.data,
                    dataKey: 'AREA_OF_SIGNIFICANCE.E55',
                    validateBranch: function (nodes) {
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#afrh-other-section')[0],
                    data: this.data,
                    dataKey: 'OTHER_AFRH_W_DESIGNATION.E3',
                    validateBranch: function (nodes) {
                        return true;
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#other-designation-section')[0],
                    data: this.data,
                    dataKey: 'OTHER_DESIGNATION.E3',
                    validateBranch: function (nodes) {
                        return true;
                        return this.validateHasValues(nodes);
                    }
                }));

                console.log("before score section branchlist");
                this.addBranchList(new BranchList({
                    el: this.$el.find('#score-section')[0],
                    data: this.data,
                    dataKey: 'COMPOSITE_SCORE.E60',
                    //singleEdit: true,
                    // validateBranch: function (nodes) {
                        // var valid = false;
                        // if (nodes[0]["value"] != "") {
                            // console.log(nodes[0]["value"]);
                            // valid = true;
                        // };
                        // console.log(valid);
                        // return valid;
                    // }
                }));
                console.log("added score section branchlist");

                this.addBranchList(new BranchList({
                    el: this.$el.find('#hpmp-section')[0],
                    data: this.data,
                    dataKey: 'HPMP_STATUS.E55',
                    validateBranch: function (nodes) {
                        return true;
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#relative-level-section')[0],
                    data: this.data,
                    dataKey: 'RELATIVE_LEVEL_OF_SIGNIFICANCE.E55',
                    validateBranch: function (nodes) {
                        var goodDate = true;
                        _.each(nodes, function(node){
                            if (node["entitytypeid"] == "RELATIVE_LEVEL_OF_SIGNIFICANCE_DATE.E50") {
                                date_check = isValidDate(node["value"]);
                                if (!date_check[0]){
                                    goodDate = false;
                                }
                                node["value"] = date_check[1];
                                node["label"] = date_check[1];
                            }
                        });
                        return goodDate;
                    }
                }));

            }
        });
    }
);
<commit_msg>remove problematic function that was not in use<commit_after>define(['jquery',
    'underscore',
    'knockout',
    'views/forms/base',
    'views/forms/sections/validation',
    'views/forms/sections/branch-list',
    'bootstrap-datetimepicker',
    'summernote'],
    function ($, _, ko, BaseForm, ValidationTools, BranchList, datetimepicker, summernote) {

        var vt = new ValidationTools;

        return BaseForm.extend({

            initialize: function() {

                $('.totalscore').change(function() {
                    var sum = 0;
                    $('.totalscore').each(function(){
                        sum += parseFloat(this.value);
                    });
                    var comp = document.getElementById("comp");
                    comp.value = sum;
                    $(comp).trigger('change');
                    //comp.innerHTML = sum;
                });

                BaseForm.prototype.initialize.apply(this);

                var date_picker = $('.datetimepicker').datetimepicker({pickTime: false});
                date_picker.on('dp.change', function(evt){
                    $(this).find('input').trigger('change');
                });

                this.addBranchList(new BranchList({
                    el: this.$el.find('#afrh-hd-status-section')[0],
                    data: this.data,
                    dataKey: 'AFRH_W_HISTORIC_DISTRICT_STATE.E3',
                    validateBranch: function (nodes) {
                        var ck1 = vt.isValidDate(nodes,'AFRH_W_HISTORIC_DISTRICT_STATUS_DATE.E50');
                        var ck2 = this.validateHasValues(nodes);
                        return ck1 == true && ck2 == true;
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#period-of-significance-section')[0],
                    data: this.data,
                    dataKey: 'PERIOD_OF_SIGNIFICANCE.E55',
                    validateBranch: function (nodes) {
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#area-of-significance-section')[0],
                    data: this.data,
                    dataKey: 'AREA_OF_SIGNIFICANCE.E55',
                    validateBranch: function (nodes) {
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#afrh-other-section')[0],
                    data: this.data,
                    dataKey: 'OTHER_AFRH_W_DESIGNATION.E3',
                    validateBranch: function (nodes) {
                        return true;
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#other-designation-section')[0],
                    data: this.data,
                    dataKey: 'OTHER_DESIGNATION.E3',
                    validateBranch: function (nodes) {
                        return true;
                        return this.validateHasValues(nodes);
                    }
                }));

                console.log("before score section branchlist");
                this.addBranchList(new BranchList({
                    el: this.$el.find('#score-section')[0],
                    data: this.data,
                    dataKey: 'COMPOSITE_SCORE.E60',
                    //singleEdit: true,
                    // validateBranch: function (nodes) {
                        // var valid = false;
                        // if (nodes[0]["value"] != "") {
                            // console.log(nodes[0]["value"]);
                            // valid = true;
                        // };
                        // console.log(valid);
                        // return valid;
                    // }
                }));
                console.log("added score section branchlist");

                this.addBranchList(new BranchList({
                    el: this.$el.find('#hpmp-section')[0],
                    data: this.data,
                    dataKey: 'HPMP_STATUS.E55',
                    validateBranch: function (nodes) {
                        return true;
                        return this.validateHasValues(nodes);
                    }
                }));

                this.addBranchList(new BranchList({
                    el: this.$el.find('#relative-level-section')[0],
                    data: this.data,
                    dataKey: 'RELATIVE_LEVEL_OF_SIGNIFICANCE.E55',
                    validateBranch: function (nodes) {
                        var goodDate = true;
                        _.each(nodes, function(node){
                            if (node["entitytypeid"] == "RELATIVE_LEVEL_OF_SIGNIFICANCE_DATE.E50") {
                                date_check = isValidDate(node["value"]);
                                if (!date_check[0]){
                                    goodDate = false;
                                }
                                node["value"] = date_check[1];
                                node["label"] = date_check[1];
                            }
                        });
                        return goodDate;
                    }
                }));

            }
        });
    }
);
<|endoftext|>


<commit_before>/*
 * Provides an evaluator for a JavaScript based genome.
 */
function JSEvaluator(inputs, outputs, phenotypeFactory, isMatches,
        errorThreshold, idealGenomeLength)
{
    InputValidator.validateNotEmpty("inputs", inputs);
    InputValidator.validateNotEmpty("outputs", outputs);
    InputValidator.validateNotNull("phenotypeFactory", phenotypeFactory);

    var idealEvaluation = 1000;

    this.getInputs = function()
    {
        return inputs;
    }

    this.getOutputs = function()
    {
        return outputs;
    }

    this.getPhenotypeFactory = function()
    {
        return phenotypeFactory;
    }

    this.isMatches = function()
    {
        return isMatches;
    }

    this.getErrorThreshold = function()
    {
        return errorThreshold;
    }

    this.getIdealGenomeLength = function()
    {
        return idealGenomeLength;
    }

    this.getIdealEvaluation = function()
    {
        return idealEvaluation;
    }

    this.computeMatches = function(phenotype)
    {
        InputValidator.validateNotNull("phenotype", phenotype);

        var answer = 0;

        for (var i = 0; i < inputs.length; i++)
        {
            try
            {
                var result = execute(phenotype, inputs[i]);

                if (result === outputs[i])
                {
                    answer++;
                }
            }
            catch (ignore)
            {}
        }

        return answer;
    }

    this.computeSumError = function(phenotype)
    {
        InputValidator.validateNotNull("phenotype", phenotype);

        var sumError = 0.0;

        for (var i = 0; i < inputs.length; i++)
        {
            try
            {
                var result = execute(phenotype, inputs[i]);

                if (isNaN(result))
                {
                    sumError += 10.0;
                }
                else
                {
                    sumError += Math.abs(outputs[i] - result);
                }
            }
            catch (e)
            {
                sumError += 10.0;
            }
        }

        return sumError;
    }

    this.evaluate = function(population)
    {
        InputValidator.validateNotEmpty("population", population);

        for (var i = 0; i < population.length; i++)
        {
            var genome = population[i];
            genome.fitness = 0.0;
            genome.phenotype = phenotypeFactory.create(genome);

            if (genome.phenotype)
            {
                // Valid function.
                genome.fitness = 500.0;

                if (isMatches)
                {
                    this.evaluateMatches(genome);
                }
                else
                {
                    this.evaluateNumericError(genome);
                }
            }
            else
            {
                // Invalid function.
                this.evaluateInvalidFunction(genome);
            }
        }
    }

    this.evaluateInvalidFunction = function(genome)
    {
        var errorCount = genome.errorCount;

        if (!isNaN(errorCount))
        {
            genome.fitness += 300.0 / (errorCount + 1);
        }

        var warningCount = genome.warningCount;

        if (!isNaN(warningCount))
        {
            genome.fitness += 100.0 / (warningCount + 1);
        }
    }

    this.evaluateMatches = function(genome)
    {
        var matches = this.computeMatches(genome.phenotype);

        if (matches === outputs.length)
        {
            // Perfect evaluation.
            genome.fitness = idealEvaluation;

            if (idealGenomeLength)
            {
                // Add pressure for the shortest genome.
                genome.fitness += idealGenomeLength - genome.length;
            }
        }
        else
        {
            genome.fitness += matches * (400.0 / outputs.length);
        }
    }

    this.evaluateNumericError = function(genome)
    {
        var sumError = this.computeSumError(genome.phenotype);

        if (sumError <= errorThreshold)
        {
            // Perfect evaluation.
            genome.fitness = idealEvaluation;

            if (idealGenomeLength)
            {
                // Add pressure for the shortest genome.
                genome.fitness += idealGenomeLength - genome.length;
            }
        }
        else
        {
            genome.fitness += 400.0 / sumError;
        }
    }

    function execute(phenotype, input)
    {
        var answer;

        if (Array.isArray(input))
        {
            if (input.length === 2)
            {
                answer = phenotype(input[0], input[1]);
            }
            else
            {
                throw "Unhandled number of inputs: " + input.length;
            }
        }
        else
        {
            answer = phenotype(input);
        }

        return answer;
    }
}
<commit_msg>Changed evaluateNumericError() to limit the maximum fitness value.<commit_after>/*
 * Provides an evaluator for a JavaScript based genome.
 */
function JSEvaluator(inputs, outputs, phenotypeFactory, isMatches,
        errorThreshold, idealGenomeLength)
{
    InputValidator.validateNotEmpty("inputs", inputs);
    InputValidator.validateNotEmpty("outputs", outputs);
    InputValidator.validateNotNull("phenotypeFactory", phenotypeFactory);

    var idealEvaluation = 1000;

    this.getInputs = function()
    {
        return inputs;
    }

    this.getOutputs = function()
    {
        return outputs;
    }

    this.getPhenotypeFactory = function()
    {
        return phenotypeFactory;
    }

    this.isMatches = function()
    {
        return isMatches;
    }

    this.getErrorThreshold = function()
    {
        return errorThreshold;
    }

    this.getIdealGenomeLength = function()
    {
        return idealGenomeLength;
    }

    this.getIdealEvaluation = function()
    {
        return idealEvaluation;
    }

    this.computeMatches = function(phenotype)
    {
        InputValidator.validateNotNull("phenotype", phenotype);

        var answer = 0;

        for (var i = 0; i < inputs.length; i++)
        {
            try
            {
                var result = execute(phenotype, inputs[i]);

                if (result === outputs[i])
                {
                    answer++;
                }
            }
            catch (ignore)
            {}
        }

        return answer;
    }

    this.computeSumError = function(phenotype)
    {
        InputValidator.validateNotNull("phenotype", phenotype);

        var sumError = 0.0;

        for (var i = 0; i < inputs.length; i++)
        {
            try
            {
                var result = execute(phenotype, inputs[i]);

                if (isNaN(result))
                {
                    sumError += 10.0;
                }
                else
                {
                    sumError += Math.abs(outputs[i] - result);
                }
            }
            catch (e)
            {
                sumError += 10.0;
            }
        }

        return sumError;
    }

    this.evaluate = function(population)
    {
        InputValidator.validateNotEmpty("population", population);

        for (var i = 0; i < population.length; i++)
        {
            var genome = population[i];
            genome.fitness = 0.0;
            genome.phenotype = phenotypeFactory.create(genome);

            if (genome.phenotype)
            {
                // Valid function.
                genome.fitness = 500.0;

                if (isMatches)
                {
                    this.evaluateMatches(genome);
                }
                else
                {
                    this.evaluateNumericError(genome);
                }
            }
            else
            {
                // Invalid function.
                this.evaluateInvalidFunction(genome);
            }
        }
    }

    this.evaluateInvalidFunction = function(genome)
    {
        var errorCount = genome.errorCount;

        if (!isNaN(errorCount))
        {
            genome.fitness += 300.0 / (errorCount + 1);
        }

        var warningCount = genome.warningCount;

        if (!isNaN(warningCount))
        {
            genome.fitness += 100.0 / (warningCount + 1);
        }
    }

    this.evaluateMatches = function(genome)
    {
        var matches = this.computeMatches(genome.phenotype);

        if (matches === outputs.length)
        {
            // Perfect evaluation.
            genome.fitness = idealEvaluation;

            if (idealGenomeLength)
            {
                // Add pressure for the shortest genome.
                genome.fitness += idealGenomeLength - genome.length;
            }
        }
        else
        {
            genome.fitness += matches * (400.0 / outputs.length);
        }
    }

    this.evaluateNumericError = function(genome)
    {
        var sumError = this.computeSumError(genome.phenotype);

        if (sumError <= errorThreshold)
        {
            // Perfect evaluation.
            genome.fitness = idealEvaluation;

            if (idealGenomeLength)
            {
                // Add pressure for the shortest genome.
                genome.fitness += idealGenomeLength - genome.length;
            }
        }
        else
        {
            genome.fitness += 400.0 / (sumError / errorThreshold);
        }
    }

    function execute(phenotype, input)
    {
        var answer;

        if (Array.isArray(input))
        {
            if (input.length === 2)
            {
                answer = phenotype(input[0], input[1]);
            }
            else
            {
                throw "Unhandled number of inputs: " + input.length;
            }
        }
        else
        {
            answer = phenotype(input);
        }

        return answer;
    }
}
<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react';
import cx from 'react-classset';

import BuildPicker from './BuildPicker';
import GitModal from './git_modal';

const maybeCallMethod = (obj, method, ...args) => {
  obj[method] && obj[method](...args);
};

export default class EditorHeader extends Component {

  constructor(props) {
    super(props);
    this.state = {
      gitModalIsVisible: null
    };
  }

  onUpdateName = () => {
    const nameInputNode = React.findDOMNode(this.refs.nameInput);
    maybeCallMethod(this.props, 'onUpdateName', nameInputNode.value);
  }

  handleOnSubmit = (e)  => {
    e.preventDefault();
    const method = this.belongsToCurrentUser() ? 'onSave' : 'onFork';
    this[method](e);
  }

  onSave = (e) => {
    e.preventDefault();
    maybeCallMethod(this.props, 'onSave');
  }

  onFork = (e) => {
    e.preventDefault();
    maybeCallMethod(this.props, 'onFork');
  }

  onPick = (e) => {
    e.preventDefault();
    maybeCallMethod(this.props, 'onPick');
  }

  onUpdateBuild = (value) => {
    maybeCallMethod(this.props, 'onUpdateBuild', value);
  }

  belongsToCurrentUser() {
    const { currentUser, app : { creatorId} } = this.props;
    return currentUser && currentUser.id === creatorId;
  }

  currentUserIsAdmin() {
    const { currentUser } = this.props;
    return currentUser && currentUser.admin;
  }

  showGitModal = (e) => {
    e.preventDefault();
    this.setState({gitModalIsVisible: true});
  }

  hideGitModal = (e) => {
    e.preventDefault();
    this.setState({gitModalIsVisible: false});
  }

  renderGitModal = () => {
    return (
      <GitModal app={this.props.app}
               onClickBackdrop={this.hideGitModal}
               isOpen={this.state.gitModalIsVisible} />
    )
  }

  renderGitButton() {
      return (
        <button
          onClick={this.showGitModal}
          className="btn-info editor-header__button"
        >
          Clone
        </button>
      );
  }

  renderForkButton() {
      return (
        <button
          onClick={this.onFork}
          className="btn-info editor-header__button"
        >
          Fork
        </button>
      );
  }

  renderPickButton() {
    if (this.currentUserIsAdmin()) {
      return (
        <button
          onClick={this.onPick}
          className="btn-info editor-header__button"
        >
          {this.props.appIsPicked ? 'Unpick' : 'Pick'}
        </button>
      );
    }
  }

  renderSaveButton() {

    if (this.belongsToCurrentUser()) {
      return (
        <button
          onClick={this.onSave}
          className="btn-info editor-header__button"
        >
          Save
        </button>
      );
    }
  }

  render() {
    const { useDarkTheme, builds, name, buildId, onFileSelectorToggle } = this.props;
    const classes = cx({
      'editor-header': true,
      'editor-header--dark': useDarkTheme
    });

    return (

        <button
          className="editor-header__drawer-toggle"
          onClick={onFileSelectorToggle}
        title="Open file drawer">

        </button>
        <form onSubmit={this.handleOnSubmit}>
          <input
            type="text"
            ref="nameInput"
            placeholder="Give this app a title"
            value={name}
            onChange={this.onUpdateName}
            className="editor-header__name-input"
          />
          <BuildPicker
            onChange={this.onUpdateBuild}
            builds={builds}
            selectedBuildId={buildId}
          />

            {this.renderForkButton()}
            {this.renderGitButton()}
            {this.renderPickButton()}
            {this.renderSaveButton()}

        </form>
        {this.renderGitModal()}

    );
  }
}
<commit_msg>only show fork for admins for now<commit_after>'use strict';

import React, { Component } from 'react';
import cx from 'react-classset';

import BuildPicker from './BuildPicker';
import GitModal from './git_modal';

const maybeCallMethod = (obj, method, ...args) => {
  obj[method] && obj[method](...args);
};

export default class EditorHeader extends Component {

  constructor(props) {
    super(props);
    this.state = {
      gitModalIsVisible: null
    };
  }

  onUpdateName = () => {
    const nameInputNode = React.findDOMNode(this.refs.nameInput);
    maybeCallMethod(this.props, 'onUpdateName', nameInputNode.value);
  }

  handleOnSubmit = (e)  => {
    e.preventDefault();
    const method = this.belongsToCurrentUser() ? 'onSave' : 'onFork';
    this[method](e);
  }

  onSave = (e) => {
    e.preventDefault();
    maybeCallMethod(this.props, 'onSave');
  }

  onFork = (e) => {
    e.preventDefault();
    maybeCallMethod(this.props, 'onFork');
  }

  onPick = (e) => {
    e.preventDefault();
    maybeCallMethod(this.props, 'onPick');
  }

  onUpdateBuild = (value) => {
    maybeCallMethod(this.props, 'onUpdateBuild', value);
  }

  belongsToCurrentUser() {
    const { currentUser, app : { creatorId} } = this.props;
    return currentUser && currentUser.id === creatorId;
  }

  currentUserIsAdmin() {
    const { currentUser } = this.props;
    return currentUser && currentUser.admin;
  }

  showGitModal = (e) => {
    e.preventDefault();
    this.setState({gitModalIsVisible: true});
  }

  hideGitModal = (e) => {
    e.preventDefault();
    this.setState({gitModalIsVisible: false});
  }

  renderGitModal = () => {
    return (
      <GitModal app={this.props.app}
               onClickBackdrop={this.hideGitModal}
               isOpen={this.state.gitModalIsVisible} />
    )
  }

  renderGitButton() {
      return (
        <button
          onClick={this.showGitModal}
          className="btn-info editor-header__button"
        >
          Clone
        </button>
      );
  }

  renderForkButton() {
    if (this.currentUserIsAdmin()) {
      return (
        <button
          onClick={this.onFork}
          className="btn-info editor-header__button"
        >
          Fork
        </button>
      );
    }
  }

  renderPickButton() {
    if (this.currentUserIsAdmin()) {
      return (
        <button
          onClick={this.onPick}
          className="btn-info editor-header__button"
        >
          {this.props.appIsPicked ? 'Unpick' : 'Pick'}
        </button>
      );
    }
  }

  renderSaveButton() {

    if (this.belongsToCurrentUser()) {
      return (
        <button
          onClick={this.onSave}
          className="btn-info editor-header__button"
        >
          Save
        </button>
      );
    }
  }

  render() {
    const { useDarkTheme, builds, name, buildId, onFileSelectorToggle } = this.props;
    const classes = cx({
      'editor-header': true,
      'editor-header--dark': useDarkTheme
    });

    return (

        <button
          className="editor-header__drawer-toggle"
          onClick={onFileSelectorToggle}
        title="Open file drawer">

        </button>
        <form onSubmit={this.handleOnSubmit}>
          <input
            type="text"
            ref="nameInput"
            placeholder="Give this app a title"
            value={name}
            onChange={this.onUpdateName}
            className="editor-header__name-input"
          />
          <BuildPicker
            onChange={this.onUpdateBuild}
            builds={builds}
            selectedBuildId={buildId}
          />

            {this.renderForkButton()}
            {this.renderGitButton()}
            {this.renderPickButton()}
            {this.renderSaveButton()}

        </form>
        {this.renderGitModal()}

    );
  }
}
<|endoftext|>


<commit_before>define([
  "jquery",
  "lib/page/viewport_helper",
  "lib/core/feature_detect"
], function($, withViewportHelper, features) {

  "use strict";

  var HeroParallax,
      _autoInit,
      _stopScroll,
      _frame,
      _started = false,
      _heroBanners = [],
      _transform = features.transform().js;

  HeroParallax = function( args ) {
    if (this.viewport().width <= 1024) { return; }

    this.$els = args.$els || $(".js-bg-parallax");

    $.each(this.$els, function(i) {

      var $el = this.$els.eq(i),
          $animEl = $el.find(".hero-banner__image");

      _heroBanners[i] = {
        $el: $el,
        $animEl: $animEl,
        imageHeight: $animEl.height(),
        heroHeight: $el.height()
      };

      if (this.withinViewport($el)) {
        $animEl
          .addClass("hero-banner__image-first-position")
          .on(window.lp.supports.transitionend, function() {
            $(event.target).removeClass("hero-banner__image-first-position");
          });
      }

      $animEl.css(_transform, "translate3d(0, " + this.calculatePosition(i).toFixed(2) + "px, 0) scale(1) rotate(0deg)");

    }.bind(this));

    $(window).on("scroll", this._onScroll.bind(this));
  };

  withViewportHelper.call(HeroParallax.prototype);

  HeroParallax.prototype.calculatePosition = function(i) {
    var banner = _heroBanners[i],
        viewport = this.viewport(),
        positionInViewport = this.positionInViewport(banner.$el),
        lengthOnPage = viewport.height + banner.heroHeight,
        maxParallax = (banner.imageHeight - banner.heroHeight),
        scrolledPercentage = (positionInViewport.top + banner.heroHeight) / lengthOnPage;

    return -1 * maxParallax * scrolledPercentage;
  };

  HeroParallax.prototype._updateBg = function( i ) {
    var $el = _heroBanners[ i ].$el,
        $animEl = _heroBanners[ i ].$animEl;

    if (this.withinViewport($el)) {
      $animEl.css(_transform, "translate3d(0, " + this.calculatePosition(i).toFixed(2) + "px, 0) scale(1) rotate(0deg)");
    }
  };

  HeroParallax.prototype._update = function() {
    _frame = window.lp.supports.requestAnimationFrame.call(window, this._update.bind(this));
    $.each(this.$els, this._updateBg.bind(this));
  };

  HeroParallax.prototype._startRAF = function() {
    if (!_started){
      window.lp.supports.requestAnimationFrame.call(window, this._update.bind(this));
      _started = true;
    }
  };

  HeroParallax.prototype._stopRAF = function() {
    window.lp.supports.cancelAnimationFrame.call(window, _frame);
    _started = false;
  };

  HeroParallax.prototype._onScroll = function() {
    clearTimeout(_stopScroll);
    _stopScroll = setTimeout(this._stopRAF.bind(this), 100);
    this._startRAF();
  };

  _autoInit = function() {
    if ( window.lp.supports.requestAnimationFrame ){
      var $els = $(".js-bg-parallax");
      if ($els.length) {
        new HeroParallax({
          $els: $els
        });
      }
    }
  };

  //Waits for feature detect to be available
  if (window.lp.supports.requestAnimationFrame){
    _autoInit();
  }else {
    $(document).on(":featureDetect/available", function() {
      _autoInit();
    });
  }

  return HeroParallax;

});
<commit_msg>Wait parallax effect until first position is set<commit_after>define([
  "jquery",
  "lib/page/viewport_helper",
  "lib/core/feature_detect"
], function($, withViewportHelper, features) {

  "use strict";

  var HeroParallax,
      _autoInit,
      _stopScroll,
      _frame,
      _started = false,
      _heroBanners = [],
      _parallaxReady = true,
      _transform = features.transform().js;

  HeroParallax = function( args ) {
    if (this.viewport().width <= 1024) { return; }

    this.$els = args.$els || $(".js-bg-parallax");

    $.each(this.$els, function(i) {

      var $el = this.$els.eq(i),
          $animEl = $el.find(".hero-banner__image");

      _heroBanners[i] = {
        $el: $el,
        $animEl: $animEl,
        imageHeight: $animEl.height(),
        heroHeight: $el.height()
      };

      if (this.withinViewport($el)) {
        _parallaxReady = false;
        $animEl
          .addClass("hero-banner__image-first-position")
          .on(window.lp.supports.transitionend, function() {
            $animEl.removeClass("hero-banner__image-first-position");
            _parallaxReady = true;
          });
      }

      $animEl.css(_transform, "translate3d(0, " + this.calculatePosition(i).toFixed(2) + "px, 0) scale(1) rotate(0deg)");

    }.bind(this));

    $(window).on("scroll", this._onScroll.bind(this));
  };

  withViewportHelper.call(HeroParallax.prototype);

  HeroParallax.prototype.calculatePosition = function(i) {
    var banner = _heroBanners[i],
        viewport = this.viewport(),
        positionInViewport = this.positionInViewport(banner.$el),
        lengthOnPage = viewport.height + banner.heroHeight,
        maxParallax = (banner.imageHeight - banner.heroHeight),
        scrolledPercentage = (positionInViewport.top + banner.heroHeight) / lengthOnPage;

    return -1 * maxParallax * scrolledPercentage;
  };

  HeroParallax.prototype._updateBg = function( i ) {
    var $el = _heroBanners[ i ].$el,
        $animEl = _heroBanners[ i ].$animEl;

    if (this.withinViewport($el)) {
      $animEl.css(_transform, "translate3d(0, " + this.calculatePosition(i).toFixed(2) + "px, 0) scale(1) rotate(0deg)");
    }
  };

  HeroParallax.prototype._update = function() {
    _frame = window.lp.supports.requestAnimationFrame.call(window, this._update.bind(this));
    $.each(this.$els, this._updateBg.bind(this));
  };

  HeroParallax.prototype._startRAF = function() {
    if (!_started){
      window.lp.supports.requestAnimationFrame.call(window, this._update.bind(this));
      _started = true;
    }
  };

  HeroParallax.prototype._stopRAF = function() {
    window.lp.supports.cancelAnimationFrame.call(window, _frame);
    _started = false;
  };

  HeroParallax.prototype._onScroll = function() {
    clearTimeout(_stopScroll);
    _stopScroll = setTimeout(this._stopRAF.bind(this), 100);
    if (_parallaxReady){
      this._startRAF();
    }
  };

  _autoInit = function() {
    if ( window.lp.supports.requestAnimationFrame ){
      var $els = $(".js-bg-parallax");
      if ($els.length) {
        new HeroParallax({
          $els: $els
        });
      }
    }
  };

  //Waits for feature detect to be available
  if (window.lp.supports.requestAnimationFrame){
    _autoInit();
  }else {
    $(document).on(":featureDetect/available", function() {
      _autoInit();
    });
  }

  return HeroParallax;

});
<|endoftext|>


<commit_before>angular.module('ocWebGui.screen', ['ocWebGui.screen.service', 'ui.router', 'ocWebGui.shared.time'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('screen', {
        url: '/screen',
        templateUrl: 'screen/_screen.html',
        controller: 'ScreenController',
        controllerAs: 'screen',
        navbarOverlay: true
      });
  })
  .controller('ScreenController', function ($interval, $scope, shared, Agents) {
    var vm = this;
    var fetchDataInterval;

    vm.teams = shared.getTeams();
    vm.states = shared.getStates();
    vm.message = 'Tilat';
    vm.agents = [];
    vm.green = 0;
    vm.yellow = 0;
    vm.red = 0;
    vm.number_of_columns = 0;

    function fetchData() {
      Agents.query(function (agents) {
        var green = 0;
        var yellow = 0;
        var red = 0;

        // Agent status coloring and number tally.
        vm.agents = agents.map(function (agent) {
          switch (agent.status) {
            case 'Vapaa':
              agent.color = 'green';
              green++;
              break;
            case 'Jälkikirjaus':
            case 'Puhelu':
              agent.color = 'yellow';
              yellow++;
              break;
            case agent.status.match(/^Varattu \(.*\)/):
              agent.status = agent.status.match(/\((.*?)\)/ )[1];
              break;
            default:
              agent.color = 'red';
              red++;
              break;
          }
          return agent;
        });

        vm.green = green;
        vm.yellow = yellow;
        vm.red = red;

        vm.number_of_columns = (agents.length > 9) ? 'four-col' : 'three-col';
      });
    }

    vm.trimName = function (agent) {
      return agent.first_name + ' ' + agent.last_name.charAt(0);
    };

    fetchDataInterval = $interval(fetchData, 5000);
    $scope.$on('$destroy', function () {
      $interval.cancel(fetchDataInterval);
    });

    fetchData();
  });
<commit_msg>working version of switch case<commit_after>angular.module('ocWebGui.screen', ['ocWebGui.screen.service', 'ui.router', 'ocWebGui.shared.time'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('screen', {
        url: '/screen',
        templateUrl: 'screen/_screen.html',
        controller: 'ScreenController',
        controllerAs: 'screen',
        navbarOverlay: true
      });
  })
  .controller('ScreenController', function ($interval, $scope, shared, Agents) {
    var vm = this;
    var fetchDataInterval;

    vm.teams = shared.getTeams();
    vm.states = shared.getStates();
    vm.message = 'Tilat';
    vm.agents = [];
    vm.green = 0;
    vm.yellow = 0;
    vm.red = 0;
    vm.number_of_columns = 0;

    function fetchData() {
      Agents.query(function (agents) {
        var green = 0;
        var yellow = 0;
        var red = 0;

        // Agent status coloring and number tally.
        vm.agents = agents.map(function (agent) {
          switch (agent.status) {
            case 'Vapaa':
              agent.color = 'green';
              green++;
              break;
            case 'Jälkikirjaus':
            case 'Puhelu':
              agent.color = 'yellow';
              yellow++;
              break;
            case String(agent.status.match(/^Varattu \(.*\)/)):
              agent.status = agent.status.match(/^Varattu \((.*)\)/)[1];
              break;
            default:
              agent.color = 'red';
              red++;
              break;
          }
          return agent;
        });

        vm.green = green;
        vm.yellow = yellow;
        vm.red = red;

        vm.number_of_columns = (agents.length > 9) ? 'four-col' : 'three-col';
      });
    }

    vm.trimName = function (agent) {
      return agent.first_name + ' ' + agent.last_name.charAt(0);
    };

    fetchDataInterval = $interval(fetchData, 5000);
    $scope.$on('$destroy', function () {
      $interval.cancel(fetchDataInterval);
    });

    fetchData();
  });
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.version.version-directive', [])

.directive('appDiagram', [function() {
  return {
    restrict: 'E',
    scope: {},
    templateUrl: 'components/appdiagram/appdiagram-directive.html',
    link: function(scope, element, attrs) {
      scope.poolPadding = 10;
      scope.pools = [
        {
          title: 'awesome.app.dev.company.com.au',
          x: 20,
          y: 20,
          width: 140,
          height: 80
        },
        {
          title: 'questionable.app.prod-www.company.com.au',
          x: 20,
          y: 140,
          width: 140,
          height: 80
        }
      ];
    }
  };
}]);

function startMove(e) {
  document.documentElement.moveStartClientX = e.clientX;
  document.documentElement.moveStartClientY = e.clientY;
  document.documentElement.moveStartTarget = e.target;
  document.documentElement.moveStartTargetX = e.target.getAttribute('x');
  document.documentElement.moveStartTargetY = e.target.getAttribute('y');
  document.documentElement.setAttribute("onmousemove", "moveIt(event)");
}

function moveIt(e) {
  var group = document.documentElement.moveStartTarget.parentNode;
  for (var i = 0; i < group.childNodes.length; i++) {
    if (!group.childNodes[i].setAttribute) continue;
    group.childNodes[i].setAttribute("x", parseInt(document.documentElement.moveStartTargetX) + e.clientX - document.documentElement.moveStartClientX);
    group.childNodes[i].setAttribute("y", parseInt(document.documentElement.moveStartTargetY) + e.clientY - document.documentElement.moveStartClientY);
  }
}

function endMove(e) {
  document.documentElement.setAttribute("onmousemove", null)
}
<commit_msg>refactor x/y parsing on dragable<commit_after>'use strict';

angular.module('myApp.version.version-directive', [])

.directive('appDiagram', [function() {
  return {
    restrict: 'E',
    scope: {},
    templateUrl: 'components/appdiagram/appdiagram-directive.html',
    link: function(scope, element, attrs) {
      scope.poolPadding = 10;
      scope.pools = [
        {
          title: 'awesome.app.dev.company.com.au',
          x: 20,
          y: 20,
          width: 140,
          height: 80
        },
        {
          title: 'questionable.app.prod-www.company.com.au',
          x: 20,
          y: 140,
          width: 140,
          height: 80
        }
      ];
    }
  };
}]);

function startMove(e) {
  document.documentElement.moveStartClientX = e.clientX;
  document.documentElement.moveStartClientY = e.clientY;
  document.documentElement.moveStartTarget = e.target;
  document.documentElement.moveStartTargetX = parseInt(e.target.getAttribute('x'));
  document.documentElement.moveStartTargetY = parseInt(e.target.getAttribute('y'));
  document.documentElement.setAttribute("onmousemove", "moveIt(event)");
}

function moveIt(e) {
  var group = document.documentElement.moveStartTarget.parentNode;
  for (var i = 0; i < group.childNodes.length; i++) {
    if (!group.childNodes[i].setAttribute) continue;
    group.childNodes[i].setAttribute("x", document.documentElement.moveStartTargetX + e.clientX - document.documentElement.moveStartClientX);
    group.childNodes[i].setAttribute("y", document.documentElement.moveStartTargetY + e.clientY - document.documentElement.moveStartClientY);
  }
}

function endMove(e) {
  document.documentElement.setAttribute("onmousemove", null)
}
<|endoftext|>


<commit_before>import Ember from 'ember'

const {
  Component,
  computed,
  A: emberA
} = Ember

export default Component.extend({
  items: computed(function() { return emberA() }),

  contributorIds: computed('items.[]', function() {
    return this.get('items')
      .map(i => i.belongsTo('user').id())
      .uniq()
  }),

  contributorCount: computed('contributorIds.[]', function() {
    return this.get('contributorIds').length
  })
})
<commit_msg>Use link to identifiy contributor count on contribution-calendar<commit_after>import Ember from 'ember'

const {
  Component,
  computed,
  A: emberA
} = Ember

export default Component.extend({
  items: computed(function() { return emberA() }),

  contributorIds: computed('items.[]', function() {
    return this.get('items')
      .map(i => i.belongsTo('user').link())
      .uniq()
  }),

  contributorCount: computed('contributorIds.[]', function() {
    return this.get('contributorIds').length
  })
})
<|endoftext|>


<commit_before>import ActiveModelAdapter from 'active-model-adapter';
import ActiveModelSerializer from 'active-model-adapter/active-model-serializer';

export default {
  name: 'active-model-adapter',
  initialize: function(applicationOrRegistry) {
    var registry, container;
    if (applicationOrRegistry.registry && applicationOrRegistry.container) {
      // initializeStoreService was registered with an
      // instanceInitializer. The first argument is the application
      // instance.
      registry = applicationOrRegistry.registry;
      container = applicationOrRegistry.container;
    } else {
      // initializeStoreService was called by an initializer instead of
      // an instanceInitializer. The first argument is a registy. This
      // case allows ED to support Ember pre 1.12
      registry = applicationOrRegistry;
      if (registry.container) { // Support Ember 1.10 - 1.11
        container = registry.container();
      } else { // Support Ember 1.9
        container = registry;
      }
    }

    registry.register('adapter:-active-model', ActiveModelAdapter);
    registry.register('serializer:-active-model', ActiveModelSerializer);
  }
};
<commit_msg>Set isNewSerializerAPI for ActiveModelSerializer<commit_after>import ActiveModelAdapter from 'active-model-adapter';
import ActiveModelSerializer from 'active-model-adapter/active-model-serializer';

export default {
  name: 'active-model-adapter',
  initialize: function(applicationOrRegistry) {
    var registry, container;
    if (applicationOrRegistry.registry && applicationOrRegistry.container) {
      // initializeStoreService was registered with an
      // instanceInitializer. The first argument is the application
      // instance.
      registry = applicationOrRegistry.registry;
      container = applicationOrRegistry.container;
    } else {
      // initializeStoreService was called by an initializer instead of
      // an instanceInitializer. The first argument is a registy. This
      // case allows ED to support Ember pre 1.12
      registry = applicationOrRegistry;
      if (registry.container) { // Support Ember 1.10 - 1.11
        container = registry.container();
      } else { // Support Ember 1.9
        container = registry;
      }
    }

    registry.register('adapter:-active-model', ActiveModelAdapter);
    registry.register('serializer:-active-model', ActiveModelSerializer.extend({ isNewSerializerAPI: true }));
  }
};
<|endoftext|>


<commit_before>/*
 * TimeCard View
 * Copyright ©2015 Thomas Nelson, Jacob Nichols, David Opp, Todd Brochu,
Andrew McGown, Sasha Fahrenkopf, Cameron B. White.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE text file in the root directory of this source tree.
 */
import React, { PropTypes } from "react"
import { Link } from "react-router"
import moment from "moment"
import _ from "lodash"
import FluxComponent from 'flummox/component';
import flux from "../../flux/flux"
import DayOverviewCalendar from '../DayOverviewCalendar/DayOverviewCalendar'
import Page from '../Page/Page'

export default class DayOverview extends React.Component {
  render() {
    return (
      <FluxComponent
        connectToStores={['kronos']}
        stateGetter={([kronos]) => {
          const { params } = this.props
          const date = moment(params.date, 'YYYY-MM-DD')
          const day = kronos.getDay(date)
          const inPunches = kronos.getInPunchesForDate(date)
          const outPunches = kronos.getOutPunchesForDate(date)
          const exceptions = kronos.getExceptionsForDate(date)
          return {
            day,
            inPunches,
            outPunches,
            exceptions,
          }
        }}
      >
        <Overview {...this.props} />
      </FluxComponent>
    )
  }
}

class Overview extends React.Component {
  render() {
    // XXX Hack! Need to pull from API in a better way
    let lastKronosTimeZone = ""

    const { params, day, inPunches, outPunches, exceptions } = this.props
    const inPunchesChain = _.chain(inPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "InPunch",
          })
        })
    const outPunchesChain = _.chain(outPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "OutPunch",
          })
        })
	const ExceptionsChain = _.chain(exceptions)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "Exception",
          })
        })
    /*
    const shiftsChain = _.chain(Schedule)
      .get('ScheduleItems.ScheduleShift', [])
      .filter({StartDate: moment(params.date).format("M/DD/YYYY")})
      .pluck('ShiftSegments.ShiftSegment')
      .compact()
      .map(eachShift => {
        const { StartDate, EndDate, StartTime, EndTime} = eachShift
        return [
          {
            time: kronosMoment(StartDate, StartTime, lastKronosTimeZone),
            type: 'scheduledIn'
          },{
            time: kronosMoment(EndDate, EndTime, lastKronosTimeZone),
            type: 'scheduledOut'
          }
        ]
      })
      .flatten()
    */
    const execp = ExceptionsChain
		.map(punch => <Entry {...punch} />)
       .value()
    const punches = inPunchesChain
       .concat(outPunchesChain.value())
       //.concat(shiftsChain.value())
       .sortBy('time')
       .map(punch => <Entry {...punch} />)
       .value()

    const date = moment(params.date)
    const year = date.format("YYYY")
    const month = date.format("MM")

    const dayHeaders = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]

    return (
      <Page>
        <DayHeader date={date}/>

            { punches.length > 0 ?

{execp}{punches}

 :

No punches today

}

              <DayOverviewCalendar year={year} month={month-1} headers={dayHeaders} />

              <FluxComponent connectToStores={{
                  kronos: store => ({
                    day: store.getDay(moment(this.props.params.date, 'YYYY-MM-DD'))
                  })
              }}>
                <DayStats />
              </FluxComponent>

      </Page>
    )
  }
}

class DayHeader extends React.Component {
  render() {
    const displayDate = this.props.date.format("MMMM DD")
    return (

          <Link to="day" params={{date: this.props.date.clone().subtract(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-left subtle-btn">

                «

          </Link>

{displayDate}

          <Link to="day" params={{date: this.props.date.clone().add(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-right subtle-btn">

                »

          </Link>

 {/*For space*/}

    )
  }
}

class DayStats extends React.Component {
  render() {
    const { day } = this.props
    const total = day ? day.total : ''
    return (

Total Hours Worked: {total}

    )
  }
}

class Entry extends React.Component {
  render() {
    const panelClassDefault = "panel time-entry day"
    const glyphClassDefault = "day-icon"

    const settings = {
      InPunch: {
        action: "Clocked in",
        panelClass: panelClassDefault + " " + "time-in",
        glyphClass: "icon-truck"
      },
      OutPunch: {
        action: "Clocked out",
        panelClass: panelClassDefault + " " + "time-out",
        glyphClass: "icon-truck"
      },
      scheduledIn: {
        action: "Shift started",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      },
      scheduledOut: {
        action: "Shift ended",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      },
	  Exception: {
        action: "Exception",
        panelClass: panelClassDefault + " " + "time-in",
        glyphClass: "icon-truck"
      },
    }

    const {action, panelClass, glyphClass} = settings[this.props.type]
	console.log(this.props)
	if(this.props.type == "Exception") {
		console.log(this.props.typeName)
		const expection = this.props.typeName
		return (

			  <ActionIcon action = {action}/>
			  {expection}

		)
	} else {
		const time = moment(this.props.time).format('h:mma')

		const code = this.props.LaborName

		return (

			  <ActionIcon action = {action}/>
			  {action}
			  {time}
			  {code}

		)
	}
  }
}

class ActionIcon extends React.Component {
    render () {
       if (this.props.action == "Clocked in") {
         return (

         )
       }

        if (this.props.action == "Clocked out") {
         return (

         )
       }

        if (this.props.action == "Shift started" || "Shift ended") {
         return (

         )
       }

        else {
           return null
       }
    }
}
<commit_msg>Comment out Exceptions<commit_after>/*
 * TimeCard View
 * Copyright ©2015 Thomas Nelson, Jacob Nichols, David Opp, Todd Brochu,
Andrew McGown, Sasha Fahrenkopf, Cameron B. White.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE text file in the root directory of this source tree.
 */
import React, { PropTypes } from "react"
import { Link } from "react-router"
import moment from "moment"
import _ from "lodash"
import FluxComponent from 'flummox/component';
import flux from "../../flux/flux"
import DayOverviewCalendar from '../DayOverviewCalendar/DayOverviewCalendar'
import Page from '../Page/Page'

export default class DayOverview extends React.Component {
  render() {
    return (
      <FluxComponent
        connectToStores={['kronos']}
        stateGetter={([kronos]) => {
          const { params } = this.props
          const date = moment(params.date, 'YYYY-MM-DD')
          const day = kronos.getDay(date)
          const inPunches = kronos.getInPunchesForDate(date)
          const outPunches = kronos.getOutPunchesForDate(date)
          const exceptions = kronos.getExceptionsForDate(date)
          return {
            day,
            inPunches,
            outPunches,
            exceptions,
          }
        }}
      >
        <Overview {...this.props} />
      </FluxComponent>
    )
  }
}

class Overview extends React.Component {
  render() {
    // XXX Hack! Need to pull from API in a better way
    let lastKronosTimeZone = ""

    const { params, day, inPunches, outPunches, exceptions } = this.props
    const inPunchesChain = _.chain(inPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "InPunch",
          })
        })
    const outPunchesChain = _.chain(outPunches)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "OutPunch",
          })
        })
	const ExceptionsChain = _.chain(exceptions)
        .map(each => {
          // XXX Hack! Need to pull from API in a better way
          //lastKronosTimeZone = eachPunch.KronosTimeZone
          return _.assign(each, {
            type: "Exception",
          })
        })
    /*
    const shiftsChain = _.chain(Schedule)
      .get('ScheduleItems.ScheduleShift', [])
      .filter({StartDate: moment(params.date).format("M/DD/YYYY")})
      .pluck('ShiftSegments.ShiftSegment')
      .compact()
      .map(eachShift => {
        const { StartDate, EndDate, StartTime, EndTime} = eachShift
        return [
          {
            time: kronosMoment(StartDate, StartTime, lastKronosTimeZone),
            type: 'scheduledIn'
          },{
            time: kronosMoment(EndDate, EndTime, lastKronosTimeZone),
            type: 'scheduledOut'
          }
        ]
      })
      .flatten()
    */
    /*const execp = ExceptionsChain
		.map(punch => <Entry {...punch} />)
       .value()*/
    const punches = inPunchesChain
       .concat(outPunchesChain.value())
       //.concat(shiftsChain.value())
       .sortBy('time')
       .map(punch => <Entry {...punch} />)
       .value()

    const date = moment(params.date)
    const year = date.format("YYYY")
    const month = date.format("MM")

    const dayHeaders = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]

    return (
      <Page>
        <DayHeader date={date}/>

            { punches.length > 0 ?

{punches}

 :

No punches today

}

              <DayOverviewCalendar year={year} month={month-1} headers={dayHeaders} />

              <FluxComponent connectToStores={{
                  kronos: store => ({
                    day: store.getDay(moment(this.props.params.date, 'YYYY-MM-DD'))
                  })
              }}>
                <DayStats />
              </FluxComponent>

      </Page>
    )
  }
}

class DayHeader extends React.Component {
  render() {
    const displayDate = this.props.date.format("MMMM DD")
    return (

          <Link to="day" params={{date: this.props.date.clone().subtract(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-left subtle-btn">

                «

          </Link>

{displayDate}

          <Link to="day" params={{date: this.props.date.clone().add(1, "days").format("YYYY-MM-DD")}}
                type="button" className="pull-right subtle-btn">

                »

          </Link>

 {/*For space*/}

    )
  }
}

class DayStats extends React.Component {
  render() {
    const { day } = this.props
    const total = day ? day.total : ''
    return (

Total Hours Worked: {total}

    )
  }
}

class Entry extends React.Component {
  render() {
    const panelClassDefault = "panel time-entry day"
    const glyphClassDefault = "day-icon"

    const settings = {
      InPunch: {
        action: "Clocked in",
        panelClass: panelClassDefault + " " + "time-in",
        glyphClass: "icon-truck"
      },
      OutPunch: {
        action: "Clocked out",
        panelClass: panelClassDefault + " " + "time-out",
        glyphClass: "icon-truck"
      },
      scheduledIn: {
        action: "Shift started",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      },
      scheduledOut: {
        action: "Shift ended",
        panelClass: panelClassDefault + " " + "shift-info",
        glyphClass: "icon-clock"
      },
	  Exception: {
        action: "Exception",
        panelClass: panelClassDefault + " " + "time-in",
        glyphClass: "icon-truck"
      },
    }

    const {action, panelClass, glyphClass} = settings[this.props.type]
	console.log(this.props)
	if(this.props.type == "Exception") {
		console.log(this.props.typeName)
		const expection = this.props.typeName
		return (

			  <ActionIcon action = {action}/>
			  {expection}

		)
	} else {
		const time = moment(this.props.time).format('h:mma')

		const code = this.props.LaborName

		return (

			  <ActionIcon action = {action}/>
			  {action}
			  {time}
			  {code}

		)
	}
  }
}

class ActionIcon extends React.Component {
    render () {
       if (this.props.action == "Clocked in") {
         return (

         )
       }

        if (this.props.action == "Clocked out") {
         return (

         )
       }

        if (this.props.action == "Shift started" || "Shift ended") {
         return (

         )
       }

        else {
           return null
       }
    }
}
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module('porttare.directives')
    .directive('backButton', backButton);

  function backButton() {
    var directive = {
      restrict: 'EA',
      templateUrl: 'templates/directives/back-button/back-button.html',
      controller: BackButtonController,
      controllerAs: 'bbVm',
      bindToController: true
    };

    return directive;
  }

  function BackButtonController($window) {
    var bbVm = this;
    bbVm.goBack = goBack;

    function goBack() {
      $window.history.back();
    }
  }
})();
<commit_msg>anguiular<commit_after>(function () {
  'use strict';

  angular
    .module('porttare.directives')
    .directive('backButton', backButton);

  function backButton() {
    var directive = {
      restrict: 'EA',
      templateUrl: 'templates/directives/back-button/back-button.html',
      controller: ['$window', BackButtonController],
      controllerAs: 'bbVm',
      bindToController: true
    };

    return directive;
  }

  function BackButtonController($window) {
    var bbVm = this;
    bbVm.goBack = goBack;

    function goBack() {
      $window.history.back();
    }
  }
})();
<|endoftext|>