<commit_before>"use strict";

var expect = require("expect.js"),
    rewire = require("rewire"),
    path = require("path"),
    middler = require("middler"),
    Request = require("../../../lib/server/request/Request.class.js"),
    config = require("../../../lib/shared/config"),
    router = require("../../../lib/server/router.js");

describe("handleRequest", function() {

    var handleRequest,
        routeHandler;

    beforeEach(function() {

        router.set(middler());

        routeHandler = router.get();

        routeHandler.on("error", function(err, req, res) {

            res.end({ status : "error", message : err.message, data : {} });
        });

        handleRequest = require("../../../lib/server/request/handleRequest.js");

    });

    describe("#Services Request", function() {

        function runServiceMock(req, res, next) {
            next();
        }

        function sanitizeDataMock(req, res, next) {
            next();
        }

        var middlewareMock = [
            function a(req, res, next) {
                next();
            },
            function b(req, res,  next) {
                next();
            }
        ];

        it("should handle the request and return without an error if all middleware worked fine", function(done) {

            routeHandler.add("post", "/services/*", middlewareMock);
            routeHandler.add(["post", "put", "delete", "get"], "/services/*", runServiceMock);

            var req = new Request("create", "/services/blogPost", { da : "ta" });

            handleRequest(req, function(err, resReq, resRes) {
                expect(err).to.be(null);
                expect(resReq).to.eql(req);
                expect(resRes).not.to.be("undefined");
                done();
            });
        });

        it("should handle the request and return without an error if all middleware worked fine", function(done) {

            var middlewareMock = [
                function a(req, res, next) {
                    next(new Error("middleware a failed"));
                },
                function b(req, res,  next) {
                    next(null);
                }
            ];

            routeHandler.add(["post", "put", "delete", "get"], "/services/*", middlewareMock);
            routeHandler.add(["post", "put", "delete", "get"], "/services/*", runServiceMock);

            var req = new Request("create", "/services/blogPost", {});

            handleRequest(req, function(err, resReq, res) {
                expect(res.getStatus()).to.be("error");
                expect(res.getErrorMessage()).to.contain("middleware a failed");
                expect(resReq).to.eql(req);
                done();
            });
        });
    });

    describe("#Invalid Requests", function() {

        var handleRequest;

        beforeEach(function() {
            handleRequest = rewire("../../../lib/server/request/handleRequest.js");
        });

        it("should end the request if the type is not allowed", function(done) {

            var req = new Request("create", "/whatever/blogPost", {});

            req.getType = function() {
                return "unsupportedType";
            };

            handleRequest(req, function(err, resReq, resRes) {
                expect(err).to.be.an(Error);
                done();
            });
        });
    });

});<commit_msg>- request-validity-check is now a separate middleware<commit_after>"use strict";

var expect = require("expect.js"),
    rewire = require("rewire"),
    path = require("path"),
    middler = require("middler"),
    Request = require("../../../lib/server/request/Request.class.js"),
    config = require("../../../lib/shared/config"),
    router = require("../../../lib/server/router.js");

describe("handleRequest", function() {

    var handleRequest,
        routeHandler;

    beforeEach(function() {

        router.set(middler());

        routeHandler = router.get();

        routeHandler.on("error", function(err, req, res) {

            res.end({ status : "error", message : err.message, data : {} });
        });

        handleRequest = require("../../../lib/server/request/handleRequest.js");

    });

    describe("#Services Request", function() {

        function runServiceMock(req, res, next) {
            next();
        }

        function sanitizeDataMock(req, res, next) {
            next();
        }

        var middlewareMock = [
            function a(req, res, next) {
                next();
            },
            function b(req, res,  next) {
                next();
            }
        ];

        it("should handle the request and return without an error if all middleware worked fine", function(done) {

            routeHandler.add("post", "/services/*", middlewareMock);
            routeHandler.add(["post", "put", "delete", "get"], "/services/*", runServiceMock);

            var req = new Request("create", "/services/blogPost", { da : "ta" });

            handleRequest(req, function(err, resReq, resRes) {
                expect(err).to.be(null);
                expect(resReq).to.eql(req);
                expect(resRes).not.to.be("undefined");
                done();
            });
        });

        it("should handle the request and return without an error if all middleware worked fine", function(done) {

            var middlewareMock = [
                function a(req, res, next) {
                    next(new Error("middleware a failed"));
                },
                function b(req, res,  next) {
                    next(null);
                }
            ];

            routeHandler.add(["post", "put", "delete", "get"], "/services/*", middlewareMock);
            routeHandler.add(["post", "put", "delete", "get"], "/services/*", runServiceMock);

            var req = new Request("create", "/services/blogPost", {});

            handleRequest(req, function(err, resReq, res) {
                expect(res.getStatus()).to.be("error");
                expect(res.getErrorMessage()).to.contain("middleware a failed");
                expect(resReq).to.eql(req);
                done();
            });
        });
    });

    /*
    //check this test
    //invalid request should not pass thru but happens if they do?
    //default should be an error i guess..
    describe("#Invalid Requests", function() {

        var handleRequest;

        beforeEach(function() {
            handleRequest = rewire("../../../lib/server/request/handleRequest.js");
        });

        it("should end the request if the type is not allowed", function(done) {

            var req = new Request("create", "/whatever/blogPost", {});

            req.getType = function() {
                return "unsupportedType";
            };

            handleRequest(req, function(err, resReq, resRes) {
                console.log(resRes.getResBody());
                expect(err).to.be.an(Error);
                done();
            });
        });
    });
    //*/

});<|endoftext|>


<commit_before>function trace(s)
{
	console.debug(s);
}

function urlencode(str)	//function borrowed from http://www.albionresearch.com/misc/urlencode.php
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < str.length; i++ ) {
		var ch = str.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}

	return encoded;
};

function trim(str)
{
	return str.replace(/^\s*|\s*$/g,"");
}

//Toggles element with name "n" between visible and hidden
//
//If this function makes an element "hidden" the browser
//regards it as non-existent and does not regard it as being
//part of the page-layout
function toggle_element_by_name(n)
{
	var e = document.getElementById(n);
	e.style.display = (e.style.display?'':'none');
}

//Makes element with name "n" invisible in browser
function hide_element_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.display = 'none';
}

//Makes element with name "n" visible in browser
function show_element_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.display = '';
}

//This function, as opposed to the ones above, has the
//browser render the content but show / dont show it
function set_visible_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.visibility="visible";
}

function set_invisible_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.visibility="hidden";
}

function add_div(e, idname, style)
{
	var c=document.createElement('div');

	c.setAttribute('id', idname);
	c.className = style;
	e.appendChild(c);

	return c;
}

function add_span(e)
{
	var c=document.createElement('span');

//	c.setAttribute('id', idname);
//	c.className = style;
	e.appendChild(c);

	return c;
}
function empty_element_by_name(n)
{
	var e=document.getElementById(n);

	while (e.hasChildNodes())
		e.removeChild(e.firstChild);
}

function fill_element_by_name(n,txt)
{
	var e = document.getElementById(n);
	empty_element(e);

	e.innerHTML = txt;
}

function empty_element(e)
{
	while (e.hasChildNodes()) e.removeChild(e.firstChild);
}

//checks if image n has been loaded, waits until it is done otherwise
function image_loaded(n)
{
	var e = document.getElementById(n);

	trace('image_loaded('+n+') w:'+e.width+',h:'+e.height);

	//IE. fixme:untested
	if (!e.complete) {
		return false;
	}

	//Firefox
	if (typeof e.naturalWidth != "undefined" && e.naturalWidth == 0) {
		return false;
	}

	return true;
}

//resizes current window to the same size as image n
function resize_wnd_to_img(n)
{
	var e = document.getElementById(n);
	trace('resize_wnd_to_img('+n+') w:'+e.width+',h:'+e.height);
	var NS = (navigator.appName=="Netscape")?true:false;

	iWidth = (NS)?window.innerWidth:document.body.clientWidth;
	iHeight = (NS)?window.innerHeight:document.body.clientHeight;
	iWidth = e.width - iWidth;
	iHeight = e.height - iHeight;
	window.resizeBy(iWidth, iHeight);
	self.focus();
}

function pause(ms)
{
	var now = new Date();
	var exitTime = now.getTime() + ms;

	while(true) {
		now = new Date();
		if(now.getTime() > exitTime) return;
	}
}

/* sends a ajax poll submit */
function submit_poll(id,opt)
{
	//alert('fixme: submit_poll() add ajax submit. id ' + id + ', opt ' + opt);
	ajax_poll(id,opt);

	hide_element_by_name('poll'+id);
	show_element_by_name('poll_voted'+id);
}

function get_poll_csv(id)
{
	var w = window.open(_ext_core+'csv_poll.php?id='+id+_ext_ref, '_blank');
	w.focus();
}

//Loads image id into holder-div
function loadImage(id, holder)
{
	var e = document.getElementById(holder);
	empty_element(e);

	var i = document.createElement('img');
	i.setAttribute('src', _ext_core+'file.php?id='+id+_ext_ref);
	e.appendChild(i);

	var j = document.getElementById('image_comments_iframe');
	j.setAttribute('src', _ext_core+'html_imgcomments.php?i='+id+_ext_ref);
}

