<commit_before>/***
Adds the app switcher to a TiddlySpace app.

Makes use of tw.Stylesheet
Triple licensed under the BSD, MIT and GPL licenses:
  http://www.opensource.org/licenses/bsd-license.php
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
***/
(function() {

// Add or replace a style sheet
// css argument is a string of CSS rule sets
// options.id is an optional name identifying the style sheet
// options.doc is an optional document reference
// N.B.: Uses DOM methods instead of jQuery to ensure cross-browser comaptibility.
var twStylesheet = function(css, options) {
	options = options || {};
	var id = options.id || "backstageStyleSheet";
	var doc = options.doc || document;
	var el = doc.getElementById(id);
	if(doc.createStyleSheet) { // IE-specific handling
		if(el) {
			el.parentNode.removeChild(el);
		}
		doc.getElementsByTagName("head")[0].insertAdjacentHTML("beforeEnd",
			' '); // fails without
	} else { // modern browsers
		if(el) {
			el.replaceChild(doc.createTextNode(css), el.firstChild);
		} else {
			el = doc.createElement("style");
			el.type = "text/css";
			el.id = id;
			el.appendChild(doc.createTextNode(css));
			doc.getElementsByTagName("head")[0].appendChild(el);
		}
	}
};

// detect background-size support
// in <IE9 need to fallback to msfilter property
function hasBgSizing() {
	var supported,
		elem = document.createElement('div');

	document.body.appendChild(elem);
	elem.style.cssText = "background-size: cover;";
	supported = (elem.style.backgroundSize === undefined || elem.style.backgroundSize === null) ? false : true;
	// clean up
	elem.parentNode.removeChild(elem);
	return supported;
}
var backgroundSizeSupported = hasBgSizing();

// ms filters as fix for not supporting background-size property
var msfilter_in = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/bags/tiddlyspace/tiddlers/privateAndPublicIcon', sizingMethod='scale')",
	msfilter_out = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/bags/tiddlyspace/tiddlers/publicIcon', sizingMethod='scale')";

var stylesheet = ["iframe {",
"	height: 256px; /* need to dynamically resize this so all opts fit */",
"	z-index: 1000;",
"	position: relative;",
"}",
"",
"#app-picker {",
"	cursor: pointer;",
"	position: absolute;",
"	right: 24px;",
"	top: 0px;",
"	width: 24px;",
"	height: 24px;",
"	background-size: 24px 24px;",
"	text-indent: -999px;",
"	overflow: hidden;",
"	z-index: 2000;",
"	border: none;",
"	opacity: 0.5;",
"}",
"",
"#app-picker:hover {",
"	background-color: none !important;",
"	opacity: 1;",
"}",
"",
".bs-popup {",
"	width: 100%;",
"	position: absolute;",
"	z-index: 1000;",
"	right: 10px;",
"	top: 36px;",
"}",
"",
".bubble .description {",
"	margin-left: 70px;",
"	margin-top: 2px;",
"}",
"",
".bubble {",
"	float: right;",
"	font-size: 0.9em;",
"	font-family: Georgia;",
"	position: relative;",
"	width: 300px;",
"	margin: 0px auto 0px auto;",
"	margin: top right bottom left;",
"	border: solid 1px rgb(200, 200, 200);",
"	border-radius: 4px;",
"	-webkit-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	-moz-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	-o-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	-ms-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	background-color: #F0F4F8;",
"}",
"",
".ts-logout {",
"	display: none;",
"}",
".ts-loggedin .ts-logout {",
"	display: block;",
"}",
".arrow {",
"	border-width: 0 10px 10px;",
"	border-style: dashed dashed solid;",
"	width: 0;",
"	height: 0;",
"	border-color: transparent;",
"	display: inline-block;",
"	position: absolute;",
"	top: -10px;",
"	right: 16px;",
"	border-bottom-color: #fff;",
"}",
".bubble div.whitearrow {",
"	top: -11px;",
"	border-bottom-color: rgba(0,0,0,0.25);",
"}"
].join("\n");

function addEventListener(node, event, handler, bubble) {
	if (node.addEventListener){
		node.addEventListener(event, handler, bubble);
	} else if (node.attachEvent){
		event = event == "click" ? "onclick" : event;
		event = event == "load" ? "onload" : event;
		node.attachEvent(event, handler);
	}
}

var loadEvent = function() {
	var link = document.createElement("a");
	link.setAttribute("id", "app-picker");
	link.setAttribute("class", "app-picker");
	link.appendChild(document.createTextNode("tiddlyspace"));

        // Quite a hack. GUEST does not have a csrf token.
        if (/csrf_token=\d+:\w+:\w+/.test(document.cookie)) {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/privateAndPublicIcon)';
			} else {
				link.style.filter = msfilter_in;
			}
        } else {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/publicIcon)';
			} else {
				link.style.filter = msfilter_out;
			}
			stylesheet = stylesheet.replace('height: 180px;', 'height: 156px;');
        }

	var body = document.getElementsByTagName("BODY")[0];
	body.insertBefore(link, body.firstChild);
	var html = [
	'
',
		'',
		'

',
		'

',
	'
'].join("");
	var bubble = document.createElement("div");
	bubble.setAttribute("id", "bs-popup");
	bubble.style.cssText = "visibility:hidden;";
	bubble.className = "bs-popup";
	bubble.innerHTML = html;
	body.insertBefore(bubble, link);

	twStylesheet(stylesheet);

	var bubbleFadeInterval;
	function fade(el, fadeIn) {
		var opacity = fadeIn ? 0 : 1;
		if(bubbleFadeInterval) {
			clearInterval(bubbleFadeInterval);
		}
		bubbleFadeInterval = setInterval(function() {
			// TODO: IE does not support opacity
			el.style.cssText = "opacity:" + opacity;
			opacity = fadeIn ? opacity + 0.1 : opacity - 0.1;
			if(opacity < 0 || opacity > 1) {
				clearInterval(bubbleFadeInterval);
				el.style.cssText = fadeIn ? "" : "visibility:hidden;";
			}
		}, 25);
	}

	addEventListener(link, "mousedown", function(ev) {
		ev.preventDefault();
	}, false);

	var bubbleOpen = false;
	var toggleBubble = function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
		if(bubbleOpen) {
			fade(bubble, false);
		} else {
			fade(bubble, true);
		}
		bubbleOpen = !bubbleOpen;
	};

	addEventListener(link, "click", toggleBubble);

	addEventListener(window.document.body, "click",
		function(ev) {
			var targ,
			ev = ev || window.event;

			if (ev.target) targ = ev.target;
			else if (ev.srcElement) targ = ev.srcElement;
			if(targ == link) {
				return;
			}
			if(bubbleOpen) {
				toggleBubble(ev);
			}
		}, true);

	addEventListener(bubble, "click", function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
	});
};