function scroll_up(e, step, offs)
{
	e.scrollTop -= step;
	offs += step;

	if (offs<0) setTimeout(function() {scroll_up(e,step,offs)}, 1);
}

function scroll_down(e, step, offs)
{
	e.scrollTop += step;
	offs -= step;

	if (offs>0) setTimeout(function() {scroll_down(e,step,offs)}, 1);
}

//scroll the content of element name "n" by offset pixels. use negative value of offset to scroll up, positive to scroll down
function scroll_element_content(n,offs)
{
	var e = document.getElementById(n);

	if (offs>0) {
		setTimeout(function() {scroll_down(e,6,offs)}, 1);
	} else {
		setTimeout(function() {scroll_up(e,6,offs)}, 1);
	}
}

//expands size of <input type="text" id="n">
function expand_input(e)
{
	var x=document.getElementById(e);
	if (x.size < 120) x.size += 20;
	//fixme: set focus to start of inputted text after resizing
}

function urlOpen(u)
{
	document.location = u;
}

function in_arr(arr,val)
{
	for (var i=0; i<arr.length; i++) {
		if (arr[i] == val) return true;
	}
	return false;
}

function arr_del(arr,val)
{
	for (var i=0; i<arr.length; i++) {
		if (arr[i] == val) delete arr[i];	//fixme: this will leave arr[i] undefined, arr.length will not be changed
	}
}

function set_class(e,c){
	var x=document.getElementById(e);
	x.className=c;
}

function add_node(e,t,s) {
	var c=document.createElement('div');
	e.appendChild(c);
	var tx=document.createTextNode(t);
	c.appendChild(tx);
	c.className=s;
	return c;
}

function add_node_and_focus(e,t,s) {
	var c=add_node(e,t,s);
	c.scrollIntoView(false);
}

/* focuses on the faq item #i */
function faq_focus(n) {
	e = document.getElementById('faq_'+n);
	if (!e) return;
	e.style.display = '';	//show

	for (i=0;i<=100;i++) {
		if (i==n) continue;
		e = document.getElementById('faq_'+i);
		if (!e) return;
		e.style.display = 'none';	//hide

		hide_element_by_name('faq_edit_'+i);
		show_element_by_name('faq_holder_'+i);
	}
}

//used with $files->showThumbnails(). displays comments div and shrinks currently displayed image
//n=image id currently displayed
var comments_shown = false;
var org_w, org_h;
function show_image_comments(n)
{
	e = document.getElementById('img_'+n);

	if (!comments_shown) {
		show_element_by_name('image_comments_content');
		comments_shown = true;
		org_w = e.width;
		org_h = e.height;
		//fixme: shrinking image here dont work properly, first time it resizes it gets wrong then it gets correct
		//e.width *= 0.5;
		//e.height *= 0.5;
		return;
	}

	hide_element_by_name('image_comments_content');
	comments_shown = false;
	e.width = org_w;
	e.height = org_h;
}

//shows fileId i in a new window, displayed as a image
function popup_imgview(i,w,h)
{
	if(!w)w=300;
	if(!h)h=200;
	p = window.open(_ext_core+'popup_imgview.php?id='+i+_ext_ref, 'name', 'width='+w+',height='+h);
	if (window.focus) p.focus();
}

//sets element name "n" to the html content of "txt"
function set_div_content(n, txt)
{
	var e = document.getElementById(n);
	empty_element(e);

	e.innerHTML = txt;
	show_element_by_name(n);
}

//toggles all checkboxes in form "frm" on/off
function toggle_checkboxes(type, frm)
{
	type = (type.checked) ? true : false;
	var e = document.getElementById(frm);
	for (i = 0; i < e.length; i++) {
		var toggle = e.elements[i];
		if (toggle.type == 'checkbox') toggle.checked = type;
	}
}

function confirm_chk(t) {
	var r=confirm(t);
	if (r==true) return true;
	return false;
}

/**
 * Format selection
 *
 * Apply tagOpen/tagClose to selection in textarea, use sampleText instead
 * of selection if there is none. Copied and adapted from phpBB
 *
 * @author phpBB development team
 * @author MediaWiki development team
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Jim Raynor <jim_raynor@web.de>
 */
function insertTags(edid,tagOpen, tagClose, sampleText) {
  var txtarea = document.getElementById(edid);
  // IE
  if(document.selection  && !is_gecko) {
    var theSelection = document.selection.createRange().text;
    var replaced = true;
    if(!theSelection){
      replaced = false;
      theSelection=sampleText;
    }
    txtarea.focus();

    // This has change
    var text = theSelection;
    if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
      theSelection = theSelection.substring(0, theSelection.length - 1);
      r = document.selection.createRange();
      r.text = tagOpen + theSelection + tagClose + " ";
    } else {
      r = document.selection.createRange();
      r.text = tagOpen + theSelection + tagClose;
    }
    if(!replaced){
      r.moveStart('character',-text.length-tagClose.length);
      r.moveEnd('character',-tagClose.length);
    }
    r.select();
  // Mozilla
  } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
    replaced = false;
    var startPos = txtarea.selectionStart;
    var endPos   = txtarea.selectionEnd;
    if(endPos - startPos){ replaced = true; }
    var scrollTop=txtarea.scrollTop;
    var myText = (txtarea.value).substring(startPos, endPos);
    if(!myText) { myText=sampleText;}
    if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
      subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
    } else {
      subst = tagOpen + myText + tagClose;
    }
    txtarea.value = txtarea.value.substring(0, startPos) + subst +
                    txtarea.value.substring(endPos, txtarea.value.length);
    txtarea.focus();

    //set new selection
    if(replaced){
      var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
      txtarea.selectionStart=cPos;
      txtarea.selectionEnd=cPos;
    }else{
      txtarea.selectionStart=startPos+tagOpen.length;
      txtarea.selectionEnd=startPos+tagOpen.length+myText.length;
    }
    txtarea.scrollTop=scrollTop;
  // All others
  } else {
    var copy_alertText=alertText;
    var re1=new RegExp("\\$1","g");
    var re2=new RegExp("\\$2","g");
    copy_alertText=copy_alertText.replace(re1,sampleText);
    copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);

    if (sampleText) {
      text=prompt(copy_alertText);
    } else {
      text="";
    }
    if(!text) { text=sampleText;}
    text=tagOpen+text+tagClose;
    //append to the end
    txtarea.value += "\n"+text;

    // in Safari this causes scrolling
    if(!is_safari) {
      txtarea.focus();
    }

  }
  // reposition cursor if possible
  if (txtarea.createTextRange){
    txtarea.caretPos = document.selection.createRange().duplicate();
  }
}
<commit_msg>simplified confirm_chk()<commit_after>function trace(s)
{
	console.debug(s);
}

function urlencode(str)	//function borrowed from http://www.albionresearch.com/misc/urlencode.php
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < str.length; i++ ) {
		var ch = str.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}

	return encoded;
};

function trim(str)
{
	return str.replace(/^\s*|\s*$/g,"");
}

//Toggles element with name "n" between visible and hidden
//
//If this function makes an element "hidden" the browser
//regards it as non-existent and does not regard it as being
//part of the page-layout
function toggle_element_by_name(n)
{
	var e = document.getElementById(n);
	e.style.display = (e.style.display?'':'none');
}

//Makes element with name "n" invisible in browser
function hide_element_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.display = 'none';
}

//Makes element with name "n" visible in browser
function show_element_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.display = '';
}

//This function, as opposed to the ones above, has the
//browser render the content but show / dont show it
function set_visible_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.visibility="visible";
}

function set_invisible_by_name(n)
{
	var e = document.getElementById(n);
	if (!e) {
		//alert('fixme: element ' + n + ' not found');
		return;
	}
	e.style.visibility="hidden";
}

function add_div(e, idname, style)
{
	var c=document.createElement('div');

	c.setAttribute('id', idname);
	c.className = style;
	e.appendChild(c);

	return c;
}

function add_span(e)
{
	var c=document.createElement('span');

//	c.setAttribute('id', idname);
//	c.className = style;
	e.appendChild(c);

	return c;
}
function empty_element_by_name(n)
{
	var e=document.getElementById(n);

	while (e.hasChildNodes())
		e.removeChild(e.firstChild);
}

function fill_element_by_name(n,txt)
{
	var e = document.getElementById(n);
	empty_element(e);

	e.innerHTML = txt;
}

function empty_element(e)
{
	while (e.hasChildNodes()) e.removeChild(e.firstChild);
}

//checks if image n has been loaded, waits until it is done otherwise
function image_loaded(n)
{
	var e = document.getElementById(n);

	trace('image_loaded('+n+') w:'+e.width+',h:'+e.height);

	//IE. fixme:untested
	if (!e.complete) {
		return false;
	}

	//Firefox
	if (typeof e.naturalWidth != "undefined" && e.naturalWidth == 0) {
		return false;
	}

	return true;
}

//resizes current window to the same size as image n
function resize_wnd_to_img(n)
{
	var e = document.getElementById(n);
	trace('resize_wnd_to_img('+n+') w:'+e.width+',h:'+e.height);
	var NS = (navigator.appName=="Netscape")?true:false;

	iWidth = (NS)?window.innerWidth:document.body.clientWidth;
	iHeight = (NS)?window.innerHeight:document.body.clientHeight;
	iWidth = e.width - iWidth;
	iHeight = e.height - iHeight;
	window.resizeBy(iWidth, iHeight);
	self.focus();
}