if(window.top == window) { // only add the backstage when NOT in an iframe (top window)
	addEventListener(window, "load", loadEvent);
}

})();
<commit_msg>Add title attribute to Roundel dropdown icon.<commit_after>/***
Adds the app switcher to a TiddlySpace app.

Makes use of tw.Stylesheet
Triple licensed under the BSD, MIT and GPL licenses:
  http://www.opensource.org/licenses/bsd-license.php
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html
***/
(function() {

// Add or replace a style sheet
// css argument is a string of CSS rule sets
// options.id is an optional name identifying the style sheet
// options.doc is an optional document reference
// N.B.: Uses DOM methods instead of jQuery to ensure cross-browser comaptibility.
var twStylesheet = function(css, options) {
	options = options || {};
	var id = options.id || "backstageStyleSheet";
	var doc = options.doc || document;
	var el = doc.getElementById(id);
	if(doc.createStyleSheet) { // IE-specific handling
		if(el) {
			el.parentNode.removeChild(el);
		}
		doc.getElementsByTagName("head")[0].insertAdjacentHTML("beforeEnd",
			' '); // fails without
	} else { // modern browsers
		if(el) {
			el.replaceChild(doc.createTextNode(css), el.firstChild);
		} else {
			el = doc.createElement("style");
			el.type = "text/css";
			el.id = id;
			el.appendChild(doc.createTextNode(css));
			doc.getElementsByTagName("head")[0].appendChild(el);
		}
	}
};

// detect background-size support
// in <IE9 need to fallback to msfilter property
function hasBgSizing() {
	var supported,
		elem = document.createElement('div');

	document.body.appendChild(elem);
	elem.style.cssText = "background-size: cover;";
	supported = (elem.style.backgroundSize === undefined || elem.style.backgroundSize === null) ? false : true;
	// clean up
	elem.parentNode.removeChild(elem);
	return supported;
}
var backgroundSizeSupported = hasBgSizing();

// ms filters as fix for not supporting background-size property
var msfilter_in = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/bags/tiddlyspace/tiddlers/privateAndPublicIcon', sizingMethod='scale')",
	msfilter_out = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/bags/tiddlyspace/tiddlers/publicIcon', sizingMethod='scale')";

var stylesheet = ["iframe {",
"	height: 256px; /* need to dynamically resize this so all opts fit */",
"	z-index: 1000;",
"	position: relative;",
"}",
"",
"#app-picker {",
"	cursor: pointer;",
"	position: absolute;",
"	right: 24px;",
"	top: 0px;",
"	width: 24px;",
"	height: 24px;",
"	background-size: 24px 24px;",
"	text-indent: -999px;",
"	overflow: hidden;",
"	z-index: 2000;",
"	border: none;",
"	opacity: 0.5;",
"}",
"",
"#app-picker:hover {",
"	background-color: none !important;",
"	opacity: 1;",
"}",
"",
".bs-popup {",
"	width: 100%;",
"	position: absolute;",
"	z-index: 1000;",
"	right: 10px;",
"	top: 36px;",
"}",
"",
".bubble .description {",
"	margin-left: 70px;",
"	margin-top: 2px;",
"}",
"",
".bubble {",
"	float: right;",
"	font-size: 0.9em;",
"	font-family: Georgia;",
"	position: relative;",
"	width: 300px;",
"	margin: 0px auto 0px auto;",
"	margin: top right bottom left;",
"	border: solid 1px rgb(200, 200, 200);",
"	border-radius: 4px;",
"	-webkit-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	-moz-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	-o-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	-ms-box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	box-shadow: 0px 0px 4px rgba(0,0,0,.2);",
"	background-color: #F0F4F8;",
"}",
"",
".ts-logout {",
"	display: none;",
"}",
".ts-loggedin .ts-logout {",
"	display: block;",
"}",
".arrow {",
"	border-width: 0 10px 10px;",
"	border-style: dashed dashed solid;",
"	width: 0;",
"	height: 0;",
"	border-color: transparent;",
"	display: inline-block;",
"	position: absolute;",
"	top: -10px;",
"	right: 16px;",
"	border-bottom-color: #fff;",
"}",
".bubble div.whitearrow {",
"	top: -11px;",
"	border-bottom-color: rgba(0,0,0,0.25);",
"}"
].join("\n");

function addEventListener(node, event, handler, bubble) {
	if (node.addEventListener){
		node.addEventListener(event, handler, bubble);
	} else if (node.attachEvent){
		event = event == "click" ? "onclick" : event;
		event = event == "load" ? "onload" : event;
		node.attachEvent(event, handler);
	}
}

var loadEvent = function() {
	var link = document.createElement("a");
	link.setAttribute("id", "app-picker");
	link.setAttribute("class", "app-picker");
	link.setAttribute("title", "Click to navigate around tiddlyspace");
	link.appendChild(document.createTextNode("tiddlyspace"));

        // Quite a hack. GUEST does not have a csrf token.
        if (/csrf_token=\d+:\w+:\w+/.test(document.cookie)) {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/privateAndPublicIcon)';
			} else {
				link.style.filter = msfilter_in;
			}
        } else {
			if( backgroundSizeSupported ) {
				link.style.backgroundImage = 'url(/bags/tiddlyspace/tiddlers/publicIcon)';
			} else {
				link.style.filter = msfilter_out;
			}
			stylesheet = stylesheet.replace('height: 180px;', 'height: 156px;');
        }

	var body = document.getElementsByTagName("BODY")[0];
	body.insertBefore(link, body.firstChild);
	var html = [
	'
',
		'',
		'

',
		'

',
	'
'].join("");
	var bubble = document.createElement("div");
	bubble.setAttribute("id", "bs-popup");
	bubble.style.cssText = "visibility:hidden;";
	bubble.className = "bs-popup";
	bubble.innerHTML = html;
	body.insertBefore(bubble, link);

	twStylesheet(stylesheet);

	var bubbleFadeInterval;
	function fade(el, fadeIn) {
		var opacity = fadeIn ? 0 : 1;
		if(bubbleFadeInterval) {
			clearInterval(bubbleFadeInterval);
		}
		bubbleFadeInterval = setInterval(function() {
			// TODO: IE does not support opacity
			el.style.cssText = "opacity:" + opacity;
			opacity = fadeIn ? opacity + 0.1 : opacity - 0.1;
			if(opacity < 0 || opacity > 1) {
				clearInterval(bubbleFadeInterval);
				el.style.cssText = fadeIn ? "" : "visibility:hidden;";
			}
		}, 25);
	}

	addEventListener(link, "mousedown", function(ev) {
		ev.preventDefault();
	}, false);

	var bubbleOpen = false;
	var toggleBubble = function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
		if(bubbleOpen) {
			fade(bubble, false);
		} else {
			fade(bubble, true);
		}
		bubbleOpen = !bubbleOpen;
	};

	addEventListener(link, "click", toggleBubble);

	addEventListener(window.document.body, "click",
		function(ev) {
			var targ,
			ev = ev || window.event;

			if (ev.target) targ = ev.target;
			else if (ev.srcElement) targ = ev.srcElement;
			if(targ == link) {
				return;
			}
			if(bubbleOpen) {
				toggleBubble(ev);
			}
		}, true);

	addEventListener(bubble, "click", function(ev) {
		if(ev.stopPropagation) {
			ev.stopPropagation();
		} else {
			ev.cancelBubble = false;
		}
	});
};

if(window.top == window) { // only add the backstage when NOT in an iframe (top window)
	addEventListener(window, "load", loadEvent);
}

})();
<|endoftext|>


<commit_before>var JSTest = window.JSTest || {};

JSTest.outputElement = null;
JSTest.numberOfTests = 0;
JSTest.startTime = new Date().getTime();
JSTest.showExecutionTime = true;
JSTest.totalExecutionTime = 0;

setInterval(function(){JSTest.startTime = new Date().getTime();}, 1);

JSTest.assert = function(goal, test)
{
	var result = "FAILED";

	try
	{
        	JSTest.numberOfTests++;

        	if (test == goal)
        	{
            		result = "SUCCESS";
        	}
	}
	catch (err)
	{
		result = "FAILED";
	}

    JSTest.write(result);
};

JSTest.assertStrict = function(goal, test)
{
    JSTest.assertTrue(goal===test);
};

JSTest.assertTrue = function(test)
{
	JSTest.assert(test, true);
};

JSTest.assertFalse = function(test)
{
	JSTest.assert(test, false);
};

JSTest.assertNull = function(test)
{
	JSTest.assert(test, null);
};

JSTest.assertEqual = function(test1, test2)
{
    JSTest.assert(test1, test2);
};

JSTest.assertStrictEqual = function(test1, test2)
{
    JSTest.assertTrue(test1===test2);
};

JSTest.testPool = function(testArray)
{
    for (var i = 0; i < testArray.length; i++)
    {
        var testObj = testArray[i];

        if (testObj.type.toLowerCase() == "equal")
        {
            JSTest.assertEqual(testObj.goal, testObj.test);
        }
        else if (testObj.type.toLowerCase() == "strictequal")
        {
            JSTest.assertStrictEqual(testObj.goal, testObj.test);
        }
        else if (testObj.type.toLowerCase() == "null")
        {
            JSTest.assertNull(testObj.test);
        }
        else if (testObj.type.toLowerCase() == "false")
        {
            JSTest.assertFalse(testObj.test);
        }
        else if (testObj.type.toLowerCase() == "true")
        {
            JSTest.assertTrue(testObj.test);
        }
        else if (testObj.type.toLowerCase() == "strict")
        {
            JSTest.assertStrict(testObj.goal, testObj.test)
        }
        else if (testObj.type.toLowerCase() == "assert")
        {
            JSTest.assert(testObj.goal, testObj.test);
        }
    }
};

JSTest.write = function(message)
{
    var color = "red";

    if (message == "SUCCESS")
    {
        color = "#00b208";
    }

    var currTime = new Date().getTime();
    var timeDiff = currTime - JSTest.startTime;
    JSTest.totalExecutionTime += timeDiff;

    var html = JSTest.outputElement.innerHTML;
    html += "Test #" + JSTest.numberOfTests + ": ";
    html += "" + message + " ";
    if (JSTest.showExecutionTime)
    {
      html += "(" + timeDiff + " ms)";
    }
    html += "
";
    JSTest.outputElement.innerHTML = html;
};

<commit_msg>Minor mod<commit_after>var JSTest = window.JSTest || {};

JSTest.outputElement = null;
JSTest.numberOfTests = 0;
JSTest.startTime = new Date().getTime();
JSTest.showExecutionTime = true;
JSTest.totalExecutionTime = 0;

setInterval(function(){JSTest.startTime = new Date().getTime();}, 1);

JSTest.assert = function(goal, test)
{
    var result = "FAILED";

    try
    {
       JSTest.numberOfTests++;

       if (test == goal)
       {
          result = "SUCCESS";
       }
    }
    catch (err)
    {
       result = "FAILED";
    }

    JSTest.write(result);
};

JSTest.assertStrict = function(goal, test)
{
    JSTest.assertTrue(goal===test);
};

JSTest.assertTrue = function(test)
{
    JSTest.assert(test, true);
};

JSTest.assertFalse = function(test)
{
    JSTest.assert(test, false);
};

JSTest.assertNull = function(test)
{
    JSTest.assert(test, null);
};

JSTest.assertEqual = function(test1, test2)
{
    JSTest.assert(test1, test2);
};

JSTest.assertStrictEqual = function(test1, test2)
{
    JSTest.assertTrue(test1===test2);
};

JSTest.testPool = function(testArray)
{
    for (var i = 0; i < testArray.length; i++)
    {
        var testObj = testArray[i];

        if (testObj.type.toLowerCase() == "equal")
        {
            JSTest.assertEqual(testObj.goal, testObj.test);
        }
        else if (testObj.type.toLowerCase() == "strictequal")
        {
            JSTest.assertStrictEqual(testObj.goal, testObj.test);
        }
        else if (testObj.type.toLowerCase() == "null")
        {
            JSTest.assertNull(testObj.test);
        }
        else if (testObj.type.toLowerCase() == "false")
        {
            JSTest.assertFalse(testObj.test);
        }
        else if (testObj.type.toLowerCase() == "true")
        {
            JSTest.assertTrue(testObj.test);
        }
        else if (testObj.type.toLowerCase() == "strict")
        {
            JSTest.assertStrict(testObj.goal, testObj.test)
        }
        else if (testObj.type.toLowerCase() == "assert")
        {
            JSTest.assert(testObj.goal, testObj.test);
        }
    }
};

JSTest.write = function(message)
{
    var color = "red";

    if (message == "SUCCESS")
    {
        color = "#00b208";
    }

    var currTime = new Date().getTime();
    var timeDiff = currTime - JSTest.startTime;
    JSTest.totalExecutionTime += timeDiff;

    var html = JSTest.outputElement.innerHTML;
    html += "Test #" + JSTest.numberOfTests + ": ";
    html += "" + message + " ";
    if (JSTest.showExecutionTime)
    {
      html += "(" + timeDiff + " ms)";
    }
    html += "
";
    JSTest.outputElement.innerHTML = html;
};

<|endoftext|>


<commit_before>// Detect language immediately
var cookie_value = document.cookie.match('cookie=.n');
var visited_value = document.cookie.match('visited=1;');

console.log(visited_value);
if (visited_value != "visited=1"){
	console.log("new");
	document.cookie = "visited" + "=" + 1 + "; max-age=" + 60 * 60 * 24 * 365 + "; path=/" + "jdarchive.org";
}

if (cookie_value == "cookie=jn" && window.location.href.indexOf("/en/") != -1)
    window.location = window.location.href.replace('/en/', '/ja/');
else if (cookie_value == "cookie=en" && window.location.href.indexOf("/ja/") != -1)
    window.location = window.location.href.replace('/ja/', '/en/');
else if (cookie_value != "cookie=en" && cookie_value != "cookie=jn") {
    var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;

    if ((userLang == "en-us" || userLang == "en-US") && window.location.pathname == '/ja/home') {
        window.location = window.location.href.replace('/ja/', '/en/');
    }
    else if (userLang == "ja" && window.location.pathname == '/en/home') {
        window.location = window.location.href.replace('/en/', '/ja/');
    }
}

$(document).ready(function () {

    var BrowserDetect = {
        init: function () {

            /**************************************************/

            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {
                string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera",
                versionSearch: "Version"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {		// for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            { 		// for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS: [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };
    BrowserDetect.init();

    if ((BrowserDetect.browser == 'Firefox' && BrowserDetect.version < 12) || (BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 9)) {
        $('#browserModal').modal('show');
        console.log(BrowserDetect.version);
    }

    /***************************************************/
    /*************** HEADER ****************************/
    /***************************************************/

    /*************** USER LOGIN ************************/

    $('#sign-in').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;
    });

    $('#user-modal').bind('authenticated', function () {
        $('#sign-in').hide();
        $('#user-dropdown').show();
        $('#jda-header-me').show();
        if (!_.isUndefined(window.jda)) jda.app.userAuthenticated();
        return false;
    });

    $('#user-modal').bind('close', function () { $("#user-modal-close").trigger('click'); });

    /*************** ACCOUNT SETTINGS ************************/

    $('#account-settings').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;

    });

    /************  BUG REPORT **********************/

    $('.bug-report').click(function (e) { e.stopPropagation(); });

    $('.bug-report').parent().click(function () {
        $('.bug-unsubmitted').show();
        $('.bug-submitted').hide();
    });

    $('.close-bug').click(function () {
        $('.bug-report').parent().trigger('click');
    });

    $('.submit-bug').click(function () {

        var bug = new Backbone.Model({

            url: window.location.href,
            hash: window.location.hash.substr(1),
            description: $('.bug-description').val(),
            email: $('.bug-email').val(),
            browser: BrowserDetect.browser,
            version: BrowserDetect.version,
            os: BrowserDetect.OS,
            login: sessionStorage.getItem('user')

        });

        bug.url = "../bugs/report.php";
        bug.save();
        $('.bug-description').attr('value', '');
        $('.bug-unsubmitted').fadeOut('fast', function () {
            $('.bug-submitted').fadeIn();
        });

    });

    /*************** LANGUAGE TOGGLE ************************/
    $('#jda-language-toggle').find('.btn').click(function () {

        function set_cookie(cookie_name, cookie_value, lifespan_in_days, valid_domain) {
            // http://www.thesitewizard.com/javascripts/cookies.shtml
            var domain_string = valid_domain ? ("; domain=" + valid_domain) : '';
            document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; max-age=" + 60 * 60 * 24 * lifespan_in_days + "; path=/" + domain_string;
        }

        if (!$(this).hasClass('active')) {
            console.log('switching languages');
            $('#jda-language-toggle').find('.btn').removeClass('active');
            $(this).addClass('active');
            console.log($(this).data('language'));
            if ($(this).data('language') == 'en') {
                set_cookie("cookie", "en", "365", "jdarchive.org");
                if (window.location.href.indexOf("/en/") == -1) {
                    window.location.href = window.location.href.replace('/ja/', '/en/');
                }
            }
            else {
                set_cookie("cookie", "jn", "365", "jdarchive.org");
                if (window.location.href.indexOf("/ja/") == -1) {
                    window.location = window.location.href.replace('/en/', '/ja/');
                }
            }
        }

    });

    $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600));

    $(window).resize(function () { $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600)); });

    // Shorthand the application namespace
    //http://documentcloud.github.com/visualsearch/
    VisualSearch = VS.init({
        container: $('.visual_search'),
        query: '',
        callbacks: {

            loaded: function () {

                if ($(location).attr('href').indexOf('home') >= 0) {
                    $('.VS-search-box').css('width', '600px');
					$('.VS-search-box').css('margin-left', 'auto');
					$('.VS-search-box').css('margin-right', 'auto');
                    $('#VS-search input').css('width', '550px');
                } else {
                    $('.VS-search-box').css('width', '500px');
                    $('#VS-search input').css('width', '430px');
                }
                $("#jda-home-search-div, #search-bar").fadeTo('slow', 1);
                $('#VS-search input').attr('placeholder', 'Explore the Archive');

                $('#VS-search input').css('padding-top', '9px');
                $('#VS-search input').focus(function () {
                    //$(this).attr('placeholder', '');
                    $(this).css('width', '3px');
                });

                $('#jda-go-button').click(function () {
                    var query = VisualSearch.searchBox.value();
                    window.location = 'search#q=' + query;
                });
            },

            search: function () {

                var facets = VisualSearch.searchQuery.models;

                var tagQuery = "tag:";
                var textQuery = "";
                //var usernameQuery = "";

                _.each(facets, function (facet) {
                    console.log(facet.get('category'));
                    switch (facet.get('category')) {
                        case 'text':
                            textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
                            textQuery = textQuery.replace(/^#/, '');
                            break;
                        case 'tag':
                            tagQuery = (tagQuery.length > 4) ? tagQuery + ", " + facet.get('value') : tagQuery + facet.get('value');
                            tagQuery = tagQuery.replace(/^#/, '');
                            break;
                            /*
                            case 'user':
                                usernameQuery = facet.get('value');
                                break;
                            */
                    }
                });

                var query = textQuery + (textQuery.length > 0 && tagQuery.length > 4 ? " " : "") + (tagQuery.length > 4 ? tagQuery : "");

                window.location = 'search#q=' + query;

            },

            clearSearch: function () { $('input').val(''); },
            // These are the facets that will be autocompleted in an empty input.
            facetMatches: function (callback) {
                callback([
					//'tag', 'keyword', 'text', 'data:time & place','collection','user'
					'tag', 'text'
                ]);
            },
            // These are the values that match specific categories, autocompleted
            // in a category's input field.  searchTerm can be used to filter the
            // list on the server-side, prior to providing a list to the widget.
            valueMatches: function (facet, searchTerm, callback) {
                switch (facet) {
                    case 'user':
                        callback([]);
                        break;
                    case 'tag':
                        callback([]);
                        break;
                    case 'keyword':
                        callback([]);
                        break;
                    case 'text':
                        callback([]);
                        break;
                    case 'data:time & place':
                        callback([]);
                        break;
                }
            }
        } //callbacks
    });

    $('#jda-go-button').click(function () {
        var e = jQuery.Event("keydown");
        e.which = 13;

        //For whatever reason there are two ways of telling VS to search
        //based on whether the facet has been created yet or not
        if ($(".search_facet_input_container input").length) {
            $(".search_facet_input_container input").trigger(e);
        } else {
            VisualSearch.searchBox.searchEvent(e);
        }

        return false;
    });

});
<commit_msg>testing cookies<commit_after>// Detect language immediately
var cookie_value = document.cookie.match('cookie=.n');
var visited_value = document.cookie.match('visited=1');
var cookies = document.cookie;
console.log(cookies);