function pause(ms)
{
	var now = new Date();
	var exitTime = now.getTime() + ms;

	while(true) {
		now = new Date();
		if(now.getTime() > exitTime) return;
	}
}

/* sends a ajax poll submit */
function submit_poll(id,opt)
{
	//alert('fixme: submit_poll() add ajax submit. id ' + id + ', opt ' + opt);
	ajax_poll(id,opt);

	hide_element_by_name('poll'+id);
	show_element_by_name('poll_voted'+id);
}

function get_poll_csv(id)
{
	var w = window.open(_ext_core+'csv_poll.php?id='+id+_ext_ref, '_blank');
	w.focus();
}

//Loads image id into holder-div
function loadImage(id, holder)
{
	var e = document.getElementById(holder);
	empty_element(e);

	var i = document.createElement('img');
	i.setAttribute('src', _ext_core+'file.php?id='+id+_ext_ref);
	e.appendChild(i);

	var j = document.getElementById('image_comments_iframe');
	j.setAttribute('src', _ext_core+'html_imgcomments.php?i='+id+_ext_ref);
}

function scroll_up(e, step, offs)
{
	e.scrollTop -= step;
	offs += step;

	if (offs<0) setTimeout(function() {scroll_up(e,step,offs)}, 1);
}

function scroll_down(e, step, offs)
{
	e.scrollTop += step;
	offs -= step;

	if (offs>0) setTimeout(function() {scroll_down(e,step,offs)}, 1);
}

//scroll the content of element name "n" by offset pixels. use negative value of offset to scroll up, positive to scroll down
function scroll_element_content(n,offs)
{
	var e = document.getElementById(n);

	if (offs>0) {
		setTimeout(function() {scroll_down(e,6,offs)}, 1);
	} else {
		setTimeout(function() {scroll_up(e,6,offs)}, 1);
	}
}

//expands size of <input type="text" id="n">
function expand_input(e)
{
	var x=document.getElementById(e);
	if (x.size < 120) x.size += 20;
	//fixme: set focus to start of inputted text after resizing
}

function urlOpen(u)
{
	document.location = u;
}

function in_arr(arr,val)
{
	for (var i=0; i<arr.length; i++) {
		if (arr[i] == val) return true;
	}
	return false;
}

function arr_del(arr,val)
{
	for (var i=0; i<arr.length; i++) {
		if (arr[i] == val) delete arr[i];	//fixme: this will leave arr[i] undefined, arr.length will not be changed
	}
}

function set_class(e,c){
	var x=document.getElementById(e);
	x.className=c;
}

function add_node(e,t,s) {
	var c=document.createElement('div');
	e.appendChild(c);
	var tx=document.createTextNode(t);
	c.appendChild(tx);
	c.className=s;
	return c;
}

function add_node_and_focus(e,t,s) {
	var c=add_node(e,t,s);
	c.scrollIntoView(false);
}

/* focuses on the faq item #i */
function faq_focus(n) {
	e = document.getElementById('faq_'+n);
	if (!e) return;
	e.style.display = '';	//show

	for (i=0;i<=100;i++) {
		if (i==n) continue;
		e = document.getElementById('faq_'+i);
		if (!e) return;
		e.style.display = 'none';	//hide

		hide_element_by_name('faq_edit_'+i);
		show_element_by_name('faq_holder_'+i);
	}
}

//used with $files->showThumbnails(). displays comments div and shrinks currently displayed image
//n=image id currently displayed
var comments_shown = false;
var org_w, org_h;
function show_image_comments(n)
{
	e = document.getElementById('img_'+n);

	if (!comments_shown) {
		show_element_by_name('image_comments_content');
		comments_shown = true;
		org_w = e.width;
		org_h = e.height;
		//fixme: shrinking image here dont work properly, first time it resizes it gets wrong then it gets correct
		//e.width *= 0.5;
		//e.height *= 0.5;
		return;
	}

	hide_element_by_name('image_comments_content');
	comments_shown = false;
	e.width = org_w;
	e.height = org_h;
}

//shows fileId i in a new window, displayed as a image
function popup_imgview(i,w,h)
{
	if(!w)w=300;
	if(!h)h=200;
	p = window.open(_ext_core+'popup_imgview.php?id='+i+_ext_ref, 'name', 'width='+w+',height='+h);
	if (window.focus) p.focus();
}

//sets element name "n" to the html content of "txt"
function set_div_content(n, txt)
{
	var e = document.getElementById(n);
	empty_element(e);

	e.innerHTML = txt;
	show_element_by_name(n);
}

//toggles all checkboxes in form "frm" on/off
function toggle_checkboxes(type, frm)
{
	type = (type.checked) ? true : false;
	var e = document.getElementById(frm);
	for (i = 0; i < e.length; i++) {
		var toggle = e.elements[i];
		if (toggle.type == 'checkbox') toggle.checked = type;
	}
}

function confirm_chk(t) {
	return confirm(t);
}

/**
 * Format selection
 *
 * Apply tagOpen/tagClose to selection in textarea, use sampleText instead
 * of selection if there is none. Copied and adapted from phpBB
 *
 * @author phpBB development team
 * @author MediaWiki development team
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Jim Raynor <jim_raynor@web.de>
 */
function insertTags(edid,tagOpen, tagClose, sampleText) {
  var txtarea = document.getElementById(edid);
  // IE
  if(document.selection  && !is_gecko) {
    var theSelection = document.selection.createRange().text;
    var replaced = true;
    if(!theSelection){
      replaced = false;
      theSelection=sampleText;
    }
    txtarea.focus();

    // This has change
    var text = theSelection;
    if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
      theSelection = theSelection.substring(0, theSelection.length - 1);
      r = document.selection.createRange();
      r.text = tagOpen + theSelection + tagClose + " ";
    } else {
      r = document.selection.createRange();
      r.text = tagOpen + theSelection + tagClose;
    }
    if(!replaced){
      r.moveStart('character',-text.length-tagClose.length);
      r.moveEnd('character',-tagClose.length);
    }
    r.select();
  // Mozilla
  } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
    replaced = false;
    var startPos = txtarea.selectionStart;
    var endPos   = txtarea.selectionEnd;
    if(endPos - startPos){ replaced = true; }
    var scrollTop=txtarea.scrollTop;
    var myText = (txtarea.value).substring(startPos, endPos);
    if(!myText) { myText=sampleText;}
    if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
      subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
    } else {
      subst = tagOpen + myText + tagClose;
    }
    txtarea.value = txtarea.value.substring(0, startPos) + subst +
                    txtarea.value.substring(endPos, txtarea.value.length);
    txtarea.focus();

    //set new selection
    if(replaced){
      var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
      txtarea.selectionStart=cPos;
      txtarea.selectionEnd=cPos;
    }else{
      txtarea.selectionStart=startPos+tagOpen.length;
      txtarea.selectionEnd=startPos+tagOpen.length+myText.length;
    }
    txtarea.scrollTop=scrollTop;
  // All others
  } else {
    var copy_alertText=alertText;
    var re1=new RegExp("\\$1","g");
    var re2=new RegExp("\\$2","g");
    copy_alertText=copy_alertText.replace(re1,sampleText);
    copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);

    if (sampleText) {
      text=prompt(copy_alertText);
    } else {
      text="";
    }
    if(!text) { text=sampleText;}
    text=tagOpen+text+tagClose;
    //append to the end
    txtarea.value += "\n"+text;

    // in Safari this causes scrolling
    if(!is_safari) {
      txtarea.focus();
    }

  }
  // reposition cursor if possible
  if (txtarea.createTextRange){
    txtarea.caretPos = document.selection.createRange().duplicate();
  }
}
<|endoftext|>