console.log(visited_value);
if (visited_value != "visited=1"){
	console.log("new");
	document.cookie = "visited" + "=" + 1 + "; max-age=" + 60 * 60 * 24 * 365 + "; path=/" + "jdarchive.org";
}

if (cookie_value == "cookie=jn" && window.location.href.indexOf("/en/") != -1)
    window.location = window.location.href.replace('/en/', '/ja/');
else if (cookie_value == "cookie=en" && window.location.href.indexOf("/ja/") != -1)
    window.location = window.location.href.replace('/ja/', '/en/');
else if (cookie_value != "cookie=en" && cookie_value != "cookie=jn") {
    var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;

    if ((userLang == "en-us" || userLang == "en-US") && window.location.pathname == '/ja/home') {
        window.location = window.location.href.replace('/ja/', '/en/');
    }
    else if (userLang == "ja" && window.location.pathname == '/en/home') {
        window.location = window.location.href.replace('/en/', '/ja/');
    }
}

$(document).ready(function () {

    var BrowserDetect = {
        init: function () {

            /**************************************************/

            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {
                string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera",
                versionSearch: "Version"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {		// for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            { 		// for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS: [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };
    BrowserDetect.init();

    if ((BrowserDetect.browser == 'Firefox' && BrowserDetect.version < 12) || (BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 9)) {
        $('#browserModal').modal('show');
        console.log(BrowserDetect.version);
    }

    /***************************************************/
    /*************** HEADER ****************************/
    /***************************************************/

    /*************** USER LOGIN ************************/

    $('#sign-in').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;
    });

    $('#user-modal').bind('authenticated', function () {
        $('#sign-in').hide();
        $('#user-dropdown').show();
        $('#jda-header-me').show();
        if (!_.isUndefined(window.jda)) jda.app.userAuthenticated();
        return false;
    });

    $('#user-modal').bind('close', function () { $("#user-modal-close").trigger('click'); });

    /*************** ACCOUNT SETTINGS ************************/

    $('#account-settings').click(function () {
        $('#user-modal-body').empty().append('');
        $('#user-modal').modal('show');
        return false;

    });

    /************  BUG REPORT **********************/

    $('.bug-report').click(function (e) { e.stopPropagation(); });

    $('.bug-report').parent().click(function () {
        $('.bug-unsubmitted').show();
        $('.bug-submitted').hide();
    });

    $('.close-bug').click(function () {
        $('.bug-report').parent().trigger('click');
    });

    $('.submit-bug').click(function () {

        var bug = new Backbone.Model({

            url: window.location.href,
            hash: window.location.hash.substr(1),
            description: $('.bug-description').val(),
            email: $('.bug-email').val(),
            browser: BrowserDetect.browser,
            version: BrowserDetect.version,
            os: BrowserDetect.OS,
            login: sessionStorage.getItem('user')

        });

        bug.url = "../bugs/report.php";
        bug.save();
        $('.bug-description').attr('value', '');
        $('.bug-unsubmitted').fadeOut('fast', function () {
            $('.bug-submitted').fadeIn();
        });

    });

    /*************** LANGUAGE TOGGLE ************************/
    $('#jda-language-toggle').find('.btn').click(function () {

        function set_cookie(cookie_name, cookie_value, lifespan_in_days, valid_domain) {
            // http://www.thesitewizard.com/javascripts/cookies.shtml
            var domain_string = valid_domain ? ("; domain=" + valid_domain) : '';
            document.cookie = cookie_name + "=" + encodeURIComponent(cookie_value) + "; max-age=" + 60 * 60 * 24 * lifespan_in_days + "; path=/" + domain_string;
        }

        if (!$(this).hasClass('active')) {
            console.log('switching languages');
            $('#jda-language-toggle').find('.btn').removeClass('active');
            $(this).addClass('active');
            console.log($(this).data('language'));
            if ($(this).data('language') == 'en') {
                set_cookie("cookie", "en", "365", "jdarchive.org");
                if (window.location.href.indexOf("/en/") == -1) {
                    window.location.href = window.location.href.replace('/ja/', '/en/');
                }
            }
            else {
                set_cookie("cookie", "jn", "365", "jdarchive.org");
                if (window.location.href.indexOf("/ja/") == -1) {
                    window.location = window.location.href.replace('/en/', '/ja/');
                }
            }
        }

    });

    $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600));

    $(window).resize(function () { $('.jda-home-featured-collection').height(Math.max($(window).height() - 50, 600)); });

    // Shorthand the application namespace
    //http://documentcloud.github.com/visualsearch/
    VisualSearch = VS.init({
        container: $('.visual_search'),
        query: '',
        callbacks: {

            loaded: function () {

                if ($(location).attr('href').indexOf('home') >= 0) {
                    $('.VS-search-box').css('width', '600px');
					$('.VS-search-box').css('margin-left', 'auto');
					$('.VS-search-box').css('margin-right', 'auto');
                    $('#VS-search input').css('width', '550px');
                } else {
                    $('.VS-search-box').css('width', '500px');
                    $('#VS-search input').css('width', '430px');
                }
                $("#jda-home-search-div, #search-bar").fadeTo('slow', 1);
                $('#VS-search input').attr('placeholder', 'Explore the Archive');

                $('#VS-search input').css('padding-top', '9px');
                $('#VS-search input').focus(function () {
                    //$(this).attr('placeholder', '');
                    $(this).css('width', '3px');
                });

                $('#jda-go-button').click(function () {
                    var query = VisualSearch.searchBox.value();
                    window.location = 'search#q=' + query;
                });
            },

            search: function () {

                var facets = VisualSearch.searchQuery.models;

                var tagQuery = "tag:";
                var textQuery = "";
                //var usernameQuery = "";

                _.each(facets, function (facet) {
                    console.log(facet.get('category'));
                    switch (facet.get('category')) {
                        case 'text':
                            textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
                            textQuery = textQuery.replace(/^#/, '');
                            break;
                        case 'tag':
                            tagQuery = (tagQuery.length > 4) ? tagQuery + ", " + facet.get('value') : tagQuery + facet.get('value');
                            tagQuery = tagQuery.replace(/^#/, '');
                            break;
                            /*
                            case 'user':
                                usernameQuery = facet.get('value');
                                break;
                            */
                    }
                });

                var query = textQuery + (textQuery.length > 0 && tagQuery.length > 4 ? " " : "") + (tagQuery.length > 4 ? tagQuery : "");

                window.location = 'search#q=' + query;

            },

            clearSearch: function () { $('input').val(''); },
            // These are the facets that will be autocompleted in an empty input.
            facetMatches: function (callback) {
                callback([
					//'tag', 'keyword', 'text', 'data:time & place','collection','user'
					'tag', 'text'
                ]);
            },
            // These are the values that match specific categories, autocompleted
            // in a category's input field.  searchTerm can be used to filter the
            // list on the server-side, prior to providing a list to the widget.
            valueMatches: function (facet, searchTerm, callback) {
                switch (facet) {
                    case 'user':
                        callback([]);
                        break;
                    case 'tag':
                        callback([]);
                        break;
                    case 'keyword':
                        callback([]);
                        break;
                    case 'text':
                        callback([]);
                        break;
                    case 'data:time & place':
                        callback([]);
                        break;
                }
            }
        } //callbacks
    });

    $('#jda-go-button').click(function () {
        var e = jQuery.Event("keydown");
        e.which = 13;

        //For whatever reason there are two ways of telling VS to search
        //based on whether the facet has been created yet or not
        if ($(".search_facet_input_container input").length) {
            $(".search_facet_input_container input").trigger(e);
        } else {
            VisualSearch.searchBox.searchEvent(e);
        }

        return false;
    });

});
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals PDFJS, PDFView */

'use strict';

var PDFHistory = {
  initialized: false,
  initialDestination: null,

  initialize: function pdfHistoryInitialize(fingerprint) {
    if (PDFJS.disableHistory || PDFView.isViewerEmbedded) {
      // The browsing history is only enabled when the viewer is standalone,
      // i.e. not when it is embedded in a web page.
      return;
    }
    this.initialized = true;
    this.reInitialized = false;
    this.allowHashChange = true;
    this.historyUnlocked = true;

    this.previousHash = window.location.hash.substring(1);
    this.currentBookmark = '';
    this.currentPage = 0;
    this.updatePreviousBookmark = false;
    this.previousBookmark = '';
    this.previousPage = 0;
    this.nextHashParam = '';

    this.fingerprint = fingerprint;
    this.currentUid = this.uid = 0;
    this.current = {};

    var state = window.history.state;
    if (this._isStateObjectDefined(state)) {
      // This corresponds to navigating back to the document
      // from another page in the browser history.
      if (state.target.dest) {
        this.initialDestination = state.target.dest;
      } else {
        PDFView.initialBookmark = state.target.hash;
      }
      this.currentUid = state.uid;
      this.uid = state.uid + 1;
      this.current = state.target;
    } else {
      // This corresponds to the loading of a new document.
      if (state && state.fingerprint &&
          this.fingerprint !== state.fingerprint) {
        // Reinitialize the browsing history when a new document
        // is opened in the web viewer.
        this.reInitialized = true;
      }
      window.history.replaceState({ fingerprint: this.fingerprint }, '');
    }

    var self = this;
    window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
      evt.preventDefault();
      evt.stopPropagation();

      if (!self.historyUnlocked) {
        return;
      }
      if (evt.state) {
        // Move back/forward in the history.
        self._goTo(evt.state);
      } else {
        // Handle the user modifying the hash of a loaded document.
        self.previousHash = window.location.hash.substring(1);

        // If the history is empty when the hash changes,
        // update the previous entry in the browser history.
        if (self.uid === 0) {
          var previousParams = (self.previousHash && self.currentBookmark &&
                                self.previousHash !== self.currentBookmark) ?
            { hash: self.currentBookmark, page: self.currentPage } :
            { page: 1 };
          self.historyUnlocked = false;
          self.allowHashChange = false;
          window.history.back();
          self._pushToHistory(previousParams, false, true);
          window.history.forward();
          self.historyUnlocked = true;
        }
        self._pushToHistory({ hash: self.previousHash }, false, true);
        self._updatePreviousBookmark();
      }
    }, false);

    function pdfHistoryBeforeUnload() {
      var previousParams = self._getPreviousParams(null, true);
      if (previousParams) {
        var replacePrevious = (!self.current.dest &&
                               self.current.hash !== self.previousHash);
        self._pushToHistory(previousParams, false, replacePrevious);
        self._updatePreviousBookmark();
      }
      // Remove the event listener when navigating away from the document,
      // since 'beforeunload' prevents Firefox from caching the document.
      window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }
    window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);

    window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
      // If the entire viewer (including the PDF file) is cached in the browser,
      // we need to reattach the 'beforeunload' event listener since
      // the 'DOMContentLoaded' event is not fired on 'pageshow'.
      window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }, false);
  },

  _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
    return (state && state.uid >= 0 &&
            state.fingerprint && this.fingerprint === state.fingerprint &&
            state.target && state.target.hash) ? true : false;
  },

  get isHashChangeUnlocked() {
    if (!this.initialized) {
      return true;
    }
    // If the current hash changes when moving back/forward in the history,
    // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
    // Since the hash generally won't correspond to the exact the position
    // stored in the history's state object, triggering the 'hashchange' event
    // can thus corrupt the browser history.
    //
    // When the hash changes during a 'popstate' event, we *only* prevent the
    // first 'hashchange' event and immediately reset allowHashChange.
    // If it is not reset, the user would not be able to change the hash.

    var temp = this.allowHashChange;
    this.allowHashChange = true;
    return temp;
  },

  _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
    if (this.updatePreviousBookmark &&
        this.currentBookmark && this.currentPage) {
      this.previousBookmark = this.currentBookmark;
      this.previousPage = this.currentPage;
      this.updatePreviousBookmark = false;
    }
  },

  updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
                                                                  pageNum) {
    if (this.initialized) {
      this.currentBookmark = bookmark.substring(1);
      this.currentPage = pageNum | 0;
      this._updatePreviousBookmark();
    }
  },

  updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
    if (this.initialized) {
      this.nextHashParam = param;
    }
  },

  push: function pdfHistoryPush(params, isInitialBookmark) {
    if (!(this.initialized && this.historyUnlocked)) {
      return;
    }
    if (params.dest && !params.hash) {
      params.hash = (this.current.hash && this.current.dest &&
                     this.current.dest === params.dest) ?
        this.current.hash :
        PDFView.getDestinationHash(params.dest).split('#')[1];
    }
    if (params.page) {
      params.page |= 0;
    }
    if (isInitialBookmark) {
      var target = window.history.state.target;
      if (!target) {
        // Invoked when the user specifies an initial bookmark,
        // thus setting PDFView.initialBookmark, when the document is loaded.
        this._pushToHistory(params, false);
        this.previousHash = window.location.hash.substring(1);
      }
      this.updatePreviousBookmark = this.nextHashParam ? false : true;
      if (target) {
        // If the current document is reloaded,
        // avoid creating duplicate entries in the history.
        this._updatePreviousBookmark();
      }
      return;
    }
    if (this.nextHashParam && this.nextHashParam === params.hash) {
      this.nextHashParam = null;
      this.updatePreviousBookmark = true;
      return;
    }

    if (params.hash) {
      if (this.current.hash) {
        if (this.current.hash !== params.hash) {
          this._pushToHistory(params, true);
        } else {
          if (!this.current.page && params.page) {
            this._pushToHistory(params, false, true);
          }
          this.updatePreviousBookmark = true;
        }
      } else {
        this._pushToHistory(params, true);
      }
    } else if (this.current.page && params.page &&
               this.current.page !== params.page) {
      this._pushToHistory(params, true);
    }
  },

  _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
                                                            beforeUnload) {
    if (!(this.currentBookmark && this.currentPage)) {
      return null;
    }
    if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
      if (this.previousBookmark === this.currentBookmark) {
        return null;
      }
    } else if (this.current.page || onlyCheckPage) {
      if (this.previousPage === this.currentPage) {
        return null;
      }
    } else {
      return null;
    }
    var params = { hash: this.currentBookmark, page: this.currentPage };
    if (PDFView.isPresentationMode) {
      params.hash = null;
    }
    return params;
  },

  _stateObj: function pdfHistory_stateObj(params) {
    return { fingerprint: this.fingerprint, uid: this.uid, target: params };
  },

  _pushToHistory: function pdfHistory_pushToHistory(params,
                                                    addPrevious, overwrite) {
    if (!this.initialized) {
      return;
    }
    if (!params.hash && params.page) {
      params.hash = ('page=' + params.page);
    }
    if (addPrevious && !overwrite) {
      var previousParams = this._getPreviousParams();
      if (previousParams) {
        var replacePrevious = (this.current.hash !== this.previousHash);
        this._pushToHistory(previousParams, false, replacePrevious);
      }
    }
    if (overwrite || this.uid === 0) {
      window.history.replaceState(this._stateObj(params), '');
    } else {
      window.history.pushState(this._stateObj(params), '');
    }
    this.currentUid = this.uid++;
    this.current = params;
    this.updatePreviousBookmark = true;
  },

  _goTo: function pdfHistory_goTo(state) {
    if (!(this.initialized && this.historyUnlocked &&
          this._isStateObjectDefined(state))) {
      return;
    }
    if (!this.reInitialized && state.uid < this.currentUid) {
      var previousParams = this._getPreviousParams(true);
      if (previousParams) {
        this._pushToHistory(this.current, false);
        this._pushToHistory(previousParams, false);
        this.currentUid = state.uid;
        window.history.back();
        return;
      }
    }
    this.historyUnlocked = false;

    if (state.target.dest) {
      PDFView.navigateTo(state.target.dest);
    } else {
      PDFView.setHash(state.target.hash);
    }
    this.currentUid = state.uid;
    if (state.uid > this.uid) {
      this.uid = state.uid;
    }
    this.current = state.target;
    this.updatePreviousBookmark = true;

    var currentHash = window.location.hash.substring(1);
    if (this.previousHash !== currentHash) {
      this.allowHashChange = false;
    }
    this.previousHash = currentHash;

    this.historyUnlocked = true;
  },

  back: function pdfHistoryBack() {
    this.go(-1);
  },

  forward: function pdfHistoryForward() {
    this.go(1);
  },

  go: function pdfHistoryGo(direction) {
    if (this.initialized && this.historyUnlocked) {
      var state = window.history.state;
      if (direction === -1 && state && state.uid > 0) {
        window.history.back();
      } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
        window.history.forward();
      }
    }
  }
};
<commit_msg>Set URL in history.replaceState/pushState<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals PDFJS, PDFView */

'use strict';

var PDFHistory = {
  initialized: false,
  initialDestination: null,

  initialize: function pdfHistoryInitialize(fingerprint) {
    if (PDFJS.disableHistory || PDFView.isViewerEmbedded) {
      // The browsing history is only enabled when the viewer is standalone,
      // i.e. not when it is embedded in a web page.
      return;
    }
    this.initialized = true;
    this.reInitialized = false;
    this.allowHashChange = true;
    this.historyUnlocked = true;

    this.previousHash = window.location.hash.substring(1);
    this.currentBookmark = '';
    this.currentPage = 0;
    this.updatePreviousBookmark = false;
    this.previousBookmark = '';
    this.previousPage = 0;
    this.nextHashParam = '';

    this.fingerprint = fingerprint;
    this.currentUid = this.uid = 0;
    this.current = {};

    var state = window.history.state;
    if (this._isStateObjectDefined(state)) {
      // This corresponds to navigating back to the document
      // from another page in the browser history.
      if (state.target.dest) {
        this.initialDestination = state.target.dest;
      } else {
        PDFView.initialBookmark = state.target.hash;
      }
      this.currentUid = state.uid;
      this.uid = state.uid + 1;
      this.current = state.target;
    } else {
      // This corresponds to the loading of a new document.
      if (state && state.fingerprint &&
          this.fingerprint !== state.fingerprint) {
        // Reinitialize the browsing history when a new document
        // is opened in the web viewer.
        this.reInitialized = true;
      }
      window.history.replaceState({ fingerprint: this.fingerprint }, '',
          document.URL);
    }

    var self = this;
    window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
      evt.preventDefault();
      evt.stopPropagation();

      if (!self.historyUnlocked) {
        return;
      }
      if (evt.state) {
        // Move back/forward in the history.
        self._goTo(evt.state);
      } else {
        // Handle the user modifying the hash of a loaded document.
        self.previousHash = window.location.hash.substring(1);

        // If the history is empty when the hash changes,
        // update the previous entry in the browser history.
        if (self.uid === 0) {
          var previousParams = (self.previousHash && self.currentBookmark &&
                                self.previousHash !== self.currentBookmark) ?
            { hash: self.currentBookmark, page: self.currentPage } :
            { page: 1 };
          self.historyUnlocked = false;
          self.allowHashChange = false;
          window.history.back();
          self._pushToHistory(previousParams, false, true);
          window.history.forward();
          self.historyUnlocked = true;
        }
        self._pushToHistory({ hash: self.previousHash }, false, true);
        self._updatePreviousBookmark();
      }
    }, false);

    function pdfHistoryBeforeUnload() {
      var previousParams = self._getPreviousParams(null, true);
      if (previousParams) {
        var replacePrevious = (!self.current.dest &&
                               self.current.hash !== self.previousHash);
        self._pushToHistory(previousParams, false, replacePrevious);
        self._updatePreviousBookmark();
      }
      // Remove the event listener when navigating away from the document,
      // since 'beforeunload' prevents Firefox from caching the document.
      window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }
    window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);

    window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
      // If the entire viewer (including the PDF file) is cached in the browser,
      // we need to reattach the 'beforeunload' event listener since
      // the 'DOMContentLoaded' event is not fired on 'pageshow'.
      window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }, false);
  },

  _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
    return (state && state.uid >= 0 &&
            state.fingerprint && this.fingerprint === state.fingerprint &&
            state.target && state.target.hash) ? true : false;
  },

  get isHashChangeUnlocked() {
    if (!this.initialized) {
      return true;
    }
    // If the current hash changes when moving back/forward in the history,
    // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
    // Since the hash generally won't correspond to the exact the position
    // stored in the history's state object, triggering the 'hashchange' event
    // can thus corrupt the browser history.
    //
    // When the hash changes during a 'popstate' event, we *only* prevent the
    // first 'hashchange' event and immediately reset allowHashChange.
    // If it is not reset, the user would not be able to change the hash.

    var temp = this.allowHashChange;
    this.allowHashChange = true;
    return temp;
  },

  _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
    if (this.updatePreviousBookmark &&
        this.currentBookmark && this.currentPage) {
      this.previousBookmark = this.currentBookmark;
      this.previousPage = this.currentPage;
      this.updatePreviousBookmark = false;
    }
  },

  updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
                                                                  pageNum) {
    if (this.initialized) {
      this.currentBookmark = bookmark.substring(1);
      this.currentPage = pageNum | 0;
      this._updatePreviousBookmark();
    }
  },

  updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
    if (this.initialized) {
      this.nextHashParam = param;
    }
  },

  push: function pdfHistoryPush(params, isInitialBookmark) {
    if (!(this.initialized && this.historyUnlocked)) {
      return;
    }
    if (params.dest && !params.hash) {
      params.hash = (this.current.hash && this.current.dest &&
                     this.current.dest === params.dest) ?
        this.current.hash :
        PDFView.getDestinationHash(params.dest).split('#')[1];
    }
    if (params.page) {
      params.page |= 0;
    }
    if (isInitialBookmark) {
      var target = window.history.state.target;
      if (!target) {
        // Invoked when the user specifies an initial bookmark,
        // thus setting PDFView.initialBookmark, when the document is loaded.
        this._pushToHistory(params, false);
        this.previousHash = window.location.hash.substring(1);
      }
      this.updatePreviousBookmark = this.nextHashParam ? false : true;
      if (target) {
        // If the current document is reloaded,
        // avoid creating duplicate entries in the history.
        this._updatePreviousBookmark();
      }
      return;
    }
    if (this.nextHashParam && this.nextHashParam === params.hash) {
      this.nextHashParam = null;
      this.updatePreviousBookmark = true;
      return;
    }

    if (params.hash) {
      if (this.current.hash) {
        if (this.current.hash !== params.hash) {
          this._pushToHistory(params, true);
        } else {
          if (!this.current.page && params.page) {
            this._pushToHistory(params, false, true);
          }
          this.updatePreviousBookmark = true;
        }
      } else {
        this._pushToHistory(params, true);
      }
    } else if (this.current.page && params.page &&
               this.current.page !== params.page) {
      this._pushToHistory(params, true);
    }
  },

  _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
                                                            beforeUnload) {
    if (!(this.currentBookmark && this.currentPage)) {
      return null;
    }
    if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
      if (this.previousBookmark === this.currentBookmark) {
        return null;
      }
    } else if (this.current.page || onlyCheckPage) {
      if (this.previousPage === this.currentPage) {
        return null;
      }
    } else {
      return null;
    }
    var params = { hash: this.currentBookmark, page: this.currentPage };
    if (PDFView.isPresentationMode) {
      params.hash = null;
    }
    return params;
  },

  _stateObj: function pdfHistory_stateObj(params) {
    return { fingerprint: this.fingerprint, uid: this.uid, target: params };
  },

  _pushToHistory: function pdfHistory_pushToHistory(params,
                                                    addPrevious, overwrite) {
    if (!this.initialized) {
      return;
    }
    if (!params.hash && params.page) {
      params.hash = ('page=' + params.page);
    }
    if (addPrevious && !overwrite) {
      var previousParams = this._getPreviousParams();
      if (previousParams) {
        var replacePrevious = (this.current.hash !== this.previousHash);
        this._pushToHistory(previousParams, false, replacePrevious);
      }
    }
    if (overwrite || this.uid === 0) {
      window.history.replaceState(this._stateObj(params), '', document.URL);
    } else {
      window.history.pushState(this._stateObj(params), '', document.URL);
    }
    this.currentUid = this.uid++;
    this.current = params;
    this.updatePreviousBookmark = true;
  },

  _goTo: function pdfHistory_goTo(state) {
    if (!(this.initialized && this.historyUnlocked &&
          this._isStateObjectDefined(state))) {
      return;
    }
    if (!this.reInitialized && state.uid < this.currentUid) {
      var previousParams = this._getPreviousParams(true);
      if (previousParams) {
        this._pushToHistory(this.current, false);
        this._pushToHistory(previousParams, false);
        this.currentUid = state.uid;
        window.history.back();
        return;
      }
    }
    this.historyUnlocked = false;

    if (state.target.dest) {
      PDFView.navigateTo(state.target.dest);
    } else {
      PDFView.setHash(state.target.hash);
    }
    this.currentUid = state.uid;
    if (state.uid > this.uid) {
      this.uid = state.uid;
    }
    this.current = state.target;
    this.updatePreviousBookmark = true;

    var currentHash = window.location.hash.substring(1);
    if (this.previousHash !== currentHash) {
      this.allowHashChange = false;
    }
    this.previousHash = currentHash;

    this.historyUnlocked = true;
  },

  back: function pdfHistoryBack() {
    this.go(-1);
  },

  forward: function pdfHistoryForward() {
    this.go(1);
  },

  go: function pdfHistoryGo(direction) {
    if (this.initialized && this.historyUnlocked) {
      var state = window.history.state;
      if (direction === -1 && state && state.uid > 0) {
        window.history.back();
      } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
        window.history.forward();
      }
    }
  }
};
<|endoftext|>