<commit_before>var Teaching = {
    is_desktop: undefined,

    render: function() {
        showLoading();
        CommonLoading.render_init();
        Teaching.make_html();
    },

    make_html: function () {
        $('html,body').animate({scrollTop: 0}, 'fast');
        var teaching_source = $("#teaching").html();
        var template = Handlebars.compile(teaching_source);

        $("#main-content").html(template({
            'seattle_affil': (window.user.seattle_affil || window.user.seattle),
            'bothell_affil': (window.user.bothell_affil || window.user.bothell),
            'tacoma_affil': (window.user.tacoma_affil || window.user.tacoma)
        }));

        NoticeBanner.render_init($("#notice_banner_location"));

        Teaching.load_cards_for_viewport();
        // Set initial display state
        Teaching.is_desktop = get_is_desktop();

        // Monitor for viewport changes and reorder cards if needed
        $(window).resize(function(){
            if (Teaching.is_desktop !== get_is_desktop()){
                Teaching.load_cards_for_viewport();
                Teaching.is_desktop = get_is_desktop();
            }
        });
    },

    load_cards_for_viewport: function() {
        if (get_is_desktop()) {
            Teaching._load_desktop_cards();
        } else {
            Teaching._load_mobile_cards();
        }
    },

    _load_desktop_cards: function() {
        Teaching._reset_content_divs();
        var desktop_body_cards = [
            VisualScheduleCard,
            InstructorCourseCards
        ];
        var desktop_sidebar_cards = [
            TeachingResourcesCard,
            EventsCard
        ];
        Cards.load_cards_in_order(desktop_body_cards, $("#teaching_content_cards"));
        Cards.load_cards_in_order(desktop_sidebar_cards, $("#teaching_accounts_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_desktop"));
    },

    _load_mobile_cards: function() {
        Teaching._reset_content_divs();
        var mobile_cards = [
            VisualScheduleCard,
            InstructorCourseCards,
            TeachingResourcesCard,
            EventsCard
        ];
        Cards.load_cards_in_order(mobile_cards, $("#teaching_content_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_mobile"));
    },

    _reset_content_divs: function() {
        $("#teaching_content_cards").html('');
        $("#teaching_accounts_cards").html('');
        $("#calendar_banner_location_desktop").html('');
        $("#calendar_banner_location_mobile").html('');
    }
};
<commit_msg>removes visual schedule from teaching page<commit_after>var Teaching = {
    is_desktop: undefined,

    render: function() {
        showLoading();
        CommonLoading.render_init();
        Teaching.make_html();
    },

    make_html: function () {
        $('html,body').animate({scrollTop: 0}, 'fast');
        var teaching_source = $("#teaching").html();
        var template = Handlebars.compile(teaching_source);

        $("#main-content").html(template({
            'seattle_affil': (window.user.seattle_affil || window.user.seattle),
            'bothell_affil': (window.user.bothell_affil || window.user.bothell),
            'tacoma_affil': (window.user.tacoma_affil || window.user.tacoma)
        }));

        NoticeBanner.render_init($("#notice_banner_location"));

        Teaching.load_cards_for_viewport();
        // Set initial display state
        Teaching.is_desktop = get_is_desktop();

        // Monitor for viewport changes and reorder cards if needed
        $(window).resize(function(){
            if (Teaching.is_desktop !== get_is_desktop()){
                Teaching.load_cards_for_viewport();
                Teaching.is_desktop = get_is_desktop();
            }
        });
    },

    load_cards_for_viewport: function() {
        if (get_is_desktop()) {
            Teaching._load_desktop_cards();
        } else {
            Teaching._load_mobile_cards();
        }
    },

    _load_desktop_cards: function() {
        Teaching._reset_content_divs();
        var desktop_body_cards = [
            InstructorCourseCards
        ];
        var desktop_sidebar_cards = [
            TeachingResourcesCard,
            EventsCard
        ];
        Cards.load_cards_in_order(desktop_body_cards, $("#teaching_content_cards"));
        Cards.load_cards_in_order(desktop_sidebar_cards, $("#teaching_accounts_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_desktop"));
    },

    _load_mobile_cards: function() {
        Teaching._reset_content_divs();
        var mobile_cards = [
            InstructorCourseCards,
            TeachingResourcesCard,
            EventsCard
        ];
        Cards.load_cards_in_order(mobile_cards, $("#teaching_content_cards"));
        CalendarBanner.render_init($("#calendar_banner_location_mobile"));
    },

    _reset_content_divs: function() {
        $("#teaching_content_cards").html('');
        $("#teaching_accounts_cards").html('');
        $("#calendar_banner_location_desktop").html('');
        $("#calendar_banner_location_mobile").html('');
    }
};
<|endoftext|>


<commit_before>define(
[
    'models',
    'views/common',
    'views/cluster',
    'views/clusters',
    'views/release',
    'views/notifications'
],
function(models, commonViews, clusterViews, clustersViews, releaseViews, notificationsViews) {
    'use strict';

    var AppRouter = Backbone.Router.extend({
        routes: {
            'clusters': 'listClusters',
            'cluster/:id': 'showCluster',
            'cluster/:id/:tab': 'showClusterTab',
            'releases': 'listReleases',
            'notifications': 'showNotifications',
            '*default': 'listClusters'
        },
        initialize: function() {
            this.content = $('#content');
            this.navbar = new commonViews.Navbar({elements: [
                ['OpenStack Installations', '#clusters'],
                ['OpenStack Releases', '#releases']
            ]});
            this.content.before(this.navbar.render().el);
            this.breadcrumbs = new commonViews.Breadcrumbs();
            this.content.before(this.breadcrumbs.render().el);
        },
        setPage: function(newPage) {
            if (this.page) {
                this.page.tearDown();
            }
            this.page = newPage;
            this.page.updateNavbar();
            this.page.updateBreadcrumbs();
            this.page.updateTitle();
            this.content.html(this.page.render().el);
        },
        showCluster: function(id) {
            this.navigate('#cluster/' + id + '/nodes', {trigger: true, replace: true});
        },
        showClusterTab: function(id, activeTab) {
            if (!_.contains(clusterViews.ClusterPage.prototype.tabs, activeTab)) {
                this.showCluster(id);
                return;
            }

            var cluster;
            var tabArguments = _.tail(arguments, 2);
            var render = function() {
                this.setPage(new clusterViews.ClusterPage({model: cluster, activeTab: activeTab, tabArguments: tabArguments}));
            };

            if (app.page && app.page.constructor == clusterViews.ClusterPage && app.page.model.id == id) {
                // just another tab has been chosen, do not load cluster again
                cluster = app.page.model;
                render.call(this);
            } else {
                cluster = new models.Cluster({id: id});
                cluster.fetch({
                    success: _.bind(render, this),
                    error: _.bind(this.listClusters, this)
                });
            }
        },
        listClusters: function() {
            this.navigate('#clusters', {replace: true});
            var clusters = new models.Clusters();
            clusters.fetch({
                success: _.bind(function() {
                    this.setPage(new clustersViews.ClustersPage({collection: clusters}));
                }, this)
            });
        },
        listReleases: function() {
            var releases = new models.Releases();
            releases.fetch({
                success: _.bind(function() {
                    this.setPage(new releaseViews.ReleasesPage({collection: releases}));
                }, this)
            });
        },
        showNotifications: function() {
            this.setPage(new notificationsViews.NotificationsPage({collection: app.navbar.notifications, nodes: app.navbar.stats.nodes}));
        },
        urlify: function (text) {
            var urlRegexp = /http:(\&\#x2F\;){2}(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\&\#x2F\;)/g;
            return text.replace(urlRegexp, function(url) {
                return '' + url + '';
            });
        },
        forceWebkitRedraw: function(el) {
            if ($.browser.webkit) {
                el.each(function() {
                    this.style.webkitTransform = 'scale(1)';
                    var dummy = this.offsetHeight;
                    this.style.webkitTransform = '';
                });
            }
        }
    });

    return {
        initialize: function() {
            var app = new AppRouter();
            window.app = app;
            Backbone.history.start();

            // tooltips
            $('body').tooltip({selector: "[rel=tooltip]"});
            app.bind('all', function(route) {$('.tooltip').remove();});
        }
    };
});
<commit_msg>Take into account linefeeds in deployment results<commit_after>define(
[
    'models',
    'views/common',
    'views/cluster',
    'views/clusters',
    'views/release',
    'views/notifications'
],
function(models, commonViews, clusterViews, clustersViews, releaseViews, notificationsViews) {
    'use strict';

    var AppRouter = Backbone.Router.extend({
        routes: {
            'clusters': 'listClusters',
            'cluster/:id': 'showCluster',
            'cluster/:id/:tab': 'showClusterTab',
            'releases': 'listReleases',
            'notifications': 'showNotifications',
            '*default': 'listClusters'
        },
        initialize: function() {
            this.content = $('#content');
            this.navbar = new commonViews.Navbar({elements: [
                ['OpenStack Installations', '#clusters'],
                ['OpenStack Releases', '#releases']
            ]});
            this.content.before(this.navbar.render().el);
            this.breadcrumbs = new commonViews.Breadcrumbs();
            this.content.before(this.breadcrumbs.render().el);
        },
        setPage: function(newPage) {
            if (this.page) {
                this.page.tearDown();
            }
            this.page = newPage;
            this.page.updateNavbar();
            this.page.updateBreadcrumbs();
            this.page.updateTitle();
            this.content.html(this.page.render().el);
        },
        showCluster: function(id) {
            this.navigate('#cluster/' + id + '/nodes', {trigger: true, replace: true});
        },
        showClusterTab: function(id, activeTab) {
            if (!_.contains(clusterViews.ClusterPage.prototype.tabs, activeTab)) {
                this.showCluster(id);
                return;
            }

            var cluster;
            var tabArguments = _.tail(arguments, 2);
            var render = function() {
                this.setPage(new clusterViews.ClusterPage({model: cluster, activeTab: activeTab, tabArguments: tabArguments}));
            };

            if (app.page && app.page.constructor == clusterViews.ClusterPage && app.page.model.id == id) {
                // just another tab has been chosen, do not load cluster again
                cluster = app.page.model;
                render.call(this);
            } else {
                cluster = new models.Cluster({id: id});
                cluster.fetch({
                    success: _.bind(render, this),
                    error: _.bind(this.listClusters, this)
                });
            }
        },
        listClusters: function() {
            this.navigate('#clusters', {replace: true});
            var clusters = new models.Clusters();
            clusters.fetch({
                success: _.bind(function() {
                    this.setPage(new clustersViews.ClustersPage({collection: clusters}));
                }, this)
            });
        },
        listReleases: function() {
            var releases = new models.Releases();
            releases.fetch({
                success: _.bind(function() {
                    this.setPage(new releaseViews.ReleasesPage({collection: releases}));
                }, this)
            });
        },
        showNotifications: function() {
            this.setPage(new notificationsViews.NotificationsPage({collection: app.navbar.notifications, nodes: app.navbar.stats.nodes}));
        },
        urlify: function (text) {
            var urlRegexp = /http:(\&\#x2F\;){2}(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\&\#x2F\;)/g;
            return text.replace(/\n/g, '
').replace(urlRegexp, function(url) {
                return '' + url + '';
            });
        },
        forceWebkitRedraw: function(el) {
            if ($.browser.webkit) {
                el.each(function() {
                    this.style.webkitTransform = 'scale(1)';
                    var dummy = this.offsetHeight;
                    this.style.webkitTransform = '';
                });
            }
        }
    });

    return {
        initialize: function() {
            var app = new AppRouter();
            window.app = app;
            Backbone.history.start();

            // tooltips
            $('body').tooltip({selector: "[rel=tooltip]"});
            app.bind('all', function(route) {$('.tooltip').remove();});
        }
    };
});
<|endoftext|>


<commit_before>import {h, Component} 					from 'preact/preact';
import ContentSimple					from 'com/content-simple/simple';
import UIIcon							from 'com/ui/icon/icon';
import UIButton							from 'com/ui/button/button';

//import $Node							from '../../shrub/js/node/node';

export default class ContentPost extends Component {
	constructor( props ) {
		super(props);
	}

	render( props ) {
		let {node, user, path, extra} = props;
		props = Object.assign({}, props);

		// Additional properties
		//props.authored = 1;

		if ( node ) {
			if ( node.subtype === 'news' ) {
				//props.header = "NEWS";
				props.by = "NEWS";
				props.headerIcon = "news";
				props.headerClass = "-col-c";
			}
			else if ( node.subtype === 'info' ) {
				//props.header = "INFO";
				props.by = "INFO";
				props.headerIcon = "info";
				props.headerClass = "-col-nddd";
			}
			else if ( node.subtype === 'guide' ) {
				//props.header = "GUIDE";
				props.by = "GUIDE";
				props.headerIcon = "article";
				props.headerClass = "-col-nddd";
			}
			else if ( node.subtype === 'promo' ) {
				//props.header = "INFO";
				//props.by = "INFO";
				props.headerIcon = "gift";
				props.headerClass = "-col-ab";
				if ( props.single ) {
					if ( props.user && props.user.id ) {
						let Body =
Unknown Promo Type
;

						// Shared promos have a single code used by many (associated with the node)
						if ( node.subsubtype == 'shared' ) {
							if ( node.meta['promo-code'] ) {
								Body = (

										Code: {node.meta['promo-code']}

								);
							}
							else {
								Body =
No `promo-code` associated with shared promo node.
;
							}
						}
						// Single promos have a pool of codes, and each user must request one
						else if ( node.subsubtype == 'single' ) {
							Body =
{node.subsubtype}
;
						}

						props.children = (

Get Promo

								{Body}

						);
					}
					else {
						props.children = (

Get Promo

Login to claim

						);
					}
				}
				else {
					props.children = (

							<UIButton class="content-common-nav-button" href={node.path}><UIIcon src="gift" />
Continue
</UIButton>

					);
				}
			}
		}

		props.limit = 1024*24;

		return <ContentSimple {...props} />;
	}
}
<commit_msg>shared promos now working<commit_after>import {h, Component} 					from 'preact/preact';
import ContentSimple					from 'com/content-simple/simple';
import UIIcon							from 'com/ui/icon/icon';
import UIButton							from 'com/ui/button/button';

//import $Node							from '../../shrub/js/node/node';

export default class ContentPost extends Component {
	constructor( props ) {
		super(props);
	}

	render( props ) {
		let {node, user, path, extra} = props;
		props = Object.assign({}, props);

		// Additional properties
		//props.authored = 1;

		if ( node ) {
			if ( node.subtype === 'news' ) {
				//props.header = "NEWS";
				props.by = "NEWS";
				props.headerIcon = "news";
				props.headerClass = "-col-c";
			}
			else if ( node.subtype === 'info' ) {
				//props.header = "INFO";
				props.by = "INFO";
				props.headerIcon = "info";
				props.headerClass = "-col-nddd";
			}
			else if ( node.subtype === 'guide' ) {
				//props.header = "GUIDE";
				props.by = "GUIDE";
				props.headerIcon = "article";
				props.headerClass = "-col-nddd";
			}
			else if ( node.subtype === 'promo' ) {
				//props.header = "INFO";
				//props.by = "INFO";
				props.headerIcon = "gift";
				props.headerClass = "-col-ab";
				if ( props.single ) {
					if ( props.user && props.user.id ) {
						let Body =
Unknown Promo Type
;

						// Shared promos have a single code used by many (associated with the node)
						if ( node.subsubtype == 'shared' ) {
							if ( node.meta['promo-code'] ) {
								Body = (

										Code: {node.meta['promo-code']}

								);
							}
							else {
								Body =
No `promo-code` associated with shared promo node.
;
							}
						}
						// Single promos have a pool of codes, and each user must request one
						else if ( node.subsubtype == 'single' ) {
							Body =
{node.subsubtype}
;
						}

						props.children = (

Get Promo

								{Body}

						);
					}
					else {
						props.children = (

Get Promo

Login to claim

						);
					}
				}
				else {
					props.children = (

							<UIButton class="content-common-nav-button" href={node.path}><UIIcon src="gift" />
Continue
</UIButton>

					);
				}
			}
		}

		props.limit = 1024*24;

		return <ContentSimple {...props} />;
	}
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief tests for readonly mode of arango
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Esteban Lombeyda
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function dropDatabaseTestSuite () {
  var db;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._changeMode("Normal");
      db._createDatabase("testDB");
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        db._dropDatabase("testDB");
        } catch (e) {
        }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: creation of a data base in read only modes should faill
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDatabase: function () {
      var not_modified = false;
      try {
        db._createDatabase("xxxDB");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: droping of a data base in read only mode should be posible
      ////////////////////////////////////////////////////////////////////////////////

      testDropDatabase: function () {
        var modified = false;
        try {
          db._dropDatabase("testDB");
          modified = true;
        } catch (e) {
          not_modified = false;
        }
        assertTrue(modified);
     },
  };
}
////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////
function readOnlyDatabaseSuite () {
  var db;
  var collection;
  return {

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief set up
    ////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db = require("internal").db;
      db._drop("testCol");
      collection = db._createDocumentCollection("testCol");
      collection.save({_key: "testDocKey", a: 2 });
      db._changeMode("ReadOnly");
    },
    tearDown : function () {
      try {
        db._changeMode("Normal");
        collection.drop();
      } catch (e) {
      }
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (prefix)
    ////////////////////////////////////////////////////////////////////////////////

    testCreateDocumentCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("abcDC");
        } catch (e) {
          not_modified = true;
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
      assertTrue(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (parameter)
    ////////////////////////////////////////////////////////////////////////////////

    testDropCollection: function () {
      var not_modified = false;
      try {
        db._createDocumentCollection("xxxDC");
        not_modified = true;
        } catch (e) {
      }
      assertFalse(not_modified);
    },

    ////////////////////////////////////////////////////////////////////////////////
    /// @brief test: simple routing (optional)
    ////////////////////////////////////////////////////////////////////////////////

    testInsertDocument: function () {
      var modified = false;
      try {
        collection.save({a:1, b:2});
        modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (optional)
      ////////////////////////////////////////////////////////////////////////////////

      testUpdateDocument: function () {
        var modified = false;
        try {
          collection.update("testDocKey", {name: "testing", a: 3});
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: simple routing (prefix vs non-prefix)
      ////////////////////////////////////////////////////////////////////////////////

      testRemoveDocument: function () {
        var modified = false;
        try {
          var removed = collection.remove("testDocKey");
          assertFalse(removed);
          modified = true;
        } catch (e) {
          assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
        }
        assertFalse(modified);
      },

      ////////////////////////////////////////////////////////////////////////////////
      /// @brief test: content string
      ////////////////////////////////////////////////////////////////////////////////

      testCreateBitArrayIndex: function () {
        var modified = false;
        try {
          collection.ensureBitarray("a", [1,2,3,4]);
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateHashIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "hash", fields: [ "name" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
      },

      testCreateGeoIndex: function () {
        var modified = false;
        try {
          collection.ensureIndex({ type: "geo1", fields: [ "x" ], unique: true });
          modified = true;
          } catch (e) {
            assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
          }
        assertFalse(modified);
       },

       testCreateGeo2Index: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "geo2", fields: [ "x", "y" ], unique: true });
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

       testCreateSkipListIndex: function () {
         var modified = false;
         try {
           collection.ensureIndex({ type: "skiplist", fields: [ "x" ]});
           modified = true;
         } catch (e) {
           assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
         }
         assertFalse(modified);
       },

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(dropDatabaseTestSuite);
jsunity.run(readOnlyDatabaseSuite);

return jsunity.done();

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:
<commit_msg>fixed indentation, copy&paste, incomplete and too complicated tests<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief tests for readonly mode of arango
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Esteban Lombeyda
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var jsunity = require("jsunity");
var arangodb = require("org/arangodb");

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////

function databaseTestSuite () {
  var db = require("internal").db;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db._changeMode("Normal");
      try {
        db._dropDatabase("testDB");
      }
      catch (e) {
        // ignore any errors
      }

      db._createDatabase("testDB");
      db._changeMode("ReadOnly");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      db._changeMode("Normal");
      try {
        db._dropDatabase("testDB");
      }
      catch (e) {
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: creation of a database in read only mode should fail
////////////////////////////////////////////////////////////////////////////////

    testCreateDatabase: function () {
      try {
        db._createDatabase("xxxDB");
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: dropping of a database in read only mode should be possible
////////////////////////////////////////////////////////////////////////////////

    testDropDatabase: function () {
      try {
        db._dropDatabase("testDB");
        assertEqual(-1, db._listDatabases().indexOf("testDb"));
      }
      catch (e) {
        fail();
      }
    }

  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief single tests when server is running in ReadOnly mode
////////////////////////////////////////////////////////////////////////////////

function operationsTestSuite () {
  var db = require("internal").db;
  var collection;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      db._drop("testCol");
      collection = db._create("testCol");
      collection.save({_key: "testDocKey", a: 2 });
      db._changeMode("ReadOnly");
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      db._changeMode("Normal");
      collection.drop();
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: creating a collection
////////////////////////////////////////////////////////////////////////////////

    testCreateCollection: function () {
      db._drop("abcDC");

      try {
        db._create("abcDC");
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: dropping a collection
////////////////////////////////////////////////////////////////////////////////

    testDropCollection: function () {
      // should not throw any errors
      db._drop("testCol");
      assertTrue(true);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: insert
////////////////////////////////////////////////////////////////////////////////

    testInsertDocument: function () {
      try {
        collection.save({a:1, b:2});
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: update
////////////////////////////////////////////////////////////////////////////////

    testUpdateDocument: function () {
      try {
        collection.update("testDocKey", {name: "testing", a: 3});
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: replace
////////////////////////////////////////////////////////////////////////////////

    testReplaceDocument: function () {
      try {
        collection.replace("testDocKey", {name: "testing", a: 3});
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: remove
////////////////////////////////////////////////////////////////////////////////

    testRemoveDocument: function () {
      try {
        collection.remove("testDocKey");
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: create index
////////////////////////////////////////////////////////////////////////////////

    testCreateBitArrayIndex: function () {
      try {
        collection.ensureBitarray("a", [1,2,3,4]);
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: create index
////////////////////////////////////////////////////////////////////////////////

    testCreateHashIndex: function () {
      try {
        collection.ensureIndex({ type: "hash", fields: [ "name" ], unique: true });
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: create index
////////////////////////////////////////////////////////////////////////////////

    testCreateGeoIndex: function () {
      try {
        collection.ensureIndex({ type: "geo1", fields: [ "x" ], unique: true });
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: create index
////////////////////////////////////////////////////////////////////////////////

    testCreateGeo2Index: function () {
      try {
        collection.ensureIndex({ type: "geo2", fields: [ "x", "y" ], unique: true });
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief test: create index
////////////////////////////////////////////////////////////////////////////////

    testCreateSkipListIndex: function () {
      try {
        collection.ensureIndex({ type: "skiplist", fields: [ "x" ]});
        fail();
      }
      catch (e) {
        assertEqual(arangodb.ERROR_ARANGO_READ_ONLY, e.errorNum);
      }
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(databaseTestSuite);
jsunity.run(operationsTestSuite);

return jsunity.done();

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>function addOnloadEvent(proc){
     if (window.addEventListener) {
          window.addEventListener("load",proc,false);
     }
     else if (window.attachEvent) {
          window.attachEvent("onload", proc);
     }
}

var win = false;
var textContent = 'textContent';
var filter_state = new Object;
var sort_state = '';

function init(){
     win = document.all?true:false;
     textContent = win?'innerText':'textContent';
}

addOnloadEvent(init);
addOnloadEvent(focus_focus);

function sort_table(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;

     sort_state = target.getAttribute('value')

     var rev = false;
     if (target.style.backgroundColor){
          target.style.backgroundColor = '';
          rev = true;
     } else {
          var brothers = target.parentNode.childNodes;
          for (var i = 0; i < brothers.length; i++){
               brothers[i].style.backgroundColor = '';
          }
          target.style.backgroundColor = 'pink';
     }
     var table = find_parent(target, 'TABLE');
     var headers = table.rows.item(0).cells;
     var pos = target.cellIndex;
     var rows = table.rows;
     var rows_ = new Array;
     for (i = 1; i < rows.length; i++) {
          rows_[i-1] = rows.item(i);
     }

     rows_ = rows_.sort(function(x,y){
                             var x_var = x.cells.item(pos).getAttribute('value');
                             var y_var = y.cells.item(pos).getAttribute('value');
                             if (x_var == y_var)
                                  return 0;
                             else if (x_var > y_var)
                                  return rev?1:-1;
                             else
                                  return rev?-1:1;
                        });

     var newbody = document.createElement('tbody');

     var tbody = table.getElementsByTagName('TBODY').item(0);

     for (i = 0; i<rows_.length; i++) {
          newbody.appendChild(rows_[i]);
     }
     table.replaceChild(newbody, tbody);
}

function apply_flter_state(a){
     var state = '';
     for (filter in  filter_state){
          for (f in filter_state[filter]){
               state += ('&' + filter + '=' + encodeURIComponent(filter_state[filter][f].value));
          }
     }
     if (sort_state) {
          state += '&sort_state=' + encodeURIComponent(sort_state);
     }
     if (state){
          a.href += '?'+state.slice(1);
     }
}

function copy_search(a){
     if (location.search){
          a.href += (location.search + '&search=' + encodeURIComponent(location.search.slice(1)));
     }
}

function filter_table(select, id, all_text){

     var table = document.getElementById(id);
     var options = select.options;
     var option;

     var option_list = new Array;
     var select_text_list = new Array;

     var label = find_parent(select, 'TABLE').rows.item(0).cells.item(select.parentNode.cellIndex);
     var label_text = label[textContent]
     var thead_cells = table.tHead.rows.item(0).cells;
     var pos = 0;
     for (var i = 0; i<thead_cells.length; i++) {
          if (thead_cells.item(i)[textContent] == label_text) {
               pos = i;
               break;
          }
     }

     /* find selected text */
     for (var i=0; i<options.length; i++) {
          option = options.item(i)
          if (option.selected) {
               option_list.push(option);
               select_text_list.push(option.text);
          }
     }

     filter_state[select.name] = option_list;

     /* highlight selected option */
     var prev_options = select.prev_options;
     if (prev_options != undefined)
          for (i=0; i<prev_options.length; i++) {
               prev_options[i].style.backgroundColor = '';
          }
     for (i=0; i<option_list.length; i++) {
          option_list[i].style.backgroundColor = 'lightblue';
     }
     select.prev_options = option_list;

     var all = has_item(select_text_list,all_text)?true:false;

     var row;
     /* reset previous filter */
     if (select.filterd_rows != undefined) {
          for (i = 0; i<select.filterd_rows.length; i++) {
               row = select.filterd_rows[i];
               row.filterd -= 1;
          }
     }
     var cell;
     var rows = table.rows;
     var filterd_rows = new Array;

     var tbody = table.getElementsByTagName('TBODY').item(0);
     var newbody = document.createElement('tbody');
     table.style.display='none';
     /* filter loop */
     for (i = 1; i < rows.length; i++) {
          row = rows.item(i);
          cell = row.cells.item(pos);
          /* initialize filter count */
          if (row.filterd == undefined) {
               row.filterd = 0;
          }
          /* count up */
          if (!all && !has_item(select_text_list, cell[textContent])) {
               filterd_rows.push(row)
               row.filterd += 1;
          }

          /* check count and set visibility */
          if (!all && row.filterd > 0) {
               row.style.display = "none";
          } else if (row.filterd == 0) {
               row.style.display = '';
          }
     }
     table.style.display=''
     /* save filterd_rows for next select */
     select.filterd_rows = filterd_rows;
     label.style.color = all?'':'red';

     return true;
}

function filter_this(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;
     var target_text = target[textContent];
     var table = find_parent(target,'TABLE');
     var head = table.tHead.rows.item(0).cells.item(target.cellIndex);
     var pos = head.getAttribute('for');
     var filter = document.getElementById('table_filter');
     var select = filter.rows.item(1).cells.item(pos).getElementsByTagName('SELECT').item(0);
     var opt;
     for (var i=0; i<select.options.length; i++) {
          opt = select.options[i];
          if (opt[textContent] == target_text) {
               opt.selected = true;
          }
     }
     select.onchange()

//      var rows = table.rows;
//      var filterd_rows = new Array;
}

function find_parent(ele, tagname){
     while (ele.tagName != tagname) {
          ele = ele.parentNode;
          if (ele == document) {
               return false;
          }
     }
     return ele;
}

function toggle_select_mode(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;
     if (target.className != 'clickable')
          return false;
     target = find_parent(target, 'TH');
     var pos = target.cellIndex;
     var td = target.parentNode.nextSibling.cells.item(pos);
     var select = td.getElementsByTagName('SELECT').item(0);
     select.multiple = select.size>1?false:true;
     select.size = select.size>1?1:5;
     return false;
}

function has_item(array, value){
     for (var i=0; i<array.length; i++) {
          if (array[i] == value){
               return true;
          }
     }
     return false;
}

function up_select(button,id){
     var select = document.getElementById(id);
     var options = select.options;
     var prev = options.item(0);
     var opt;
     for (var i=0; i<options.length; i++) {
          opt = options.item(i);
          if (opt.selected) {
               select.insertBefore(opt,prev);
          }
          else {
               prev = opt;
          }
     }
}

function down_select(button,id){
     var select = document.getElementById(id);
     var options = select.options;
     var prev = options.item(options.length-1);
     var opt;
     for (var i=options.length-1; i>=0; i--) {
          opt = options.item(i);
          if (opt.selected) {
               select.insertBefore(prev,opt);
          }
          else {
               prev = opt;
          }
     }
}

function toggle_fulllist(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;
     if (target.className != 'clickable')
          return false;
     target = find_parent(target, 'TH');
     var pos = target.cellIndex;
     var td = target.parentNode.nextSibling.cells.item(pos*2);
     var select = td.getElementsByTagName('SELECT').item(0);
     if (select.prev_size != undefined) {
          select.size = select.prev_size;
          select.prev_size = undefined;
     } else {
          select.prev_size = select.size;
          select.size = select.length;
     }
     return false;
}

var current_search = null;
var previous_search_key = null;

function delay_search(value){

     if (current_search) {
          // abort previous delayed search
          clearTimeout(current_search);
     }
     current_search = setTimeout(function () {
                                      search_musume(value);
                                      current_search = null;
                                 },
                                 300);
}

function search_musume(value)
{
     var table = document.getElementById('musume_list');
     if (value == previous_search_key){
          return false;
     }
     previous_search_key = value;
     var showall=value==""?true:false

     var tbody = table.getElementsByTagName('TBODY').item(0);
     var newbody = document.createElement('tbody');
     table.style.display='none';
     var rows = table.rows;
     var matcher = new RegExp(value,'i');
     var row, cell0, cell1;

     for (var i = 1; i < rows.length; i++) {
          row = rows.item(i);
          cell0 = row.cells.item(1);
          cell1 = row.cells.item(2);
          if (showall ||
              (cell0[textContent]+cell1[textContent]).match(matcher)) {
               row.style.display = '';
          }
          else {
               row.style.display = "none";
          }
     }
     table.style.display=''
     current_search = null;
     return false;
}

function focus_focus(){
     var target = document.getElementById('focus');
     if (target)
          target.focus();
     return false;
}

function submitForm(form){
  form.submit();
  submitForm = blockIt;
  return false;
}

function blockIt(){
  return false;
}

<commit_msg>Improved sort filter and search function code.<commit_after>function addOnloadEvent(proc){
     if (window.addEventListener) {
          window.addEventListener("load",proc,false);
     }
     else if (window.attachEvent) {
          window.attachEvent("onload", proc);
     }
}

var win = false;
var textContent = 'textContent';
var filter_state = new Object;
var sort_state = '';

function init(){
     win = document.all?true:false;
     textContent = win?'innerText':'textContent';
}

addOnloadEvent(init);
addOnloadEvent(focus_focus);

function sort_table(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;

     sort_state = target.getAttribute('value')

     var rev = false;
     if (target.style.backgroundColor){
          target.style.backgroundColor = '';
          rev = true;
     } else {
          var brothers = target.parentNode.childNodes;
          for (var i = 0; i < brothers.length; i++){
               brothers[i].style.backgroundColor = '';
          }
          target.style.backgroundColor = 'pink';
     }
     var table = find_parent(target, 'TABLE');
     var headers = table.rows.item(0).cells;
     var pos = target.cellIndex;
     var rows = table.rows;
     var rows_ = new Array;
     for (i = 1; i < rows.length; i++) {
          rows_[i-1] = rows.item(i);
     }

     rows_ = rows_.sort(function(x,y){
                             var x_var = x.cells.item(pos).getAttribute('value');
                             var y_var = y.cells.item(pos).getAttribute('value');
                             if (x_var == y_var)
                                  return 0;
                             else if (x_var > y_var)
                                  return rev?1:-1;
                             else
                                  return rev?-1:1;
                        });

     var newbody = document.createElement('tbody');

     var tbody = table.tBodies[0];

     for (i = 0; i<rows_.length; i++) {
          newbody.appendChild(rows_[i]);
     }
     table.replaceChild(newbody, tbody);
}

function apply_flter_state(a){
     var state = '';
     for (filter in  filter_state){
          for (f in filter_state[filter]){
               state += ('&' + filter + '=' + encodeURIComponent(filter_state[filter][f].value));
          }
     }
     if (sort_state) {
          state += '&sort_state=' + encodeURIComponent(sort_state);
     }
     if (state){
          a.href += '?'+state.slice(1);
     }
}

function copy_search(a){
     if (location.search){
          a.href += (location.search + '&search=' + encodeURIComponent(location.search.slice(1)));
     }
}

function filter_table(select, id, all_text){

     var table = document.getElementById(id);
     var options = select.options;
     var option;

     var option_list = new Array;
     var select_text_list = new Array;

     var label = find_parent(select, 'TABLE').rows.item(0).cells.item(select.parentNode.cellIndex);
     var label_text = label[textContent];
     var thead_cells = table.tHead.rows.item(0).cells;
     var pos = 0;
     for (var i = 0; i<thead_cells.length; i++) {
          if (thead_cells.item(i)[textContent] == label_text) {
               pos = i;
               break;
          }
     }

     /* find selected text */
     for (i=0; i<options.length; i++) {
          option = options.item(i)
          if (option.selected) {
               option_list.push(option);
               select_text_list.push(option.text);
          }
     }

     filter_state[select.name] = option_list;

     /* highlight selected option */
     var prev_options = select.prev_options;
     if (prev_options != undefined)
          for (i=0; i<prev_options.length; i++) {
               prev_options[i].style.backgroundColor = '';
          }
     for (i=0; i<option_list.length; i++) {
          option_list[i].style.backgroundColor = 'lightblue';
     }
     select.prev_options = option_list;

     var all = has_item(select_text_list,all_text)?true:false;

     var row;
     /* reset previous filter */
     if (select.filterd_rows != undefined) {
          for (i = 0; i<select.filterd_rows.length; i++) {
               row = select.filterd_rows[i];
               row.filterd -= 1;
          }
     }
     var cell;
     var rows = table.rows;
     var filterd_rows = new Array;

     table.style.display='none';
     /* filter loop */
     for (i = 1; i < rows.length; i++) {
          row = rows.item(i);
          cell = row.cells.item(pos);
          /* initialize filter count */
          if (row.filterd == undefined) {
               row.filterd = 0;
          }
          /* count up */
          if (!all && !has_item(select_text_list, cell[textContent])) {
               filterd_rows.push(row)
               row.filterd += 1;
          }

          /* check count and set visibility */
          if (!all && row.filterd > 0) {
               row.style.display = "none";
          } else if (row.filterd == 0) {
               row.style.display = '';
          }
     }
     table.style.display=''
     /* save filterd_rows for next select */
     select.filterd_rows = filterd_rows;
     label.style.color = all?'':'red';

     return true;
}

function find_parent(ele, tagname){
     while (ele.tagName != tagname) {
          ele = ele.parentNode;
          if (ele == document) {
               return false;
          }
     }
     return ele;
}

function toggle_select_mode(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;
     if (target.className != 'clickable')
          return false;
     target = find_parent(target, 'TH');
     var pos = target.cellIndex;
     var td = target.parentNode.nextSibling.cells.item(pos);
     var select = td.getElementsByTagName('SELECT').item(0);
     select.multiple = select.size>1?false:true;
     select.size = select.size>1?1:5;
     return false;
}

function has_item(array, value){
     for (var i=0; i<array.length; i++) {
          if (array[i] == value){
               return true;
          }
     }
     return false;
}

function up_select(button,id){
     var select = document.getElementById(id);
     var options = select.options;
     var prev = options.item(0);
     var opt;
     for (var i=0; i<options.length; i++) {
          opt = options.item(i);
          if (opt.selected) {
               select.insertBefore(opt,prev);
          }
          else {
               prev = opt;
          }
     }
}

function down_select(button,id){
     var select = document.getElementById(id);
     var options = select.options;
     var prev = options.item(options.length-1);
     var opt;
     for (var i=options.length-1; i>=0; i--) {
          opt = options.item(i);
          if (opt.selected) {
               select.insertBefore(prev,opt);
          }
          else {
               prev = opt;
          }
     }
}

function toggle_fulllist(e){
     e = win?window.event:e;
     var target = win?e.srcElement:e.target;
     if (target.className != 'clickable')
          return false;
     target = find_parent(target, 'TH');
     var pos = target.cellIndex;
     var td = target.parentNode.nextSibling.cells.item(pos*2);
     var select = td.getElementsByTagName('SELECT').item(0);
     if (select.prev_size != undefined) {
          select.size = select.prev_size;
          select.prev_size = undefined;
     } else {
          select.prev_size = select.size;
          select.size = select.length;
     }
     return false;
}

var current_search = null;
var previous_search_key = null;

function delay_search(value){

     if (current_search) {
          // abort previous delayed search
          clearTimeout(current_search);
     }
     current_search = setTimeout(function () {
                                      search_musume(value);
                                      current_search = null;
                                 },
                                 300);
}

function search_musume(value)
{
     var table = document.getElementById('musume_list');
     if (value == previous_search_key){
          return false;
     }

     // save searching position to table attribute
     if (table.search_pos == undefined) {
          var thead_cells = table.tHead.rows.item(0).cells;
          var pos = [];
          var name;
          for (var i = 0; i<thead_cells.length; i++) {
               name = thead_cells.item(i).getAttribute('value');
               if (name == 'no' || name == 'title') {
                    pos.push(i);
               }
          }
          table.search_pos = [1,2];
     }

     previous_search_key = value;
     var showall=value==""?true:false

     table.style.display='none';
     var rows = table.rows;
     var matcher = new RegExp(value,'i');
     var row, cell0, cell1;

     for (i = 1; i < rows.length; i++) {
          row = rows.item(i);
          cell0 = row.cells.item(table.search_pos[0]);
          cell1 = row.cells.item(table.search_pos[1]);
          if (showall ||
              (cell0[textContent]+cell1[textContent]).match(matcher)) {
               row.style.display = '';
          }
          else {
               row.style.display = "none";
          }
     }
     table.style.display=''
     current_search = null;
     return false;
}

function search_onKeyDown(e)
{
     if(true || e.ctrlKey){
          switch (e.keyCode) {
          case 32: /* SPACE */{
                    var table = document.getElementById('musume_list');
                    var rows = table.tBodies[0].rows;
                    var pos = get_row_pos_by_value(table, 'title');
                    for (var i=0; i < rows.length; i++) {
                         if (rows[i].style.display != "none") {
                              rows[i].cells[pos].firstChild.focus();
                              return false;
                         }
                    }
               }
          }
     }
     return true;
}

function focus_focus(){
     var target = document.getElementById('focus');
     if (target)
          target.focus();
     return false;
}

function submitForm(form){
  form.submit();
  submitForm = blockIt;
  return false;
}

function blockIt(){
  return false;
}

function update_status(elem){
     var form = document.getElementById('filtering_form');
     var target = elem[textContent];
     var options = form.status.options;
     for (var i=0; i < options.length; i++) {
          if (options[i][textContent] == target) {
               options[i].selected = true;
               break;
          }
     }
     form.status.onchange();
     return false;
}

function get_row_pos_by_value(table, value) {
     var thead_cells = table.tHead.rows.item(0).cells;
     for (var i = 0; i<thead_cells.length; i++) {
          if (thead_cells.item(i).getAttribute('value') == value) {
               return i;
          }
     }
     return -1;
}<|endoftext|>


<commit_before>const Promise = require('bluebird');
const chrono = require('chrono-node');
const moment = require('moment');
const _ = require('lodash');
const database = require('../../../database');

function reminder(message, sender) {
  if (message.length === 0) return Promise.resolve('Incorrect format. !remind <minutes> <message>');
  let msg;
  if (message.length === 1) {
    database.connection.query(`CALL get_rands(${1}, ${sender.channel.id})`, (err, result) => {
      if (result == null || result.length === 0 || result[0].length === 0) {
        msg = '';
      } else {
        msg = result[0][0].message;
      }
    });
  } else {
    msg = message.join(' ');
  }
  return new Promise((resolve) => {
    if (!isNaN(message[0])) {
      const time = _.parseInt(message[0]);
      if (time > 10080 || isNaN(time)) return resolve('Maximum time is 7 days (10080 minutes)');
      if (time < 1) return resolve('Time must be at least 1 minute.');
      setTimeout(() => {
        sender.reply(`:fire: REMEMBER: ${msg.split(' ').slice(1).join(' ')}! :fire:`);
      }, time * 60000);
      const minuteMsg = time === 1 ? 'minute' : 'minutes';
      return resolve(`Reminding you in ${time} ${minuteMsg}.`);
    }

    const results = chrono.parse(msg);
    if (results.length === 0) return resolve('Error parsing date. Try using format: !remind <minutes> <message>');

    let endTime = moment(results[0].start.date());
    const currentTime = new moment();
    let duration = moment.duration(endTime.diff(currentTime));
    let minutes = Math.round(duration.asMinutes());

    if (minutes < 1) {
      if (results[0].end) {
        endTime = results[0].end.date();
        duration = moment.duration(endTime.diff(currentTime));
        minutes = duration.asMinutes();
      }
      if (minutes < 1) {
        return resolve('Time must be at least 1 minute.');
      }
    }
    if (minutes > 10080) return resolve('Maximum time is 7 days (10080 minutes)');

    setTimeout(() => {
      sender.reply(`:fire: REMEMBER: "${msg}"! :fire:`);
    }, minutes * 60000);
    const minuteMsg = minutes === 1 ? 'minute' : 'minutes';
    return resolve(`Reminding you in ${minutes} ${minuteMsg}.`);
  });
}

module.exports = {
  remind: reminder,
  reminder,
  timer: reminder,
  alarm: reminder,
  alert: reminder
};
<commit_msg>Fix message parse<commit_after>const Promise = require('bluebird');
const chrono = require('chrono-node');
const moment = require('moment');
const _ = require('lodash');
const database = require('../../../database');

function reminder(message, sender) {
  if (message.length === 0) return Promise.resolve('Incorrect format. !remind <minutes> <message>');
  let msg;
  if (message.length === 1) {
    database.connection.query(`CALL get_rands(${1}, ${sender.channel.id})`, (err, result) => {
      if (result == null || result.length === 0 || result[0].length === 0) {
        msg = '';
      } else {
        msg = result[0][0].message;
      }
    });
  } else {
    msg = message.join(' ');
  }
  return new Promise((resolve) => {
    if (!isNaN(message[0])) {
      const time = _.parseInt(message[0]);
      if (time > 10080 || isNaN(time)) return resolve('Maximum time is 7 days (10080 minutes)');
      if (time < 1) return resolve('Time must be at least 1 minute.');
      setTimeout(() => {
        let reminderMsg = '';
        if (message.length === 1) {
          reminderMsg = msg;
        } else {
          reminderMsg = msg.split(' ').slice(1).join(' ');
        }
        sender.reply(`:fire: REMEMBER: ${reminderMsg}! :fire:`);
      }, time * 60000);
      const minuteMsg = time === 1 ? 'minute' : 'minutes';
      return resolve(`Reminding you in ${time} ${minuteMsg}.`);
    }

    const results = chrono.parse(msg);
    if (results.length === 0) return resolve('Error parsing date. Try using format: !remind <minutes> <message>');

    let endTime = moment(results[0].start.date());
    const currentTime = new moment();
    let duration = moment.duration(endTime.diff(currentTime));
    let minutes = Math.round(duration.asMinutes());

    if (minutes < 1) {
      if (results[0].end) {
        endTime = results[0].end.date();
        duration = moment.duration(endTime.diff(currentTime));
        minutes = duration.asMinutes();
      }
      if (minutes < 1) {
        return resolve('Time must be at least 1 minute.');
      }
    }
    if (minutes > 10080) return resolve('Maximum time is 7 days (10080 minutes)');

    setTimeout(() => {
      sender.reply(`:fire: REMEMBER: "${msg}"! :fire:`);
    }, minutes * 60000);
    const minuteMsg = minutes === 1 ? 'minute' : 'minutes';
    return resolve(`Reminding you in ${minutes} ${minuteMsg}.`);
  });
}

module.exports = {
  remind: reminder,
  reminder,
  timer: reminder,
  alarm: reminder,
  alert: reminder
};
<|endoftext|>


<commit_before>import Promise from 'bluebird';
import nconf from 'nconf';
import R from 'ramda';

import { getShardsCmdResults } from '../../redis';

function servers(client, evt, suffix, lang, json) {
  const server_count = {guilds: client.Guilds.length, channels: client.Channels.length, users: client.Users.length};

  if (nconf.get('SHARDING') && !json) {
    return getShardsCmdResults('servers')
      .then(R.append({results: server_count}))
      .then(R.pluck('results'))
      .reduce((sum, res) => R.zipObj(R.keys(res), R.map(key => sum[key] + res[key], R.keys(res))))
      .then(res => `Connected to ${res.guilds} servers, ${res.channels} channels and ${res.users} users.`);
  }

  if (json) return Promise.resolve(server_count);
  return Promise.resolve(`Connected to ${server_count.guilds} servers, ${server_count.channels} channels and ${server_count.users} users.`);
}

export const help = {servers: {}};
export default {
  servers,
  statistics: servers,
  stats: servers
};
<commit_msg>Delete servers.js<commit_after><|endoftext|>