<commit_before>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var TransferInManager = require('./transfer-in-doc-manager');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');

var TransferInDoc = BateeqModels.inventory.TransferInDoc;
var TransferInItem = BateeqModels.inventory.TransferInItem;

const moduleId = "EFR-TB/BBP";

module.exports = class PusatTerimaBarangBaruManager extends TransferInManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.TransferInDoc);
        this.spkDocCollection = this.db.use(map.merchandiser.SPKDoc);

        var StorageManager = require('../master/storage-manager');
        this.storageManager = new StorageManager(db, user);

        var ItemManager = require('../master/item-manager');
        this.itemManager = new ItemManager(db, user);

        var InventoryManager = require('./inventory-manager');
        this.inventoryManager = new InventoryManager(db, user);

        var TransferInDocManager = require('./transfer-in-doc-manager');
        this.transferInDocManager = new TransferInDocManager(db, user);

        var ModuleManager = require('../master/module-manager');
        this.moduleManager = new ModuleManager(db, user);

        var SPKManager = require('../merchandiser/efr-pk-manager');
        this.spkManager = new SPKManager(db, user);

        var ExpeditionManager = require('./efr-kb-exp-manager');
        this.expeditionManager = new ExpeditionManager(db, user);
    }

    readPendingSPK(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false,
                isDraft: false
            }, keywordFilter = {};

            var regex = new RegExp("EFR\-PK/\PBJ|EFR\-PK/\PBR", "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                },
                // 'expeditionDocumentId': { "$ne": {} }
            };
            var destination;
            if (Object.getOwnPropertyNames(paging.filter).length != 0) {
                destination =
                    {
                        "destination.code":
                        {
                            $in: paging.filter
                        }
                    }
            }

            var isReceived = {
                isReceived: false
            };

            let isDistributed = {
                isDistributed: true
            };

            let isCentral = {
                "destination.isCentral": true
            };

            if (paging.keyword) {
                var regex = new RegExp(paging.keyword, "i");

                var filterPackingList = {
                    'packingList': {
                        '$regex': regex
                    }
                };
                keywordFilter = {
                    '$or': [filterPackingList]
                };
            }

            var query = {
                $and: [
                    deleted,
                    filterCode,
                    isReceived,
                    isDistributed,
                    isCentral,
                    destination,
                    keywordFilter
                ]
            }

            this.spkDocCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(spkDocs => {
                    resolve(spkDocs);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            keywordFilter = {
                '$or': [filterCode]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }
    // getById(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getByIdOrDefault(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleOrDefaultByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getSingleByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .single(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    // getSingleOrDefaultByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .singleOrDefault(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    getPendingSPKById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false,
                isReceived: false,
                isDraft: false
            };
            this.spkDocCollection.singleOrDefault(query)
                .then(SPKDoc => {
                    SPKDoc.password = '';
                    SPKDoc._id = undefined;
                    resolve(SPKDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _beforeInsert(validTransferInDoc) {
        return super._beforeInsert(validTransferInDoc)
            .then(validTransferInDoc => {
                validTransferInDoc.code = generateCode(moduleId);
                //kaga transfer in yang qty 0
                var length = validTransferInDoc.items.length;
                for (var i = 0; i < length;) {
                    var item = validTransferInDoc.items[i];
                    if (item.quantity == 0) {
                        validTransferInDoc.items.splice(i, 1);
                    }
                    else {
                        i++;
                    }
                    length = validTransferInDoc.items.length;
                }
                return Promise.resolve(validTransferInDoc);
            }).catch(e => {
                throw e;
            })
    }

    _afterInsert(id) {
        return super._afterInsert(id)
            .then(id => {
                return this.getSingleById(id)
                    .then(transferInDoc => {
                        var reference = transferInDoc.reference;
                        var updateSPK = this.spkManager.updateReceivedByPackingList(reference);
                        var updateExpedition = this.expeditionManager.updateReceivedByPackingList(reference);

                        return Promise.all([updateSPK, updateExpedition])
                            .then(result => {
                                return id;
                            });
                    });
            })
            .catch(e => {
                throw e;
            })
    }

    update(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    validTransferInDoc._deleted = true;
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(transferInDoc) {
        var errors = {};
        return new Promise((resolve, reject) => {
            this.spkManager.getByPL(transferInDoc.reference).
                then(spkDoc => {
                    if (spkDoc) {
                        if (transferInDoc.password != spkDoc.password) {
                            errors["password"] = "invalid password";
                        }
                        if (transferInDoc.reference == "") {
                            errors["reference"] = "reference is required";
                        }
                        if (transferInDoc.items.length <= 0) {
                            errors["items"] = "no item(s) to transfer in";
                        }
                        if (spkDoc.sourceId.toString() != transferInDoc.sourceId.toString()) {
                            errors["sourceId"] = "invalid sourceId";
                        }
                        if (spkDoc.destinationId.toString() != transferInDoc.destinationId.toString()) {
                            errors["destinationId"] = "invalid destinationId";
                        }
                        if (spkDoc.isReceived) {
                            errors["isReceived"] = "this reference already received";
                        }
                        var index = 0;
                        var itemErrors = [];
                        for (var item of transferInDoc.items) {
                            var itemError = {};
                            item.quantity = item.sendQuantity;
                            if (item.sendQuantity < 0)
                                itemError["sendQuantity"] = "items should not less than 0 quantity";
                            else
                                if (item.sendQuantity != spkDoc.items[index].sendQuantity)
                                    if (item.remark == "")
                                        itemError["remark"] = "Masukkan no referensi berita acara";
                            index++;
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }
                        for (var prop in errors) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            reject(new ValidationError('data does not pass validation', errors));
                        }
                    }
                    else {
                        errors["reference"] = "reference not found";
                        var ValidationError = require('module-toolkit').ValidationError;
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    transferInDoc = new TransferInDoc(transferInDoc);
                    transferInDoc.stamp(this.user.username, 'manager');
                    resolve(transferInDoc);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<commit_msg>update for filtering on pending gudang<commit_after>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var TransferInManager = require('./transfer-in-doc-manager');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');

var TransferInDoc = BateeqModels.inventory.TransferInDoc;
var TransferInItem = BateeqModels.inventory.TransferInItem;

const moduleId = "EFR-TB/BBP";

module.exports = class PusatTerimaBarangBaruManager extends TransferInManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.TransferInDoc);
        this.spkDocCollection = this.db.use(map.merchandiser.SPKDoc);

        var StorageManager = require('../master/storage-manager');
        this.storageManager = new StorageManager(db, user);

        var ItemManager = require('../master/item-manager');
        this.itemManager = new ItemManager(db, user);

        var InventoryManager = require('./inventory-manager');
        this.inventoryManager = new InventoryManager(db, user);

        var TransferInDocManager = require('./transfer-in-doc-manager');
        this.transferInDocManager = new TransferInDocManager(db, user);

        var ModuleManager = require('../master/module-manager');
        this.moduleManager = new ModuleManager(db, user);

        var SPKManager = require('../merchandiser/efr-pk-manager');
        this.spkManager = new SPKManager(db, user);

        var ExpeditionManager = require('./efr-kb-exp-manager');
        this.expeditionManager = new ExpeditionManager(db, user);
    }

    readPendingSPK(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false,
                isDraft: false
            }, keywordFilter = {};

            var regex = new RegExp("EFR\-PK/\PBJ|EFR\-PK/\PBR", "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                },
                // 'expeditionDocumentId': { "$ne": {} }
            };
            var destination;
            if (Object.getOwnPropertyNames(paging.filter).length != 0) {
                destination =
                    {
                        "destination.code":
                        {
                            $in: paging.filter
                        }
                    }
            }

            var isReceived = {
                isReceived: false
            };

            let isDistributed = {
                isDistributed: true
            };

            let isCentral = {
                "destination.isCentral": true
            };

            if (paging.keyword) {
                var regex = new RegExp(paging.keyword, "i");

                var filterPackingList = {
                    'packingList': {
                        '$regex': regex
                    }
                };

                var filterReference = {
                    'reference': {
                        '$regex': regex
                    }
                };

                var filterSourceName = {
                    'source.name': {
                        '$regex': regex
                    }
                };

                var filterDestinationName = {
                    'destination.name': {
                        '$regex': regex
                    }
                };

                keywordFilter = {
                    '$or': [filterPackingList, filterReference, filterSourceName, filterDestinationName]
                };
            }

            var query = {
                $and: [
                    deleted,
                    filterCode,
                    isReceived,
                    isDistributed,
                    isCentral,
                    destination,
                    keywordFilter
                ]
            }

            this.spkDocCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(spkDocs => {
                    resolve(spkDocs);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            keywordFilter = {
                '$or': [filterCode]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }
    // getById(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getByIdOrDefault(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleOrDefaultByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getSingleByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .single(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    // getSingleOrDefaultByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .singleOrDefault(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    getPendingSPKById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false,
                isReceived: false,
                isDraft: false
            };
            this.spkDocCollection.singleOrDefault(query)
                .then(SPKDoc => {
                    SPKDoc.password = '';
                    SPKDoc._id = undefined;
                    resolve(SPKDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _beforeInsert(validTransferInDoc) {
        return super._beforeInsert(validTransferInDoc)
            .then(validTransferInDoc => {
                validTransferInDoc.code = generateCode(moduleId);
                //kaga transfer in yang qty 0
                var length = validTransferInDoc.items.length;
                for (var i = 0; i < length;) {
                    var item = validTransferInDoc.items[i];
                    if (item.quantity == 0) {
                        validTransferInDoc.items.splice(i, 1);
                    }
                    else {
                        i++;
                    }
                    length = validTransferInDoc.items.length;
                }
                return Promise.resolve(validTransferInDoc);
            }).catch(e => {
                throw e;
            })
    }

    _afterInsert(id) {
        return super._afterInsert(id)
            .then(id => {
                return this.getSingleById(id)
                    .then(transferInDoc => {
                        var reference = transferInDoc.reference;
                        var updateSPK = this.spkManager.updateReceivedByPackingList(reference);
                        var updateExpedition = this.expeditionManager.updateReceivedByPackingList(reference);

                        return Promise.all([updateSPK, updateExpedition])
                            .then(result => {
                                return id;
                            });
                    });
            })
            .catch(e => {
                throw e;
            })
    }

    update(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    validTransferInDoc._deleted = true;
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(transferInDoc) {
        var errors = {};
        return new Promise((resolve, reject) => {
            this.spkManager.getByPL(transferInDoc.reference).
                then(spkDoc => {
                    if (spkDoc) {
                        if (transferInDoc.password != spkDoc.password) {
                            errors["password"] = "invalid password";
                        }
                        if (transferInDoc.reference == "") {
                            errors["reference"] = "reference is required";
                        }
                        if (transferInDoc.items.length <= 0) {
                            errors["items"] = "no item(s) to transfer in";
                        }
                        if (spkDoc.sourceId.toString() != transferInDoc.sourceId.toString()) {
                            errors["sourceId"] = "invalid sourceId";
                        }
                        if (spkDoc.destinationId.toString() != transferInDoc.destinationId.toString()) {
                            errors["destinationId"] = "invalid destinationId";
                        }
                        if (spkDoc.isReceived) {
                            errors["isReceived"] = "this reference already received";
                        }
                        var index = 0;
                        var itemErrors = [];
                        for (var item of transferInDoc.items) {
                            var itemError = {};
                            item.quantity = item.sendQuantity;
                            if (item.sendQuantity < 0)
                                itemError["sendQuantity"] = "items should not less than 0 quantity";
                            else
                                if (item.sendQuantity != spkDoc.items[index].sendQuantity)
                                    if (item.remark == "")
                                        itemError["remark"] = "Masukkan no referensi berita acara";
                            index++;
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }
                        for (var prop in errors) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            reject(new ValidationError('data does not pass validation', errors));
                        }
                    }
                    else {
                        errors["reference"] = "reference not found";
                        var ValidationError = require('module-toolkit').ValidationError;
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    transferInDoc = new TransferInDoc(transferInDoc);
                    transferInDoc.stamp(this.user.username, 'manager');
                    resolve(transferInDoc);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<|endoftext|>