www.berekenen.nl Open in urlscan Pro
185.58.56.175  Public Scan

URL: https://www.berekenen.nl/skin/default/cache/48881a8c8de1ae7a23bc0b2f812dd4991bhtugm.js
Submission: On April 18 via manual from NL — Scanned from NL

Form analysis 0 forms found in the DOM

Text Content

if(typeof(json)=='undefined'){
	function json(data, onsucces, onerror){
		var value = null;
		try {
			eval('value = ' + data + ';');
		}catch(e){
			onerror(e);
			return;
		}
		onsucces(value);
	}
}
if(typeof(json.get)=='undefined'){
	json.get = function(url, onsucces, onerror){
		$.get(url, function(response){
			json(response, onsucces, function(ex){ onerror(ex, response); });
		}, 'text');
	};
}
if(typeof(json.post)=='undefined'){
	json.post = function(url, data, onsucces, onerror){
		$.post(url, data, function(response){
			json(response, onsucces, function(ex){ onerror(ex, response); });
		}, 'text');
	};
}

function print_r(i,t){
	d = '';
	if(t==null) t='';
	if(i==null) return '(null)';	
	switch(i.constructor){
		case Number:
		case Boolean:
		case Date:
		{
			d+=i;
		}
		break;
		case Function:
		{
			d+=i.toString().replace('\n','').replace('\r','');
		}
		break;
		case String:
		{
			d+='"'+i+'"';
		}
		break;
		case Array:
		{
			d+='Array\n'+t+'(\n'+t;
			for(x in i){
				d+='  ['+x+'] = '+print_r(i[x],t+'    ')+'\n'+t;
			}
			d+=')';
		}
		break;
		case Object:
		{
			d+='Object\n'+t+'(\n'+t;
			for(x in i){
				d+='  ['+x+'] = '+print_r(i[x],t+'    ')+'\n'+t;
			}
			d+=')';
		}
		break;
		default:{
		  d+='Unknown: ' + i;
		  //alert('Error variable unknown:\n'+i.constructor);
        }
	}
	return d;
}


(function($) {
	$.fn.serializeForm = function(){
		var data = {};
		this.each(function() {
			var form = $(this);
			var items = form.find('select,input,textarea');
			for(var i=0; i<items.length; i++){
				var item = $(items[i]);
				var name = item.attr('name');
				if(name){
					if('checkbox|radio'.indexOf(item.attr('type'))>=0){
						if(item.prop('checked')){
							if(item.attr('value')){
								data[name] = item.val();
							}else{
								data[name] = 'on';
							}
						}
					}else {
						data[name] = item.val();
					}
				}
			}
		});
		return data;
	};
})(jQuery);

(function($) {
	$.fn.traverse = function(data, callback, namespace){
		var form = this;
		var __make = function(base, sub){
			if(!base) return sub;
			return base + '[' + sub + ']';
		};
		var __traverse = function(data, base, callback){
			for(key in data){
				var item = data[key];
	
				if(typeof(item)=='object'){
					__traverse(item, __make(base, key), callback);
				}else{
					var element = form.find('[name="' + __make(base, key) + '"]');
					callback(element, item);
				}
			}
		};
	
		__traverse(data, typeof(namespace)=='undefined' ? false : namespace, callback);
	};
})(jQuery);


/**
 * json_encode
 */
if(typeof(json_encode)=='undefined'){
	function json_string(text){
		text = text.replace(/\\/g,'\\\\').replace(/\'/g,'\\\'').replace(/\"/g,'\\"').replace(/\0/g,'\\0').replace(/\r\n/g,'\\n').replace(/\n/g,'\\n').replace(/\r/g,'\\r');
		
		var string = '';
		for(var i=0; i<text.length; i++){
			var c = text.charCodeAt(i);
			if(c >= 128){
				var value = c.toString(16);
				while(value.length < 4) value = '0' + value;
				string+= '\\u' + value;
			}else{
				string+= text.charAt(i);
			}
		}
		
		
		return '"' + (string) + '"';
	}
	function json_encode(value){
		if(value==null) return 'null';
		switch(value.constructor){
			case Boolean:  return value ? 'true' : 'false';
			case Number:   return value.toString();
			case Date:	 return json_encode(value.toString());
			case Function: return json_encode(value.toString());
			case String:   return json_string(value);
			case Array:
				var json = [];
				for(var i=0; i<value.length; i++){
					json.push(json_encode(value[i]));
				}
			return '[' + json.join(',') + ']';
			default:
			case Object:
				var json = [];
				for(key in value){
					json.push(json_encode(key.toString()) + ':' + json_encode(value[key]));
				}
				return '{' + json.join(',') + '}';
		}
	}
}

function select_set_values(selector, data, params){
	if(typeof(params.empty)=='undefined') params.empty = false;

	var select = $(selector);
	select.find('option').remove();

	if(params.empty) select.append($('<option>', { value : '' }).text(''));

	for(var x in data){
		var item = data[x];
		select.append($('<option>', { value : item[params.value] }).text(item[params.text]));
	}
	if(typeof(params.defaultValue)=='undefined'){
		select.val(params.defaultValue);
	}
	select.change();
}

function serialize(form){
	form = $(form);
	var data = {};
	var items = form.find('select,input,textarea');
	for(var i=0; i<items.length; i++){
		var item = $(items[i]);
		var name = item.attr('name');
		if(name){
			if('checkbox|radio'.indexOf(item.attr('type'))>=0){
				if(item.checked('type')){
					if(item.attr('value')){
						data[name] = item.val();
					}else{
						data[name] = 'on';
					}
				}
			}else {
				data[name] = item.val();
			}
		}
	}
	return data;
}

function traverse(data, callback, namespace){
	var __make = function(base, sub){
		if(!base) return sub;
		return base + '[' + sub + ']';
	};
	var __traverse = function(data, base, callback){
		for(key in data){
			var item = data[key];

			if(typeof(item)=='object'){
				__traverse(item, __make(base, key), callback);
			}else{
				callback(__make(base, key), item);
			}
		}
	};

	__traverse(data, typeof(namespace)=='undefined' ? false : namespace, callback);
}

/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-addtest-prefixed-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,e.prefixed=function(a,b,c){return b?J(a,b,c):J(a,"pfx")},g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};

(function($){
	$.fn.selectFancy = function(settings){
		var config = {
			emptySelect: true,
			className: null,
			multipleText: '%d geselecteerd'
		};
		if(settings) $.extend(config, settings);
		this.each(function(){
			var me			= $(this);
			var select		= me.find('> select');
			if(select.length <= 0) return;
			if(me.data('installed')){
				return;
			}
			me.data('installed', true);
			
			if(me.css('position')=='static') me.css('position', 'relative');
			select.css('z-index', 0).css('vissible', 'hidden');
			
			var container = $(document.createElement('span'));
			select.after(container);
			
			container.addClass('select-fancy-container');
			container.html('<span class="select-fancy-button"></span><span class="select-fancy-text"><span><span></span></span></span>');
			
			var list = $(document.createElement('div'));
			$(document.body).append(list);
			list.addClass('select-fancy-list');
			if(config.className) list.addClass(config.className);
			
			$(document.body).click(function(){
				if(list.hasClass('open')){
					list.removeClass('open');
					container.removeClass('open');
					select.change();
				}
			});
			
			var __onChange = function(){
				var active = select.find(':selected');
				if(active.length > 1){
					container.find('.select-fancy-text span span').text(config.multipleText.replace('%d', active.length));
				}else if(active.length == 1){
					container.find('.select-fancy-text span span').text(active.text());
				}else if(select.find('option').length > 0){
					container.find('.select-fancy-text span span').text(select.find(':first-child').text());
				}else{
					container.find('.select-fancy-text span span').text('');
				}
			};
			__onChange();
			
			var __onClick = function(evt){
				evt.preventDefault();
				evt.stopPropagation();
				if(list.hasClass('open')){
					list.removeClass('open');
					container.removeClass('open');
				}else{
					$('body > div.select-fancy-list.open,.select-fancy-container.open').removeClass('open');
					
					list.find('.select-fancy-list-item').remove();
					select.find('option').each(function(){
						var option = $(this);
						if(config.emptySelect==false && option.val()=='') return;
						
						var item = $(document.createElement('div'))
							.addClass('select-fancy-list-item')
							.text(option.text());
							
						if(option.prop('selected')) item.addClass('selected');
						
						item.click(function(evt){
							evt.stopPropagation();
							
							if(select.attr('multiple') && (evt.ctrlKey || evt.metaKey)){
								option.prop('selected', !option.prop('selected'));
								item[option.prop('selected') ? 'addClass' : 'removeClass']('selected');
							}else{
								select.val(option.val());
								list.removeClass('open');
								container.removeClass('open');
								select.change();
							}
						});
						list.append(item);
					});
					
					
					container.addClass('open');
					list.addClass('open');
					var offset = me.offset();
					list.css('left', offset.left);
					list.css('top', offset.top + me.height());
					list.css('min-width', me.width());
				}
			};
			
			select.change(__onChange);
			container.find('.select-fancy-text').click(__onClick);
			container.find('.select-fancy-button').click(__onClick);
		});
	};
})(jQuery);
/*!
 * selectivizr v1.0.2 - (c) Keith Clark, freely distributable under the terms of the MIT license.
 * selectivizr.com
 */
(function(j){function A(a){return a.replace(B,h).replace(C,function(a,d,b){for(var a=b.split(","),b=0,e=a.length;b<e;b++){var s=D(a[b].replace(E,h).replace(F,h))+o,l=[];a[b]=s.replace(G,function(a,b,c,d,e){if(b){if(l.length>0){var a=l,f,e=s.substring(0,e).replace(H,i);if(e==i||e.charAt(e.length-1)==o)e+="*";try{f=t(e)}catch(k){}if(f){e=0;for(c=f.length;e<c;e++){for(var d=f[e],h=d.className,j=0,m=a.length;j<m;j++){var g=a[j];if(!RegExp("(^|\\s)"+g.className+"(\\s|$)").test(d.className)&&g.b&&(g.b===!0||g.b(d)===!0))h=u(h,g.className,!0)}d.className=h}}l=[]}return b}else{if(b=c?I(c):!v||v.test(d)?{className:w(d),b:!0}:null)return l.push(b),"."+b.className;return a}})}return d+a.join(",")})}function I(a){var c=!0,d=w(a.slice(1)),b=a.substring(0,5)==":not(",e,f;b&&(a=a.slice(5,-1));var l=a.indexOf("(");l>-1&&(a=a.substring(0,l));if(a.charAt(0)==":")switch(a.slice(1)){case "root":c=function(a){return b?a!=p:a==p};break;case "target":if(m==8){c=function(a){function c(){var d=location.hash,e=d.slice(1);return b?d==i||a.id!=e:d!=i&&a.id==e}k(j,"hashchange",function(){g(a,d,c())});return c()};break}return!1;case "checked":c=function(a){J.test(a.type)&&k(a,"propertychange",function(){event.propertyName=="checked"&&g(a,d,a.checked!==b)});return a.checked!==b};break;case "disabled":b=!b;case "enabled":c=function(c){if(K.test(c.tagName))return k(c,"propertychange",function(){event.propertyName=="$disabled"&&g(c,d,c.a===b)}),q.push(c),c.a=c.disabled,c.disabled===b;return a==":enabled"?b:!b};break;case "focus":e="focus",f="blur";case "hover":e||(e="mouseenter",f="mouseleave");c=function(a){k(a,b?f:e,function(){g(a,d,!0)});k(a,b?e:f,function(){g(a,d,!1)});return b};break;default:if(!L.test(a))return!1}return{className:d,b:c}}function w(a){return M+"-"+(m==6&&N?O++:a.replace(P,function(a){return a.charCodeAt(0)}))}function D(a){return a.replace(x,h).replace(Q,o)}function g(a,c,d){var b=a.className,c=u(b,c,d);if(c!=b)a.className=c,a.parentNode.className+=i}function u(a,c,d){var b=RegExp("(^|\\s)"+c+"(\\s|$)"),e=b.test(a);return d?e?a:a+o+c:e?a.replace(b,h).replace(x,h):a}function k(a,c,d){a.attachEvent("on"+c,d)}function r(a,c){if(/^https?:\/\//i.test(a))return c.substring(0,c.indexOf("/",8))==a.substring(0,a.indexOf("/",8))?a:null;if(a.charAt(0)=="/")return c.substring(0,c.indexOf("/",8))+a;var d=c.split(/[?#]/)[0];a.charAt(0)!="?"&&d.charAt(d.length-1)!="/"&&(d=d.substring(0,d.lastIndexOf("/")+1));return d+a}function y(a){if(a)return n.open("GET",a,!1),n.send(),(n.status==200?n.responseText:i).replace(R,i).replace(S,function(c,d,b,e,f){return y(r(b||f,a))}).replace(T,function(c,d,b){d=d||i;return" url("+d+r(b,a)+d+") "});return i}function U(){var a,c;a=f.getElementsByTagName("BASE");for(var d=a.length>0?a[0].href:f.location.href,b=0;b<f.styleSheets.length;b++)if(c=f.styleSheets[b],c.href!=i&&(a=r(c.href,d)))c.cssText=A(y(a));q.length>0&&setInterval(function(){for(var a=0,c=q.length;a<c;a++){var b=q[a];if(b.disabled!==b.a)b.disabled?(b.disabled=!1,b.a=!0,b.disabled=!0):b.a=b.disabled}},250)}if(!/*@cc_on!@*/true){var f=document,p=f.documentElement,n=function(){if(j.XMLHttpRequest)return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(a){return null}}(),m=/MSIE (\d+)/.exec(navigator.userAgent)[1];if(!(f.compatMode!="CSS1Compat"||m<6||m>8||!n)){var z={NW:"*.Dom.select",MooTools:"$$",DOMAssistant:"*.$",Prototype:"$$",YAHOO:"*.util.Selector.query",Sizzle:"*",jQuery:"*",dojo:"*.query"},t,q=[],O=0,N=!0,M="slvzr",R=/(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)\s*/g,S=/@import\s*(?:(?:(?:url\(\s*(['"]?)(.*)\1)\s*\))|(?:(['"])(.*)\3))[^;]*;/g,T=/\burl\(\s*(["']?)(?!data:)([^"')]+)\1\s*\)/g,L=/^:(empty|(first|last|only|nth(-last)?)-(child|of-type))$/,B=/:(:first-(?:line|letter))/g,C=/(^|})\s*([^\{]*?[\[:][^{]+)/g,G=/([ +~>])|(:[a-z-]+(?:\(.*?\)+)?)|(\[.*?\])/g,H=/(:not\()?:(hover|enabled|disabled|focus|checked|target|active|visited|first-line|first-letter)\)?/g,P=/[^\w-]/g,K=/^(INPUT|SELECT|TEXTAREA|BUTTON)$/,J=/^(checkbox|radio)$/,v=m>6?/[\$\^*]=(['"])\1/:null,E=/([(\[+~])\s+/g,F=/\s+([)\]+~])/g,Q=/\s+/g,x=/^\s*((?:[\S\s]*\S)?)\s*$/,i="",o=" ",h="$1";(function(a,c){function d(){try{p.doScroll("left")}catch(a){setTimeout(d,50);return}b("poll")}function b(d){if(!(d.type=="readystatechange"&&f.readyState!="complete")&&((d.type=="load"?a:f).detachEvent("on"+d.type,b,!1),!e&&(e=!0)))c.call(a,d.type||d)}var e=!1,g=!0;if(f.readyState=="complete")c.call(a,i);else{if(f.createEventObject&&p.doScroll){try{g=!a.frameElement}catch(h){}g&&d()}k(f,"readystatechange",b);k(a,"load",b)}})(j,function(){for(var a in z){var c,d,b=j;if(j[a]){for(c=z[a].replace("*",a).split(".");(d=c.shift())&&(b=b[d]););if(typeof b=="function"){t=b;U();break}}}})}}})(this);
(function($){
	$.fn.smartSearch = function(settings){
		var config = {
		};
		
		if(settings) $.extend(config, settings);
		
		var __getValue = function(obj, key, def){
			if(typeof(obj[key])!='undefined'){
				if(typeof(obj[key])=='function'){
					var value = obj[key]();
					if(typeof(value)=='undefined') return def;
					return value;
				}
				return obj[key];
			}
			return def;
		};
	
		this.each(function(){
			var source = $(this);
			var popup  = $('<div class="smart-search"><ul></ul></div>');
			
			var instance = {
				index: -1,
				items: [],
				confirm:function(){
					if(instance.index < 0) return false;
					
					var item = instance.items[instance.index];
					if(typeof(item.url)!='undefined'){
						window.location = item.url;
					}else if(typeof(item.value)!='undefined'){
						source.val(item.value);
						if(typeof(config.onconfirm)!='undefined') return config.onconfirm();
					}else{
						source.val(item.text);
						if(typeof(config.onconfirm)!='undefined') return config.onconfirm();
					}
					return true;
				},
				search:function(){
					instance.index = -1;
					if(source.val().length > 0){
						config.search(source.val(), instance);
					}else{
						instance.setItems([]);
					}
				},
				setItems:function(items){
					var bounds = source.offset();
					bounds.top+= __getValue(config, 'top');
					bounds.left+= __getValue(config, 'left');
					bounds.width = __getValue(config, 'width', source.width());
					popup.css(bounds);
					
					instance.items = items;
					
					if(instance.items.length > 0){
						popup.css('display', 'block');
					}else{
						popup.css('display', 'none');
					}
					
					popup.find('> ul > li').remove();
					for(var i=0; i<Math.min(items.length, 10); i++){
						var item = items[i];
						var li = $(document.createElement('li'));
						li.text(item.text);
						li.hover(function(){
							instance.setActive(popup.find('> ul > li').index(this));
						});
						li.click(function(){
							instance.setActive(popup.find('> ul > li').index(this));
							instance.confirm();
							if(typeof(config.onclick)!='undefined') config.onclick(source);
						});
						popup.find('> ul').append(li);
					}
					
					if(items.length==1) instance.setActive(0);
				},
				setActive:function(index){
					instance.index = Math.max(-1, Math.min(index, instance.items.length - 1));
					
					popup.find('> ul > li.active').removeClass('active');
					
					if(instance.index>=0){
						$(popup.find('> ul > li')[instance.index]).addClass('active');
					}
				}
			};
			
			source.attr('autocomplete', 'off');
			source.keydown(function(evt){
				if(evt.keyCode==38){
					evt.preventDefault();
					instance.setActive(instance.index - 1);
				}else if(evt.keyCode==40){
					evt.preventDefault();
					instance.setActive(instance.index + 1);
				}else if(evt.keyCode==13){
					if(instance.confirm()){
						evt.preventDefault();
					}
				}else if(evt.keyCode!=37 && evt.keyCode!=39){
					setTimeout(function(){
						instance.search();
					}, 10);
				}
			});
			
			$(document.body).append(popup);
		});
	};
})(jQuery);
(function($){
	$.fn.dialog = function(settings){
		var config = {
			trigger:function(source, dialog){
				source.click(function(evt){
					evt.preventDefault();
					dialog.open();
				});
			}
		};
		
		if(settings) $.extend(config, settings);
	
		this.each(function(){
			var source = $(this);
			var dialog = {
				open:function(){
					var me = this;
					$('body > .dialog').remove();
					$('body').append('<div class="dialog"><div><div><div class="window"><a href="javascript:void(0)">X</a><div></div></div></div></div></div>');
					$('body > .dialog .window > a').click(function(){ me.close(); });
					config.content(source, dialog);
				},
				setContent:function(html){
					$('body > .dialog > div > div > .window > div')[0].innerHTML = html;
					return $('body > .dialog > div > div > .window > div');
				},
				setCloseText:function(text){
					$('body > .dialog > div > div > .window > a').text(text);
				},
				addClass:function(className){
					$('body > .dialog').addClass(className);
				},
				setWidth:function(width){
					width = parseInt(width);
					var body = $('.dialog .window > div');
					if(body.css('padding-left').match(/(\d+(\.\d+)?)px/i)) width+= parseInt(body.css('padding-left').match(/(\d+(\.\d+)?)px/i)[1]);
					if(body.css('padding-right').match(/(\d+(\.\d+)?)px/i)) width+= parseInt(body.css('padding-right').match(/(\d+(\.\d+)?)px/i)[1]);
					$('.dialog .window').width(width);
				},
				show:function(html){
					$('body').addClass('dialog');
				},
				hide:function(){
					$('body').removeClass('dialog');
				},
				close:function(html){
					this.hide();
					$('body > .dialog').remove();
				},
				find:function(selector){
					return $('.dialog .window > div').find(selector);
				}
			};
			
			config.trigger(source, dialog);
		});
		return this;
	};
})(jQuery);

jQuery.dialog = function(settings){
	settings.trigger = function(source, dialog){ dialog.open(); };
	$(window).dialog(settings);
};
(function($) {
  $.fn.caret = function(pos) {
    var target = this[0];
	var isContentEditable = target.contentEditable === 'true';
    //get
    if (arguments.length == 0) {
      //HTML5
      if (window.getSelection) {
        //contenteditable
        if (isContentEditable) {
          target.focus();
          var range1 = window.getSelection().getRangeAt(0),
              range2 = range1.cloneRange();
          range2.selectNodeContents(target);
          range2.setEnd(range1.endContainer, range1.endOffset);
          return range2.toString().length;
        }
        //textarea
        return target.selectionStart;
      }
      //IE<9
      if (document.selection) {
        target.focus();
        //contenteditable
        if (isContentEditable) {
            var range1 = document.selection.createRange(),
                range2 = document.body.createTextRange();
            range2.moveToElementText(target);
            range2.setEndPoint('EndToEnd', range1);
            return range2.text.length;
        }
        //textarea
        var pos = 0,
            range = target.createTextRange(),
            range2 = document.selection.createRange().duplicate(),
            bookmark = range2.getBookmark();
        range.moveToBookmark(bookmark);
        while (range.moveStart('character', -1) !== 0) pos++;
        return pos;
      }
      //not supported
      return 0;
    }
    //set
    if (pos == -1)
      pos = this[isContentEditable? 'text' : 'val']().length;
    //HTML5
    if (window.getSelection) {
      //contenteditable
      if (isContentEditable) {
        target.focus();
        window.getSelection().collapse(target.firstChild, pos);
      }
      //textarea
      else
        target.setSelectionRange(pos, pos);
    }
    //IE<9
    else if (document.body.createTextRange) {
      var range = document.body.createTextRange();
      range.moveToElementText(target);
      range.moveStart('character', pos);
      range.collapse(true);
      range.select();
    }
    if (!isContentEditable)
      target.focus();
    return pos;
  };
})(jQuery);
/**
 *
 * Color picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 */
(function ($) {
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			visible,
			tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
			defaults = {
				eventName: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: 'ff0000',
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(4).val(hsb.h).end()
					.eq(5).val(hsb.s).end()
					.eq(6).val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(0).val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			keyDown = function (ev) {
				var pressedKey = ev.charCode || ev.keyCode || -1;
				if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
					return false;
				}
				var cal = $(this).parent().parent();
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parent().parent();
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
			},
			focus = function () {
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colorpicker').livePreview					
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(4)
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerId'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			}, 
			HexToRGB = function (hex) {
				var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
				return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {
					h: 0,
					s: 0,
					b: 0
				};
				var min = Math.min(rgb.r, rgb.g, rgb.b);
				var max = Math.max(rgb.r, rgb.g, rgb.b);
				var delta = max - min;
				hsb.b = max;
				if (max != 0) {
					
				}
				hsb.s = max != 0 ? 255 * delta / max : 0;
				if (hsb.s != 0) {
					if (rgb.r == max) {
						hsb.h = (rgb.g - rgb.b) / delta;
					} else if (rgb.g == max) {
						hsb.h = 2 + (rgb.b - rgb.r) / delta;
					} else {
						hsb.h = 4 + (rgb.r - rgb.g) / delta;
					}
				} else {
					hsb.h = -1;
				}
				hsb.h *= 60;
				if (hsb.h < 0) {
					hsb.h += 360;
				}
				hsb.s *= 100/255;
				hsb.b *= 100/255;
				return hsb;
			},
			HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if(s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			},
			restoreOriginal = function () {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').origColor;
				cal.data('colorpicker').color = col;
				fillRGBFields(col, cal.get(0));
				fillHexFields(col, cal.get(0));
				fillHSBFields(col, cal.get(0));
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
			};
		return {
			init: function (opt) {
				opt = $.extend({}, defaults, opt||{});
				if (typeof opt.color == 'string') {
					opt.color = HexToHSB(opt.color);
				} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
					opt.color = RGBToHSB(opt.color);
				} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
					opt.color = fixHSB(opt.color);
				} else {
					return this;
				}
				return this.each(function () {
					if (!$(this).data('colorpickerId')) {
						var options = $.extend({}, opt);
						options.origColor = opt.color;
						var id = 'collorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerId', id);
						var cal = $(tpl).attr('id', id);
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keyup', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal
							.find('span').bind('mousedown', downIncrement).end()
							.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.el = this;
						options.hue = cal.find('div.colorpicker_hue div');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('div.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						$('#' + $(this).data('colorpickerId')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(col);
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerId')) {
						var cal = $('#' + $(this).data('colorpickerId'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hidePicker,
		ColorPickerShow: ColorPicker.showPicker,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery);
/*!
 * pickadate.js v3.5.6, 2015/04/20
 * By Amsul, http://amsul.ca
 * Hosted on http://amsul.github.io/pickadate.js
 * Licensed under MIT
 */

(function ( factory ) {

    // AMD.
    if ( typeof define == 'function' && define.amd )
        define( 'picker', ['jquery'], factory )

    // Node.js/browserify.
    else if ( typeof exports == 'object' )
        module.exports = factory( require('jquery') )

    // Browser globals.
    else this.Picker = factory( jQuery )

}(function( $ ) {

var $window = $( window )
var $document = $( document )
var $html = $( document.documentElement )
var supportsTransitions = document.documentElement.style.transition != null


/**
 * The picker constructor that creates a blank picker.
 */
function PickerConstructor( ELEMENT, NAME, COMPONENT, OPTIONS ) {

    // If there’s no element, return the picker constructor.
    if ( !ELEMENT ) return PickerConstructor


    var
        IS_DEFAULT_THEME = false,


        // The state of the picker.
        STATE = {
            id: ELEMENT.id || 'P' + Math.abs( ~~(Math.random() * new Date()) )
        },


        // Merge the defaults and options passed.
        SETTINGS = COMPONENT ? $.extend( true, {}, COMPONENT.defaults, OPTIONS ) : OPTIONS || {},


        // Merge the default classes with the settings classes.
        CLASSES = $.extend( {}, PickerConstructor.klasses(), SETTINGS.klass ),


        // The element node wrapper into a jQuery object.
        $ELEMENT = $( ELEMENT ),


        // Pseudo picker constructor.
        PickerInstance = function() {
            return this.start()
        },


        // The picker prototype.
        P = PickerInstance.prototype = {

            constructor: PickerInstance,

            $node: $ELEMENT,


            /**
             * Initialize everything
             */
            start: function() {

                // If it’s already started, do nothing.
                if ( STATE && STATE.start ) return P


                // Update the picker states.
                STATE.methods = {}
                STATE.start = true
                STATE.open = false
                STATE.type = ELEMENT.type


                // Confirm focus state, convert into text input to remove UA stylings,
                // and set as readonly to prevent keyboard popup.
                ELEMENT.autofocus = ELEMENT == getActiveElement()
                ELEMENT.readOnly = !SETTINGS.editable
                ELEMENT.id = ELEMENT.id || STATE.id
                if ( ELEMENT.type != 'text' ) {
                    ELEMENT.type = 'text'
                }


                // Create a new picker component with the settings.
                P.component = new COMPONENT(P, SETTINGS)


                // Create the picker root and then prepare it.
                P.$root = $( '<div class="' + CLASSES.picker + '" id="' + ELEMENT.id + '_root" />' )
                prepareElementRoot()


                // Create the picker holder and then prepare it.
                P.$holder = $( createWrappedComponent() ).appendTo( P.$root )
                prepareElementHolder()


                // If there’s a format for the hidden input element, create the element.
                if ( SETTINGS.formatSubmit ) {
                    prepareElementHidden()
                }


                // Prepare the input element.
                prepareElement()


                // Insert the hidden input as specified in the settings.
                if ( SETTINGS.containerHidden ) $( SETTINGS.containerHidden ).append( P._hidden )
                else $ELEMENT.after( P._hidden )


                // Insert the root as specified in the settings.
                if ( SETTINGS.container ) $( SETTINGS.container ).append( P.$root )
                else $ELEMENT.after( P.$root )


                // Bind the default component and settings events.
                P.on({
                    start: P.component.onStart,
                    render: P.component.onRender,
                    stop: P.component.onStop,
                    open: P.component.onOpen,
                    close: P.component.onClose,
                    set: P.component.onSet
                }).on({
                    start: SETTINGS.onStart,
                    render: SETTINGS.onRender,
                    stop: SETTINGS.onStop,
                    open: SETTINGS.onOpen,
                    close: SETTINGS.onClose,
                    set: SETTINGS.onSet
                })


                // Once we’re all set, check the theme in use.
                IS_DEFAULT_THEME = isUsingDefaultTheme( P.$holder[0] )


                // If the element has autofocus, open the picker.
                if ( ELEMENT.autofocus ) {
                    P.open()
                }


                // Trigger queued the “start” and “render” events.
                return P.trigger( 'start' ).trigger( 'render' )
            }, //start


            /**
             * Render a new picker
             */
            render: function( entireComponent ) {

                // Insert a new component holder in the root or box.
                if ( entireComponent ) {
                    P.$holder = $( createWrappedComponent() )
                    prepareElementHolder()
                    P.$root.html( P.$holder )
                }
                else P.$root.find( '.' + CLASSES.box ).html( P.component.nodes( STATE.open ) )

                // Trigger the queued “render” events.
                return P.trigger( 'render' )
            }, //render


            /**
             * Destroy everything
             */
            stop: function() {

                // If it’s already stopped, do nothing.
                if ( !STATE.start ) return P

                // Then close the picker.
                P.close()

                // Remove the hidden field.
                if ( P._hidden ) {
                    P._hidden.parentNode.removeChild( P._hidden )
                }

                // Remove the root.
                P.$root.remove()

                // Remove the input class, remove the stored data, and unbind
                // the events (after a tick for IE - see `P.close`).
                $ELEMENT.removeClass( CLASSES.input ).removeData( NAME )
                setTimeout( function() {
                    $ELEMENT.off( '.' + STATE.id )
                }, 0)

                // Restore the element state
                ELEMENT.type = STATE.type
                ELEMENT.readOnly = false

                // Trigger the queued “stop” events.
                P.trigger( 'stop' )

                // Reset the picker states.
                STATE.methods = {}
                STATE.start = false

                return P
            }, //stop


            /**
             * Open up the picker
             */
            open: function( dontGiveFocus ) {

                // If it’s already open, do nothing.
                if ( STATE.open ) return P

                // Add the “active” class.
                $ELEMENT.addClass( CLASSES.active )
                aria( ELEMENT, 'expanded', true )

                // * A Firefox bug, when `html` has `overflow:hidden`, results in
                //   killing transitions :(. So add the “opened” state on the next tick.
                //   Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
                setTimeout( function() {

                    // Add the “opened” class to the picker root.
                    P.$root.addClass( CLASSES.opened )
                    aria( P.$root[0], 'hidden', false )

                }, 0 )

                // If we have to give focus, bind the element and doc events.
                if ( dontGiveFocus !== false ) {

                    // Set it as open.
                    STATE.open = true

                    // Prevent the page from scrolling.
                    if ( IS_DEFAULT_THEME ) {
                        $html.
                            css( 'overflow', 'hidden' ).
                            css( 'padding-right', '+=' + getScrollbarWidth() )
                    }

                    // Pass focus to the root element’s jQuery object.
                    focusPickerOnceOpened()

                    // Bind the document events.
                    $document.on( 'click.' + STATE.id + ' focusin.' + STATE.id, function( event ) {

                        var target = event.target

                        // If the target of the event is not the element, close the picker picker.
                        // * Don’t worry about clicks or focusins on the root because those don’t bubble up.
                        //   Also, for Firefox, a click on an `option` element bubbles up directly
                        //   to the doc. So make sure the target wasn't the doc.
                        // * In Firefox stopPropagation() doesn’t prevent right-click events from bubbling,
                        //   which causes the picker to unexpectedly close when right-clicking it. So make
                        //   sure the event wasn’t a right-click.
                        if ( target != ELEMENT && target != document && event.which != 3 ) {

                            // If the target was the holder that covers the screen,
                            // keep the element focused to maintain tabindex.
                            P.close( target === P.$holder[0] )
                        }

                    }).on( 'keydown.' + STATE.id, function( event ) {

                        var
                            // Get the keycode.
                            keycode = event.keyCode,

                            // Translate that to a selection change.
                            keycodeToMove = P.component.key[ keycode ],

                            // Grab the target.
                            target = event.target


                        // On escape, close the picker and give focus.
                        if ( keycode == 27 ) {
                            P.close( true )
                        }


                        // Check if there is a key movement or “enter” keypress on the element.
                        else if ( target == P.$holder[0] && ( keycodeToMove || keycode == 13 ) ) {

                            // Prevent the default action to stop page movement.
                            event.preventDefault()

                            // Trigger the key movement action.
                            if ( keycodeToMove ) {
                                PickerConstructor._.trigger( P.component.key.go, P, [ PickerConstructor._.trigger( keycodeToMove ) ] )
                            }

                            // On “enter”, if the highlighted item isn’t disabled, set the value and close.
                            else if ( !P.$root.find( '.' + CLASSES.highlighted ).hasClass( CLASSES.disabled ) ) {
                                P.set( 'select', P.component.item.highlight )
                                if ( SETTINGS.closeOnSelect ) {
                                    P.close( true )
                                }
                            }
                        }


                        // If the target is within the root and “enter” is pressed,
                        // prevent the default action and trigger a click on the target instead.
                        else if ( $.contains( P.$root[0], target ) && keycode == 13 ) {
                            event.preventDefault()
                            target.click()
                        }
                    })
                }

                // Trigger the queued “open” events.
                return P.trigger( 'open' )
            }, //open


            /**
             * Close the picker
             */
            close: function( giveFocus ) {

                // If we need to give focus, do it before changing states.
                if ( giveFocus ) {
                    if ( SETTINGS.editable ) {
                        ELEMENT.focus()
                    }
                    else {
                        // ....ah yes! It would’ve been incomplete without a crazy workaround for IE :|
                        // The focus is triggered *after* the close has completed - causing it
                        // to open again. So unbind and rebind the event at the next tick.
                        P.$holder.off( 'focus.toOpen' ).focus()
                        setTimeout( function() {
                            P.$holder.on( 'focus.toOpen', handleFocusToOpenEvent )
                        }, 0 )
                    }
                }

                // Remove the “active” class.
                $ELEMENT.removeClass( CLASSES.active )
                aria( ELEMENT, 'expanded', false )

                // * A Firefox bug, when `html` has `overflow:hidden`, results in
                //   killing transitions :(. So remove the “opened” state on the next tick.
                //   Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=625289
                setTimeout( function() {

                    // Remove the “opened” and “focused” class from the picker root.
                    P.$root.removeClass( CLASSES.opened + ' ' + CLASSES.focused )
                    aria( P.$root[0], 'hidden', true )

                }, 0 )

                // If it’s already closed, do nothing more.
                if ( !STATE.open ) return P

                // Set it as closed.
                STATE.open = false

                // Allow the page to scroll.
                if ( IS_DEFAULT_THEME ) {
                    $html.
                        css( 'overflow', '' ).
                        css( 'padding-right', '-=' + getScrollbarWidth() )
                }

                // Unbind the document events.
                $document.off( '.' + STATE.id )

                // Trigger the queued “close” events.
                return P.trigger( 'close' )
            }, //close


            /**
             * Clear the values
             */
            clear: function( options ) {
                return P.set( 'clear', null, options )
            }, //clear


            /**
             * Set something
             */
            set: function( thing, value, options ) {

                var thingItem, thingValue,
                    thingIsObject = $.isPlainObject( thing ),
                    thingObject = thingIsObject ? thing : {}

                // Make sure we have usable options.
                options = thingIsObject && $.isPlainObject( value ) ? value : options || {}

                if ( thing ) {

                    // If the thing isn’t an object, make it one.
                    if ( !thingIsObject ) {
                        thingObject[ thing ] = value
                    }

                    // Go through the things of items to set.
                    for ( thingItem in thingObject ) {

                        // Grab the value of the thing.
                        thingValue = thingObject[ thingItem ]

                        // First, if the item exists and there’s a value, set it.
                        if ( thingItem in P.component.item ) {
                            if ( thingValue === undefined ) thingValue = null
                            P.component.set( thingItem, thingValue, options )
                        }

                        // Then, check to update the element value and broadcast a change.
                        if ( thingItem == 'select' || thingItem == 'clear' ) {
                            $ELEMENT.
                                val( thingItem == 'clear' ? '' : P.get( thingItem, SETTINGS.format ) ).
                                trigger( 'change' )
                        }
                    }

                    // Render a new picker.
                    P.render()
                }

                // When the method isn’t muted, trigger queued “set” events and pass the `thingObject`.
                return options.muted ? P : P.trigger( 'set', thingObject )
            }, //set


            /**
             * Get something
             */
            get: function( thing, format ) {

                // Make sure there’s something to get.
                thing = thing || 'value'

                // If a picker state exists, return that.
                if ( STATE[ thing ] != null ) {
                    return STATE[ thing ]
                }

                // Return the submission value, if that.
                if ( thing == 'valueSubmit' ) {
                    if ( P._hidden ) {
                        return P._hidden.value
                    }
                    thing = 'value'
                }

                // Return the value, if that.
                if ( thing == 'value' ) {
                    return ELEMENT.value
                }

                // Check if a component item exists, return that.
                if ( thing in P.component.item ) {
                    if ( typeof format == 'string' ) {
                        var thingValue = P.component.get( thing )
                        return thingValue ?
                            PickerConstructor._.trigger(
                                P.component.formats.toString,
                                P.component,
                                [ format, thingValue ]
                            ) : ''
                    }
                    return P.component.get( thing )
                }
            }, //get



            /**
             * Bind events on the things.
             */
            on: function( thing, method, internal ) {

                var thingName, thingMethod,
                    thingIsObject = $.isPlainObject( thing ),
                    thingObject = thingIsObject ? thing : {}

                if ( thing ) {

                    // If the thing isn’t an object, make it one.
                    if ( !thingIsObject ) {
                        thingObject[ thing ] = method
                    }

                    // Go through the things to bind to.
                    for ( thingName in thingObject ) {

                        // Grab the method of the thing.
                        thingMethod = thingObject[ thingName ]

                        // If it was an internal binding, prefix it.
                        if ( internal ) {
                            thingName = '_' + thingName
                        }

                        // Make sure the thing methods collection exists.
                        STATE.methods[ thingName ] = STATE.methods[ thingName ] || []

                        // Add the method to the relative method collection.
                        STATE.methods[ thingName ].push( thingMethod )
                    }
                }

                return P
            }, //on



            /**
             * Unbind events on the things.
             */
            off: function() {
                var i, thingName,
                    names = arguments;
                for ( i = 0, namesCount = names.length; i < namesCount; i += 1 ) {
                    thingName = names[i]
                    if ( thingName in STATE.methods ) {
                        delete STATE.methods[thingName]
                    }
                }
                return P
            },


            /**
             * Fire off method events.
             */
            trigger: function( name, data ) {
                var _trigger = function( name ) {
                    var methodList = STATE.methods[ name ]
                    if ( methodList ) {
                        methodList.map( function( method ) {
                            PickerConstructor._.trigger( method, P, [ data ] )
                        })
                    }
                }
                _trigger( '_' + name )
                _trigger( name )
                return P
            } //trigger
        } //PickerInstance.prototype


    /**
     * Wrap the picker holder components together.
     */
    function createWrappedComponent() {

        // Create a picker wrapper holder
        return PickerConstructor._.node( 'div',

            // Create a picker wrapper node
            PickerConstructor._.node( 'div',

                // Create a picker frame
                PickerConstructor._.node( 'div',

                    // Create a picker box node
                    PickerConstructor._.node( 'div',

                        // Create the components nodes.
                        P.component.nodes( STATE.open ),

                        // The picker box class
                        CLASSES.box
                    ),

                    // Picker wrap class
                    CLASSES.wrap
                ),

                // Picker frame class
                CLASSES.frame
            ),

            // Picker holder class
            CLASSES.holder,

            'tabindex="-1"'
        ) //endreturn
    } //createWrappedComponent



    /**
     * Prepare the input element with all bindings.
     */
    function prepareElement() {

        $ELEMENT.

            // Store the picker data by component name.
            data(NAME, P).

            // Add the “input” class name.
            addClass(CLASSES.input).

            // If there’s a `data-value`, update the value of the element.
            val( $ELEMENT.data('value') ?
                P.get('select', SETTINGS.format) :
                ELEMENT.value
            )


        // Only bind keydown events if the element isn’t editable.
        if ( !SETTINGS.editable ) {

            $ELEMENT.

                // On focus/click, open the picker.
                on( 'focus.' + STATE.id + ' click.' + STATE.id, function(event) {
                    event.preventDefault()
                    P.open()
                }).

                // Handle keyboard event based on the picker being opened or not.
                on( 'keydown.' + STATE.id, handleKeydownEvent )
        }


        // Update the aria attributes.
        aria(ELEMENT, {
            haspopup: true,
            expanded: false,
            readonly: false,
            owns: ELEMENT.id + '_root'
        })
    }


    /**
     * Prepare the root picker element with all bindings.
     */
    function prepareElementRoot() {
        aria( P.$root[0], 'hidden', true )
    }


     /**
      * Prepare the holder picker element with all bindings.
      */
    function prepareElementHolder() {

        P.$holder.

            on({

                // For iOS8.
                keydown: handleKeydownEvent,

                'focus.toOpen': handleFocusToOpenEvent,

                blur: function() {
                    // Remove the “target” class.
                    $ELEMENT.removeClass( CLASSES.target )
                },

                // When something within the holder is focused, stop from bubbling
                // to the doc and remove the “focused” state from the root.
                focusin: function( event ) {
                    P.$root.removeClass( CLASSES.focused )
                    event.stopPropagation()
                },

                // When something within the holder is clicked, stop it
                // from bubbling to the doc.
                'mousedown click': function( event ) {

                    var target = event.target

                    // Make sure the target isn’t the root holder so it can bubble up.
                    if ( target != P.$holder[0] ) {

                        event.stopPropagation()

                        // * For mousedown events, cancel the default action in order to
                        //   prevent cases where focus is shifted onto external elements
                        //   when using things like jQuery mobile or MagnificPopup (ref: #249 & #120).
                        //   Also, for Firefox, don’t prevent action on the `option` element.
                        if ( event.type == 'mousedown' && !$( target ).is( 'input, select, textarea, button, option' )) {

                            event.preventDefault()

                            // Re-focus onto the holder so that users can click away
                            // from elements focused within the picker.
                            P.$holder[0].focus()
                        }
                    }
                }

            }).

            // If there’s a click on an actionable element, carry out the actions.
            on( 'click', '[data-pick], [data-nav], [data-clear], [data-close]', function() {

                var $target = $( this ),
                    targetData = $target.data(),
                    targetDisabled = $target.hasClass( CLASSES.navDisabled ) || $target.hasClass( CLASSES.disabled ),

                    // * For IE, non-focusable elements can be active elements as well
                    //   (http://stackoverflow.com/a/2684561).
                    activeElement = getActiveElement()
                    activeElement = activeElement && ( activeElement.type || activeElement.href )

                // If it’s disabled or nothing inside is actively focused, re-focus the element.
                if ( targetDisabled || activeElement && !$.contains( P.$root[0], activeElement ) ) {
                    P.$holder[0].focus()
                }

                // If something is superficially changed, update the `highlight` based on the `nav`.
                if ( !targetDisabled && targetData.nav ) {
                    P.set( 'highlight', P.component.item.highlight, { nav: targetData.nav } )
                }

                // If something is picked, set `select` then close with focus.
                else if ( !targetDisabled && 'pick' in targetData ) {
                    P.set( 'select', targetData.pick )
                    if ( SETTINGS.closeOnSelect ) {
                        P.close( true )
                    }
                }

                // If a “clear” button is pressed, empty the values and close with focus.
                else if ( targetData.clear ) {
                    P.clear()
                    if ( SETTINGS.closeOnClear ) {
                        P.close( true )
                    }
                }

                else if ( targetData.close ) {
                    P.close( true )
                }

            }) //P.$holder

    }


     /**
      * Prepare the hidden input element along with all bindings.
      */
    function prepareElementHidden() {

        var name

        if ( SETTINGS.hiddenName === true ) {
            name = ELEMENT.name
            ELEMENT.name = ''
        }
        else {
            name = [
                typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '',
                typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'
            ]
            name = name[0] + ELEMENT.name + name[1]
        }

        P._hidden = $(
            '<input ' +
            'type=hidden ' +

            // Create the name using the original input’s with a prefix and suffix.
            'name="' + name + '"' +

            // If the element has a value, set the hidden value as well.
            (
                $ELEMENT.data('value') || ELEMENT.value ?
                    ' value="' + P.get('select', SETTINGS.formatSubmit) + '"' :
                    ''
            ) +
            '>'
        )[0]

        $ELEMENT.

            // If the value changes, update the hidden input with the correct format.
            on('change.' + STATE.id, function() {
                P._hidden.value = ELEMENT.value ?
                    P.get('select', SETTINGS.formatSubmit) :
                    ''
            })
    }


    // Wait for transitions to end before focusing the holder. Otherwise, while
    // using the `container` option, the view jumps to the container.
    function focusPickerOnceOpened() {

        if (IS_DEFAULT_THEME && supportsTransitions) {
            P.$holder.find('.' + CLASSES.frame).one('transitionend', function() {
                P.$holder[0].focus()
            })
        }
        else {
            P.$holder[0].focus()
        }
    }


    function handleFocusToOpenEvent(event) {

        // Stop the event from propagating to the doc.
        event.stopPropagation()

        // Add the “target” class.
        $ELEMENT.addClass( CLASSES.target )

        // Add the “focused” class to the root.
        P.$root.addClass( CLASSES.focused )

        // And then finally open the picker.
        P.open()
    }


    // For iOS8.
    function handleKeydownEvent( event ) {

        var keycode = event.keyCode,

            // Check if one of the delete keys was pressed.
            isKeycodeDelete = /^(8|46)$/.test(keycode)

        // For some reason IE clears the input value on “escape”.
        if ( keycode == 27 ) {
            P.close( true )
            return false
        }

        // Check if `space` or `delete` was pressed or the picker is closed with a key movement.
        if ( keycode == 32 || isKeycodeDelete || !STATE.open && P.component.key[keycode] ) {

            // Prevent it from moving the page and bubbling to doc.
            event.preventDefault()
            event.stopPropagation()

            // If `delete` was pressed, clear the values and close the picker.
            // Otherwise open the picker.
            if ( isKeycodeDelete ) { P.clear().close() }
            else { P.open() }
        }
    }


    // Return a new picker instance.
    return new PickerInstance()
} //PickerConstructor



/**
 * The default classes and prefix to use for the HTML classes.
 */
PickerConstructor.klasses = function( prefix ) {
    prefix = prefix || 'picker'
    return {

        picker: prefix,
        opened: prefix + '--opened',
        focused: prefix + '--focused',

        input: prefix + '__input',
        active: prefix + '__input--active',
        target: prefix + '__input--target',

        holder: prefix + '__holder',

        frame: prefix + '__frame',
        wrap: prefix + '__wrap',

        box: prefix + '__box'
    }
} //PickerConstructor.klasses



/**
 * Check if the default theme is being used.
 */
function isUsingDefaultTheme( element ) {

    var theme,
        prop = 'position'

    // For IE.
    if ( element.currentStyle ) {
        theme = element.currentStyle[prop]
    }

    // For normal browsers.
    else if ( window.getComputedStyle ) {
        theme = getComputedStyle( element )[prop]
    }

    return theme == 'fixed'
}



/**
 * Get the width of the browser’s scrollbar.
 * Taken from: https://github.com/VodkaBears/Remodal/blob/master/src/jquery.remodal.js
 */
function getScrollbarWidth() {

    if ( $html.height() <= $window.height() ) {
        return 0
    }

    var $outer = $( '<div style="visibility:hidden;width:100px" />' ).
        appendTo( 'body' )

    // Get the width without scrollbars.
    var widthWithoutScroll = $outer[0].offsetWidth

    // Force adding scrollbars.
    $outer.css( 'overflow', 'scroll' )

    // Add the inner div.
    var $inner = $( '<div style="width:100%" />' ).appendTo( $outer )

    // Get the width with scrollbars.
    var widthWithScroll = $inner[0].offsetWidth

    // Remove the divs.
    $outer.remove()

    // Return the difference between the widths.
    return widthWithoutScroll - widthWithScroll
}



/**
 * PickerConstructor helper methods.
 */
PickerConstructor._ = {

    /**
     * Create a group of nodes. Expects:
     * `
        {
            min:    {Integer},
            max:    {Integer},
            i:      {Integer},
            node:   {String},
            item:   {Function}
        }
     * `
     */
    group: function( groupObject ) {

        var
            // Scope for the looped object
            loopObjectScope,

            // Create the nodes list
            nodesList = '',

            // The counter starts from the `min`
            counter = PickerConstructor._.trigger( groupObject.min, groupObject )


        // Loop from the `min` to `max`, incrementing by `i`
        for ( ; counter <= PickerConstructor._.trigger( groupObject.max, groupObject, [ counter ] ); counter += groupObject.i ) {

            // Trigger the `item` function within scope of the object
            loopObjectScope = PickerConstructor._.trigger( groupObject.item, groupObject, [ counter ] )

            // Splice the subgroup and create nodes out of the sub nodes
            nodesList += PickerConstructor._.node(
                groupObject.node,
                loopObjectScope[ 0 ],   // the node
                loopObjectScope[ 1 ],   // the classes
                loopObjectScope[ 2 ]    // the attributes
            )
        }

        // Return the list of nodes
        return nodesList
    }, //group


    /**
     * Create a dom node string
     */
    node: function( wrapper, item, klass, attribute ) {

        // If the item is false-y, just return an empty string
        if ( !item ) return ''

        // If the item is an array, do a join
        item = $.isArray( item ) ? item.join( '' ) : item

        // Check for the class
        klass = klass ? ' class="' + klass + '"' : ''

        // Check for any attributes
        attribute = attribute ? ' ' + attribute : ''

        // Return the wrapped item
        return '<' + wrapper + klass + attribute + '>' + item + '</' + wrapper + '>'
    }, //node


    /**
     * Lead numbers below 10 with a zero.
     */
    lead: function( number ) {
        return ( number < 10 ? '0': '' ) + number
    },


    /**
     * Trigger a function otherwise return the value.
     */
    trigger: function( callback, scope, args ) {
        return typeof callback == 'function' ? callback.apply( scope, args || [] ) : callback
    },


    /**
     * If the second character is a digit, length is 2 otherwise 1.
     */
    digits: function( string ) {
        return ( /\d/ ).test( string[ 1 ] ) ? 2 : 1
    },


    /**
     * Tell if something is a date object.
     */
    isDate: function( value ) {
        return {}.toString.call( value ).indexOf( 'Date' ) > -1 && this.isInteger( value.getDate() )
    },


    /**
     * Tell if something is an integer.
     */
    isInteger: function( value ) {
        return {}.toString.call( value ).indexOf( 'Number' ) > -1 && value % 1 === 0
    },


    /**
     * Create ARIA attribute strings.
     */
    ariaAttr: ariaAttr
} //PickerConstructor._



/**
 * Extend the picker with a component and defaults.
 */
PickerConstructor.extend = function( name, Component ) {

    // Extend jQuery.
    $.fn[ name ] = function( options, action ) {

        // Grab the component data.
        var componentData = this.data( name )

        // If the picker is requested, return the data object.
        if ( options == 'picker' ) {
            return componentData
        }

        // If the component data exists and `options` is a string, carry out the action.
        if ( componentData && typeof options == 'string' ) {
            return PickerConstructor._.trigger( componentData[ options ], componentData, [ action ] )
        }

        // Otherwise go through each matched element and if the component
        // doesn’t exist, create a new picker using `this` element
        // and merging the defaults and options with a deep copy.
        return this.each( function() {
            var $this = $( this )
            if ( !$this.data( name ) ) {
                new PickerConstructor( this, name, Component, options )
            }
        })
    }

    // Set the defaults.
    $.fn[ name ].defaults = Component.defaults
} //PickerConstructor.extend



function aria(element, attribute, value) {
    if ( $.isPlainObject(attribute) ) {
        for ( var key in attribute ) {
            ariaSet(element, key, attribute[key])
        }
    }
    else {
        ariaSet(element, attribute, value)
    }
}
function ariaSet(element, attribute, value) {
    element.setAttribute(
        (attribute == 'role' ? '' : 'aria-') + attribute,
        value
    )
}
function ariaAttr(attribute, data) {
    if ( !$.isPlainObject(attribute) ) {
        attribute = { attribute: data }
    }
    data = ''
    for ( var key in attribute ) {
        var attr = (key == 'role' ? '' : 'aria-') + key,
            attrVal = attribute[key]
        data += attrVal == null ? '' : attr + '="' + attribute[key] + '"'
    }
    return data
}

// IE8 bug throws an error for activeElements within iframes.
function getActiveElement() {
    try {
        return document.activeElement
    } catch ( err ) { }
}



// Expose the picker constructor.
return PickerConstructor


}));




/*!
 * Date picker for pickadate.js v3.5.6
 * http://amsul.github.io/pickadate.js/date.htm
 */

(function ( factory ) {

    // AMD.
    if ( typeof define == 'function' && define.amd )
        define( ['picker', 'jquery'], factory )

    // Node.js/browserify.
    else if ( typeof exports == 'object' )
        module.exports = factory( require('./picker.js'), require('jquery') )

    // Browser globals.
    else factory( Picker, jQuery )

}(function( Picker, $ ) {


/**
 * Globals and constants
 */
var DAYS_IN_WEEK = 7,
    WEEKS_IN_CALENDAR = 6,
    _ = Picker._



/**
 * The date picker constructor
 */
function DatePicker( picker, settings ) {

    var calendar = this,
        element = picker.$node[ 0 ],
        elementValue = element.value,
        elementDataValue = picker.$node.data( 'value' ),
        valueString = elementDataValue || elementValue,
        formatString = elementDataValue ? settings.formatSubmit : settings.format,
        isRTL = function() {

            return element.currentStyle ?

                // For IE.
                element.currentStyle.direction == 'rtl' :

                // For normal browsers.
                getComputedStyle( picker.$root[0] ).direction == 'rtl'
        }

    calendar.settings = settings
    calendar.$node = picker.$node

    // The queue of methods that will be used to build item objects.
    calendar.queue = {
        min: 'measure create',
        max: 'measure create',
        now: 'now create',
        select: 'parse create validate',
        highlight: 'parse navigate create validate',
        view: 'parse create validate viewset',
        disable: 'deactivate',
        enable: 'activate'
    }

    // The component's item object.
    calendar.item = {}

    calendar.item.clear = null
    calendar.item.disable = ( settings.disable || [] ).slice( 0 )
    calendar.item.enable = -(function( collectionDisabled ) {
        return collectionDisabled[ 0 ] === true ? collectionDisabled.shift() : -1
    })( calendar.item.disable )

    calendar.
        set( 'min', settings.min ).
        set( 'max', settings.max ).
        set( 'now' )

    // When there’s a value, set the `select`, which in turn
    // also sets the `highlight` and `view`.
    if ( valueString ) {
        calendar.set( 'select', valueString, {
            format: formatString,
            defaultValue: true
        })
    }

    // If there’s no value, default to highlighting “today”.
    else {
        calendar.
            set( 'select', null ).
            set( 'highlight', calendar.item.now )
    }


    // The keycode to movement mapping.
    calendar.key = {
        40: 7, // Down
        38: -7, // Up
        39: function() { return isRTL() ? -1 : 1 }, // Right
        37: function() { return isRTL() ? 1 : -1 }, // Left
        go: function( timeChange ) {
            var highlightedObject = calendar.item.highlight,
                targetDate = new Date( highlightedObject.year, highlightedObject.month, highlightedObject.date + timeChange )
            calendar.set(
                'highlight',
                targetDate,
                { interval: timeChange }
            )
            this.render()
        }
    }


    // Bind some picker events.
    picker.
        on( 'render', function() {
            picker.$root.find( '.' + settings.klass.selectMonth ).on( 'change', function() {
                var value = this.value
                if ( value ) {
                    picker.set( 'highlight', [ picker.get( 'view' ).year, value, picker.get( 'highlight' ).date ] )
                    picker.$root.find( '.' + settings.klass.selectMonth ).trigger( 'focus' )
                }
            })
            picker.$root.find( '.' + settings.klass.selectYear ).on( 'change', function() {
                var value = this.value
                if ( value ) {
                    picker.set( 'highlight', [ value, picker.get( 'view' ).month, picker.get( 'highlight' ).date ] )
                    picker.$root.find( '.' + settings.klass.selectYear ).trigger( 'focus' )
                }
            })
        }, 1 ).
        on( 'open', function() {
            var includeToday = ''
            if ( calendar.disabled( calendar.get('now') ) ) {
                includeToday = ':not(.' + settings.klass.buttonToday + ')'
            }
            picker.$root.find( 'button' + includeToday + ', select' ).attr( 'disabled', false )
        }, 1 ).
        on( 'close', function() {
            picker.$root.find( 'button, select' ).attr( 'disabled', true )
        }, 1 )

} //DatePicker


/**
 * Set a datepicker item object.
 */
DatePicker.prototype.set = function( type, value, options ) {

    var calendar = this,
        calendarItem = calendar.item

    // If the value is `null` just set it immediately.
    if ( value === null ) {
        if ( type == 'clear' ) type = 'select'
        calendarItem[ type ] = value
        return calendar
    }

    // Otherwise go through the queue of methods, and invoke the functions.
    // Update this as the time unit, and set the final value as this item.
    // * In the case of `enable`, keep the queue but set `disable` instead.
    //   And in the case of `flip`, keep the queue but set `enable` instead.
    calendarItem[ ( type == 'enable' ? 'disable' : type == 'flip' ? 'enable' : type ) ] = calendar.queue[ type ].split( ' ' ).map( function( method ) {
        value = calendar[ method ]( type, value, options )
        return value
    }).pop()

    // Check if we need to cascade through more updates.
    if ( type == 'select' ) {
        calendar.set( 'highlight', calendarItem.select, options )
    }
    else if ( type == 'highlight' ) {
        calendar.set( 'view', calendarItem.highlight, options )
    }
    else if ( type.match( /^(flip|min|max|disable|enable)$/ ) ) {
        if ( calendarItem.select && calendar.disabled( calendarItem.select ) ) {
            calendar.set( 'select', calendarItem.select, options )
        }
        if ( calendarItem.highlight && calendar.disabled( calendarItem.highlight ) ) {
            calendar.set( 'highlight', calendarItem.highlight, options )
        }
    }

    return calendar
} //DatePicker.prototype.set


/**
 * Get a datepicker item object.
 */
DatePicker.prototype.get = function( type ) {
    return this.item[ type ]
} //DatePicker.prototype.get


/**
 * Create a picker date object.
 */
DatePicker.prototype.create = function( type, value, options ) {

    var isInfiniteValue,
        calendar = this

    // If there’s no value, use the type as the value.
    value = value === undefined ? type : value


    // If it’s infinity, update the value.
    if ( value == -Infinity || value == Infinity ) {
        isInfiniteValue = value
    }

    // If it’s an object, use the native date object.
    else if ( $.isPlainObject( value ) && _.isInteger( value.pick ) ) {
        value = value.obj
    }

    // If it’s an array, convert it into a date and make sure
    // that it’s a valid date – otherwise default to today.
    else if ( $.isArray( value ) ) {
        value = new Date( value[ 0 ], value[ 1 ], value[ 2 ] )
        value = _.isDate( value ) ? value : calendar.create().obj
    }

    // If it’s a number or date object, make a normalized date.
    else if ( _.isInteger( value ) || _.isDate( value ) ) {
        value = calendar.normalize( new Date( value ), options )
    }

    // If it’s a literal true or any other case, set it to now.
    else /*if ( value === true )*/ {
        value = calendar.now( type, value, options )
    }

    // Return the compiled object.
    return {
        year: isInfiniteValue || value.getFullYear(),
        month: isInfiniteValue || value.getMonth(),
        date: isInfiniteValue || value.getDate(),
        day: isInfiniteValue || value.getDay(),
        obj: isInfiniteValue || value,
        pick: isInfiniteValue || value.getTime()
    }
} //DatePicker.prototype.create


/**
 * Create a range limit object using an array, date object,
 * literal “true”, or integer relative to another time.
 */
DatePicker.prototype.createRange = function( from, to ) {

    var calendar = this,
        createDate = function( date ) {
            if ( date === true || $.isArray( date ) || _.isDate( date ) ) {
                return calendar.create( date )
            }
            return date
        }

    // Create objects if possible.
    if ( !_.isInteger( from ) ) {
        from = createDate( from )
    }
    if ( !_.isInteger( to ) ) {
        to = createDate( to )
    }

    // Create relative dates.
    if ( _.isInteger( from ) && $.isPlainObject( to ) ) {
        from = [ to.year, to.month, to.date + from ];
    }
    else if ( _.isInteger( to ) && $.isPlainObject( from ) ) {
        to = [ from.year, from.month, from.date + to ];
    }

    return {
        from: createDate( from ),
        to: createDate( to )
    }
} //DatePicker.prototype.createRange


/**
 * Check if a date unit falls within a date range object.
 */
DatePicker.prototype.withinRange = function( range, dateUnit ) {
    range = this.createRange(range.from, range.to)
    return dateUnit.pick >= range.from.pick && dateUnit.pick <= range.to.pick
}


/**
 * Check if two date range objects overlap.
 */
DatePicker.prototype.overlapRanges = function( one, two ) {

    var calendar = this

    // Convert the ranges into comparable dates.
    one = calendar.createRange( one.from, one.to )
    two = calendar.createRange( two.from, two.to )

    return calendar.withinRange( one, two.from ) || calendar.withinRange( one, two.to ) ||
        calendar.withinRange( two, one.from ) || calendar.withinRange( two, one.to )
}


/**
 * Get the date today.
 */
DatePicker.prototype.now = function( type, value, options ) {
    value = new Date()
    if ( options && options.rel ) {
        value.setDate( value.getDate() + options.rel )
    }
    return this.normalize( value, options )
}


/**
 * Navigate to next/prev month.
 */
DatePicker.prototype.navigate = function( type, value, options ) {

    var targetDateObject,
        targetYear,
        targetMonth,
        targetDate,
        isTargetArray = $.isArray( value ),
        isTargetObject = $.isPlainObject( value ),
        viewsetObject = this.item.view/*,
        safety = 100*/


    if ( isTargetArray || isTargetObject ) {

        if ( isTargetObject ) {
            targetYear = value.year
            targetMonth = value.month
            targetDate = value.date
        }
        else {
            targetYear = +value[0]
            targetMonth = +value[1]
            targetDate = +value[2]
        }

        // If we’re navigating months but the view is in a different
        // month, navigate to the view’s year and month.
        if ( options && options.nav && viewsetObject && viewsetObject.month !== targetMonth ) {
            targetYear = viewsetObject.year
            targetMonth = viewsetObject.month
        }

        // Figure out the expected target year and month.
        targetDateObject = new Date( targetYear, targetMonth + ( options && options.nav ? options.nav : 0 ), 1 )
        targetYear = targetDateObject.getFullYear()
        targetMonth = targetDateObject.getMonth()

        // If the month we’re going to doesn’t have enough days,
        // keep decreasing the date until we reach the month’s last date.
        while ( /*safety &&*/ new Date( targetYear, targetMonth, targetDate ).getMonth() !== targetMonth ) {
            targetDate -= 1
            /*safety -= 1
            if ( !safety ) {
                throw 'Fell into an infinite loop while navigating to ' + new Date( targetYear, targetMonth, targetDate ) + '.'
            }*/
        }

        value = [ targetYear, targetMonth, targetDate ]
    }

    return value
} //DatePicker.prototype.navigate


/**
 * Normalize a date by setting the hours to midnight.
 */
DatePicker.prototype.normalize = function( value/*, options*/ ) {
    value.setHours( 0, 0, 0, 0 )
    return value
}


/**
 * Measure the range of dates.
 */
DatePicker.prototype.measure = function( type, value/*, options*/ ) {

    var calendar = this

    // If it’s anything false-y, remove the limits.
    if ( !value ) {
        value = type == 'min' ? -Infinity : Infinity
    }

    // If it’s a string, parse it.
    else if ( typeof value == 'string' ) {
        value = calendar.parse( type, value )
    }

    // If it's an integer, get a date relative to today.
    else if ( _.isInteger( value ) ) {
        value = calendar.now( type, value, { rel: value } )
    }

    return value
} ///DatePicker.prototype.measure


/**
 * Create a viewset object based on navigation.
 */
DatePicker.prototype.viewset = function( type, dateObject/*, options*/ ) {
    return this.create([ dateObject.year, dateObject.month, 1 ])
}


/**
 * Validate a date as enabled and shift if needed.
 */
DatePicker.prototype.validate = function( type, dateObject, options ) {

    var calendar = this,

        // Keep a reference to the original date.
        originalDateObject = dateObject,

        // Make sure we have an interval.
        interval = options && options.interval ? options.interval : 1,

        // Check if the calendar enabled dates are inverted.
        isFlippedBase = calendar.item.enable === -1,

        // Check if we have any enabled dates after/before now.
        hasEnabledBeforeTarget, hasEnabledAfterTarget,

        // The min & max limits.
        minLimitObject = calendar.item.min,
        maxLimitObject = calendar.item.max,

        // Check if we’ve reached the limit during shifting.
        reachedMin, reachedMax,

        // Check if the calendar is inverted and at least one weekday is enabled.
        hasEnabledWeekdays = isFlippedBase && calendar.item.disable.filter( function( value ) {

            // If there’s a date, check where it is relative to the target.
            if ( $.isArray( value ) ) {
                var dateTime = calendar.create( value ).pick
                if ( dateTime < dateObject.pick ) hasEnabledBeforeTarget = true
                else if ( dateTime > dateObject.pick ) hasEnabledAfterTarget = true
            }

            // Return only integers for enabled weekdays.
            return _.isInteger( value )
        }).length/*,

        safety = 100*/



    // Cases to validate for:
    // [1] Not inverted and date disabled.
    // [2] Inverted and some dates enabled.
    // [3] Not inverted and out of range.
    //
    // Cases to **not** validate for:
    // • Navigating months.
    // • Not inverted and date enabled.
    // • Inverted and all dates disabled.
    // • ..and anything else.
    if ( !options || (!options.nav && !options.defaultValue) ) if (
        /* 1 */ ( !isFlippedBase && calendar.disabled( dateObject ) ) ||
        /* 2 */ ( isFlippedBase && calendar.disabled( dateObject ) && ( hasEnabledWeekdays || hasEnabledBeforeTarget || hasEnabledAfterTarget ) ) ||
        /* 3 */ ( !isFlippedBase && (dateObject.pick <= minLimitObject.pick || dateObject.pick >= maxLimitObject.pick) )
    ) {


        // When inverted, flip the direction if there aren’t any enabled weekdays
        // and there are no enabled dates in the direction of the interval.
        if ( isFlippedBase && !hasEnabledWeekdays && ( ( !hasEnabledAfterTarget && interval > 0 ) || ( !hasEnabledBeforeTarget && interval < 0 ) ) ) {
            interval *= -1
        }


        // Keep looping until we reach an enabled date.
        while ( /*safety &&*/ calendar.disabled( dateObject ) ) {

            /*safety -= 1
            if ( !safety ) {
                throw 'Fell into an infinite loop while validating ' + dateObject.obj + '.'
            }*/


            // If we’ve looped into the next/prev month with a large interval, return to the original date and flatten the interval.
            if ( Math.abs( interval ) > 1 && ( dateObject.month < originalDateObject.month || dateObject.month > originalDateObject.month ) ) {
                dateObject = originalDateObject
                interval = interval > 0 ? 1 : -1
            }


            // If we’ve reached the min/max limit, reverse the direction, flatten the interval and set it to the limit.
            if ( dateObject.pick <= minLimitObject.pick ) {
                reachedMin = true
                interval = 1
                dateObject = calendar.create([
                    minLimitObject.year,
                    minLimitObject.month,
                    minLimitObject.date + (dateObject.pick === minLimitObject.pick ? 0 : -1)
                ])
            }
            else if ( dateObject.pick >= maxLimitObject.pick ) {
                reachedMax = true
                interval = -1
                dateObject = calendar.create([
                    maxLimitObject.year,
                    maxLimitObject.month,
                    maxLimitObject.date + (dateObject.pick === maxLimitObject.pick ? 0 : 1)
                ])
            }


            // If we’ve reached both limits, just break out of the loop.
            if ( reachedMin && reachedMax ) {
                break
            }


            // Finally, create the shifted date using the interval and keep looping.
            dateObject = calendar.create([ dateObject.year, dateObject.month, dateObject.date + interval ])
        }

    } //endif


    // Return the date object settled on.
    return dateObject
} //DatePicker.prototype.validate


/**
 * Check if a date is disabled.
 */
DatePicker.prototype.disabled = function( dateToVerify ) {

    var
        calendar = this,

        // Filter through the disabled dates to check if this is one.
        isDisabledMatch = calendar.item.disable.filter( function( dateToDisable ) {

            // If the date is a number, match the weekday with 0index and `firstDay` check.
            if ( _.isInteger( dateToDisable ) ) {
                return dateToVerify.day === ( calendar.settings.firstDay ? dateToDisable : dateToDisable - 1 ) % 7
            }

            // If it’s an array or a native JS date, create and match the exact date.
            if ( $.isArray( dateToDisable ) || _.isDate( dateToDisable ) ) {
                return dateToVerify.pick === calendar.create( dateToDisable ).pick
            }

            // If it’s an object, match a date within the “from” and “to” range.
            if ( $.isPlainObject( dateToDisable ) ) {
                return calendar.withinRange( dateToDisable, dateToVerify )
            }
        })

    // If this date matches a disabled date, confirm it’s not inverted.
    isDisabledMatch = isDisabledMatch.length && !isDisabledMatch.filter(function( dateToDisable ) {
        return $.isArray( dateToDisable ) && dateToDisable[3] == 'inverted' ||
            $.isPlainObject( dateToDisable ) && dateToDisable.inverted
    }).length

    // Check the calendar “enabled” flag and respectively flip the
    // disabled state. Then also check if it’s beyond the min/max limits.
    return calendar.item.enable === -1 ? !isDisabledMatch : isDisabledMatch ||
        dateToVerify.pick < calendar.item.min.pick ||
        dateToVerify.pick > calendar.item.max.pick

} //DatePicker.prototype.disabled


/**
 * Parse a string into a usable type.
 */
DatePicker.prototype.parse = function( type, value, options ) {

    var calendar = this,
        parsingObject = {}

    // If it’s already parsed, we’re good.
    if ( !value || typeof value != 'string' ) {
        return value
    }

    // We need a `.format` to parse the value with.
    if ( !( options && options.format ) ) {
        options = options || {}
        options.format = calendar.settings.format
    }

    // Convert the format into an array and then map through it.
    calendar.formats.toArray( options.format ).map( function( label ) {

        var
            // Grab the formatting label.
            formattingLabel = calendar.formats[ label ],

            // The format length is from the formatting label function or the
            // label length without the escaping exclamation (!) mark.
            formatLength = formattingLabel ? _.trigger( formattingLabel, calendar, [ value, parsingObject ] ) : label.replace( /^!/, '' ).length

        // If there's a format label, split the value up to the format length.
        // Then add it to the parsing object with appropriate label.
        if ( formattingLabel ) {
            parsingObject[ label ] = value.substr( 0, formatLength )
        }

        // Update the value as the substring from format length to end.
        value = value.substr( formatLength )
    })

    // Compensate for month 0index.
    return [
        parsingObject.yyyy || parsingObject.yy,
        +( parsingObject.mm || parsingObject.m ) - 1,
        parsingObject.dd || parsingObject.d
    ]
} //DatePicker.prototype.parse


/**
 * Various formats to display the object in.
 */
DatePicker.prototype.formats = (function() {

    // Return the length of the first word in a collection.
    function getWordLengthFromCollection( string, collection, dateObject ) {

        // Grab the first word from the string.
        // Regex pattern from http://stackoverflow.com/q/150033
        var word = string.match( /[^\x00-\x7F]+|\w+/ )[ 0 ]

        // If there's no month index, add it to the date object
        if ( !dateObject.mm && !dateObject.m ) {
            dateObject.m = collection.indexOf( word ) + 1
        }

        // Return the length of the word.
        return word.length
    }

    // Get the length of the first word in a string.
    function getFirstWordLength( string ) {
        return string.match( /\w+/ )[ 0 ].length
    }

    return {

        d: function( string, dateObject ) {

            // If there's string, then get the digits length.
            // Otherwise return the selected date.
            return string ? _.digits( string ) : dateObject.date
        },
        dd: function( string, dateObject ) {

            // If there's a string, then the length is always 2.
            // Otherwise return the selected date with a leading zero.
            return string ? 2 : _.lead( dateObject.date )
        },
        ddd: function( string, dateObject ) {

            // If there's a string, then get the length of the first word.
            // Otherwise return the short selected weekday.
            return string ? getFirstWordLength( string ) : this.settings.weekdaysShort[ dateObject.day ]
        },
        dddd: function( string, dateObject ) {

            // If there's a string, then get the length of the first word.
            // Otherwise return the full selected weekday.
            return string ? getFirstWordLength( string ) : this.settings.weekdaysFull[ dateObject.day ]
        },
        m: function( string, dateObject ) {

            // If there's a string, then get the length of the digits
            // Otherwise return the selected month with 0index compensation.
            return string ? _.digits( string ) : dateObject.month + 1
        },
        mm: function( string, dateObject ) {

            // If there's a string, then the length is always 2.
            // Otherwise return the selected month with 0index and leading zero.
            return string ? 2 : _.lead( dateObject.month + 1 )
        },
        mmm: function( string, dateObject ) {

            var collection = this.settings.monthsShort

            // If there's a string, get length of the relevant month from the short
            // months collection. Otherwise return the selected month from that collection.
            return string ? getWordLengthFromCollection( string, collection, dateObject ) : collection[ dateObject.month ]
        },
        mmmm: function( string, dateObject ) {

            var collection = this.settings.monthsFull

            // If there's a string, get length of the relevant month from the full
            // months collection. Otherwise return the selected month from that collection.
            return string ? getWordLengthFromCollection( string, collection, dateObject ) : collection[ dateObject.month ]
        },
        yy: function( string, dateObject ) {

            // If there's a string, then the length is always 2.
            // Otherwise return the selected year by slicing out the first 2 digits.
            return string ? 2 : ( '' + dateObject.year ).slice( 2 )
        },
        yyyy: function( string, dateObject ) {

            // If there's a string, then the length is always 4.
            // Otherwise return the selected year.
            return string ? 4 : dateObject.year
        },

        // Create an array by splitting the formatting string passed.
        toArray: function( formatString ) { return formatString.split( /(d{1,4}|m{1,4}|y{4}|yy|!.)/g ) },

        // Format an object into a string using the formatting options.
        toString: function ( formatString, itemObject ) {
            var calendar = this
            return calendar.formats.toArray( formatString ).map( function( label ) {
                return _.trigger( calendar.formats[ label ], calendar, [ 0, itemObject ] ) || label.replace( /^!/, '' )
            }).join( '' )
        }
    }
})() //DatePicker.prototype.formats




/**
 * Check if two date units are the exact.
 */
DatePicker.prototype.isDateExact = function( one, two ) {

    var calendar = this

    // When we’re working with weekdays, do a direct comparison.
    if (
        ( _.isInteger( one ) && _.isInteger( two ) ) ||
        ( typeof one == 'boolean' && typeof two == 'boolean' )
     ) {
        return one === two
    }

    // When we’re working with date representations, compare the “pick” value.
    if (
        ( _.isDate( one ) || $.isArray( one ) ) &&
        ( _.isDate( two ) || $.isArray( two ) )
    ) {
        return calendar.create( one ).pick === calendar.create( two ).pick
    }

    // When we’re working with range objects, compare the “from” and “to”.
    if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {
        return calendar.isDateExact( one.from, two.from ) && calendar.isDateExact( one.to, two.to )
    }

    return false
}


/**
 * Check if two date units overlap.
 */
DatePicker.prototype.isDateOverlap = function( one, two ) {

    var calendar = this,
        firstDay = calendar.settings.firstDay ? 1 : 0

    // When we’re working with a weekday index, compare the days.
    if ( _.isInteger( one ) && ( _.isDate( two ) || $.isArray( two ) ) ) {
        one = one % 7 + firstDay
        return one === calendar.create( two ).day + 1
    }
    if ( _.isInteger( two ) && ( _.isDate( one ) || $.isArray( one ) ) ) {
        two = two % 7 + firstDay
        return two === calendar.create( one ).day + 1
    }

    // When we’re working with range objects, check if the ranges overlap.
    if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {
        return calendar.overlapRanges( one, two )
    }

    return false
}


/**
 * Flip the “enabled” state.
 */
DatePicker.prototype.flipEnable = function(val) {
    var itemObject = this.item
    itemObject.enable = val || (itemObject.enable == -1 ? 1 : -1)
}


/**
 * Mark a collection of dates as “disabled”.
 */
DatePicker.prototype.deactivate = function( type, datesToDisable ) {

    var calendar = this,
        disabledItems = calendar.item.disable.slice(0)


    // If we’re flipping, that’s all we need to do.
    if ( datesToDisable == 'flip' ) {
        calendar.flipEnable()
    }

    else if ( datesToDisable === false ) {
        calendar.flipEnable(1)
        disabledItems = []
    }

    else if ( datesToDisable === true ) {
        calendar.flipEnable(-1)
        disabledItems = []
    }

    // Otherwise go through the dates to disable.
    else {

        datesToDisable.map(function( unitToDisable ) {

            var matchFound

            // When we have disabled items, check for matches.
            // If something is matched, immediately break out.
            for ( var index = 0; index < disabledItems.length; index += 1 ) {
                if ( calendar.isDateExact( unitToDisable, disabledItems[index] ) ) {
                    matchFound = true
                    break
                }
            }

            // If nothing was found, add the validated unit to the collection.
            if ( !matchFound ) {
                if (
                    _.isInteger( unitToDisable ) ||
                    _.isDate( unitToDisable ) ||
                    $.isArray( unitToDisable ) ||
                    ( $.isPlainObject( unitToDisable ) && unitToDisable.from && unitToDisable.to )
                ) {
                    disabledItems.push( unitToDisable )
                }
            }
        })
    }

    // Return the updated collection.
    return disabledItems
} //DatePicker.prototype.deactivate


/**
 * Mark a collection of dates as “enabled”.
 */
DatePicker.prototype.activate = function( type, datesToEnable ) {

    var calendar = this,
        disabledItems = calendar.item.disable,
        disabledItemsCount = disabledItems.length

    // If we’re flipping, that’s all we need to do.
    if ( datesToEnable == 'flip' ) {
        calendar.flipEnable()
    }

    else if ( datesToEnable === true ) {
        calendar.flipEnable(1)
        disabledItems = []
    }

    else if ( datesToEnable === false ) {
        calendar.flipEnable(-1)
        disabledItems = []
    }

    // Otherwise go through the disabled dates.
    else {

        datesToEnable.map(function( unitToEnable ) {

            var matchFound,
                disabledUnit,
                index,
                isExactRange

            // Go through the disabled items and try to find a match.
            for ( index = 0; index < disabledItemsCount; index += 1 ) {

                disabledUnit = disabledItems[index]

                // When an exact match is found, remove it from the collection.
                if ( calendar.isDateExact( disabledUnit, unitToEnable ) ) {
                    matchFound = disabledItems[index] = null
                    isExactRange = true
                    break
                }

                // When an overlapped match is found, add the “inverted” state to it.
                else if ( calendar.isDateOverlap( disabledUnit, unitToEnable ) ) {
                    if ( $.isPlainObject( unitToEnable ) ) {
                        unitToEnable.inverted = true
                        matchFound = unitToEnable
                    }
                    else if ( $.isArray( unitToEnable ) ) {
                        matchFound = unitToEnable
                        if ( !matchFound[3] ) matchFound.push( 'inverted' )
                    }
                    else if ( _.isDate( unitToEnable ) ) {
                        matchFound = [ unitToEnable.getFullYear(), unitToEnable.getMonth(), unitToEnable.getDate(), 'inverted' ]
                    }
                    break
                }
            }

            // If a match was found, remove a previous duplicate entry.
            if ( matchFound ) for ( index = 0; index < disabledItemsCount; index += 1 ) {
                if ( calendar.isDateExact( disabledItems[index], unitToEnable ) ) {
                    disabledItems[index] = null
                    break
                }
            }

            // In the event that we’re dealing with an exact range of dates,
            // make sure there are no “inverted” dates because of it.
            if ( isExactRange ) for ( index = 0; index < disabledItemsCount; index += 1 ) {
                if ( calendar.isDateOverlap( disabledItems[index], unitToEnable ) ) {
                    disabledItems[index] = null
                    break
                }
            }

            // If something is still matched, add it into the collection.
            if ( matchFound ) {
                disabledItems.push( matchFound )
            }
        })
    }

    // Return the updated collection.
    return disabledItems.filter(function( val ) { return val != null })
} //DatePicker.prototype.activate


/**
 * Create a string for the nodes in the picker.
 */
DatePicker.prototype.nodes = function( isOpen ) {

    var
        calendar = this,
        settings = calendar.settings,
        calendarItem = calendar.item,
        nowObject = calendarItem.now,
        selectedObject = calendarItem.select,
        highlightedObject = calendarItem.highlight,
        viewsetObject = calendarItem.view,
        disabledCollection = calendarItem.disable,
        minLimitObject = calendarItem.min,
        maxLimitObject = calendarItem.max,


        // Create the calendar table head using a copy of weekday labels collection.
        // * We do a copy so we don't mutate the original array.
        tableHead = (function( collection, fullCollection ) {

            // If the first day should be Monday, move Sunday to the end.
            if ( settings.firstDay ) {
                collection.push( collection.shift() )
                fullCollection.push( fullCollection.shift() )
            }

            // Create and return the table head group.
            return _.node(
                'thead',
                _.node(
                    'tr',
                    _.group({
                        min: 0,
                        max: DAYS_IN_WEEK - 1,
                        i: 1,
                        node: 'th',
                        item: function( counter ) {
                            return [
                                collection[ counter ],
                                settings.klass.weekdays,
                                'scope=col title="' + fullCollection[ counter ] + '"'
                            ]
                        }
                    })
                )
            ) //endreturn
        })( ( settings.showWeekdaysFull ? settings.weekdaysFull : settings.weekdaysShort ).slice( 0 ), settings.weekdaysFull.slice( 0 ) ), //tableHead


        // Create the nav for next/prev month.
        createMonthNav = function( next ) {

            // Otherwise, return the created month tag.
            return _.node(
                'div',
                ' ',
                settings.klass[ 'nav' + ( next ? 'Next' : 'Prev' ) ] + (

                    // If the focused month is outside the range, disabled the button.
                    ( next && viewsetObject.year >= maxLimitObject.year && viewsetObject.month >= maxLimitObject.month ) ||
                    ( !next && viewsetObject.year <= minLimitObject.year && viewsetObject.month <= minLimitObject.month ) ?
                    ' ' + settings.klass.navDisabled : ''
                ),
                'data-nav=' + ( next || -1 ) + ' ' +
                _.ariaAttr({
                    role: 'button',
                    controls: calendar.$node[0].id + '_table'
                }) + ' ' +
                'title="' + (next ? settings.labelMonthNext : settings.labelMonthPrev ) + '"'
            ) //endreturn
        }, //createMonthNav


        // Create the month label.
        createMonthLabel = function() {

            var monthsCollection = settings.showMonthsShort ? settings.monthsShort : settings.monthsFull

            // If there are months to select, add a dropdown menu.
            if ( settings.selectMonths ) {

                return _.node( 'select',
                    _.group({
                        min: 0,
                        max: 11,
                        i: 1,
                        node: 'option',
                        item: function( loopedMonth ) {

                            return [

                                // The looped month and no classes.
                                monthsCollection[ loopedMonth ], 0,

                                // Set the value and selected index.
                                'value=' + loopedMonth +
                                ( viewsetObject.month == loopedMonth ? ' selected' : '' ) +
                                (
                                    (
                                        ( viewsetObject.year == minLimitObject.year && loopedMonth < minLimitObject.month ) ||
                                        ( viewsetObject.year == maxLimitObject.year && loopedMonth > maxLimitObject.month )
                                    ) ?
                                    ' disabled' : ''
                                )
                            ]
                        }
                    }),
                    settings.klass.selectMonth,
                    ( isOpen ? '' : 'disabled' ) + ' ' +
                    _.ariaAttr({ controls: calendar.$node[0].id + '_table' }) + ' ' +
                    'title="' + settings.labelMonthSelect + '"'
                )
            }

            // If there's a need for a month selector
            return _.node( 'div', monthsCollection[ viewsetObject.month ], settings.klass.month )
        }, //createMonthLabel


        // Create the year label.
        createYearLabel = function() {

            var focusedYear = viewsetObject.year,

            // If years selector is set to a literal "true", set it to 5. Otherwise
            // divide in half to get half before and half after focused year.
            numberYears = settings.selectYears === true ? 5 : ~~( settings.selectYears / 2 )

            // If there are years to select, add a dropdown menu.
            if ( numberYears ) {

                var
                    minYear = minLimitObject.year,
                    maxYear = maxLimitObject.year,
                    lowestYear = focusedYear - numberYears,
                    highestYear = focusedYear + numberYears

                // If the min year is greater than the lowest year, increase the highest year
                // by the difference and set the lowest year to the min year.
                if ( minYear > lowestYear ) {
                    highestYear += minYear - lowestYear
                    lowestYear = minYear
                }

                // If the max year is less than the highest year, decrease the lowest year
                // by the lower of the two: available and needed years. Then set the
                // highest year to the max year.
                if ( maxYear < highestYear ) {

                    var availableYears = lowestYear - minYear,
                        neededYears = highestYear - maxYear

                    lowestYear -= availableYears > neededYears ? neededYears : availableYears
                    highestYear = maxYear
                }

                return _.node( 'select',
                    _.group({
                        min: lowestYear,
                        max: highestYear,
                        i: 1,
                        node: 'option',
                        item: function( loopedYear ) {
                            return [

                                // The looped year and no classes.
                                loopedYear, 0,

                                // Set the value and selected index.
                                'value=' + loopedYear + ( focusedYear == loopedYear ? ' selected' : '' )
                            ]
                        }
                    }),
                    settings.klass.selectYear,
                    ( isOpen ? '' : 'disabled' ) + ' ' + _.ariaAttr({ controls: calendar.$node[0].id + '_table' }) + ' ' +
                    'title="' + settings.labelYearSelect + '"'
                )
            }

            // Otherwise just return the year focused
            return _.node( 'div', focusedYear, settings.klass.year )
        } //createYearLabel


    // Create and return the entire calendar.
    return _.node(
        'div',
        ( settings.selectYears ? createYearLabel() + createMonthLabel() : createMonthLabel() + createYearLabel() ) +
        createMonthNav() + createMonthNav( 1 ),
        settings.klass.header
    ) + _.node(
        'table',
        tableHead +
        _.node(
            'tbody',
            _.group({
                min: 0,
                max: WEEKS_IN_CALENDAR - 1,
                i: 1,
                node: 'tr',
                item: function( rowCounter ) {

                    // If Monday is the first day and the month starts on Sunday, shift the date back a week.
                    var shiftDateBy = settings.firstDay && calendar.create([ viewsetObject.year, viewsetObject.month, 1 ]).day === 0 ? -7 : 0

                    return [
                        _.group({
                            min: DAYS_IN_WEEK * rowCounter - viewsetObject.day + shiftDateBy + 1, // Add 1 for weekday 0index
                            max: function() {
                                return this.min + DAYS_IN_WEEK - 1
                            },
                            i: 1,
                            node: 'td',
                            item: function( targetDate ) {

                                // Convert the time date from a relative date to a target date.
                                targetDate = calendar.create([ viewsetObject.year, viewsetObject.month, targetDate + ( settings.firstDay ? 1 : 0 ) ])

                                var isSelected = selectedObject && selectedObject.pick == targetDate.pick,
                                    isHighlighted = highlightedObject && highlightedObject.pick == targetDate.pick,
                                    isDisabled = disabledCollection && calendar.disabled( targetDate ) || targetDate.pick < minLimitObject.pick || targetDate.pick > maxLimitObject.pick,
                                    formattedDate = _.trigger( calendar.formats.toString, calendar, [ settings.format, targetDate ] )

                                return [
                                    _.node(
                                        'div',
                                        targetDate.date,
                                        (function( klasses ) {

                                            // Add the `infocus` or `outfocus` classes based on month in view.
                                            klasses.push( viewsetObject.month == targetDate.month ? settings.klass.infocus : settings.klass.outfocus )

                                            // Add the `today` class if needed.
                                            if ( nowObject.pick == targetDate.pick ) {
                                                klasses.push( settings.klass.now )
                                            }

                                            // Add the `selected` class if something's selected and the time matches.
                                            if ( isSelected ) {
                                                klasses.push( settings.klass.selected )
                                            }

                                            // Add the `highlighted` class if something's highlighted and the time matches.
                                            if ( isHighlighted ) {
                                                klasses.push( settings.klass.highlighted )
                                            }

                                            // Add the `disabled` class if something's disabled and the object matches.
                                            if ( isDisabled ) {
                                                klasses.push( settings.klass.disabled )
                                            }

                                            return klasses.join( ' ' )
                                        })([ settings.klass.day ]),
                                        'data-pick=' + targetDate.pick + ' ' + _.ariaAttr({
                                            role: 'gridcell',
                                            label: formattedDate,
                                            selected: isSelected && calendar.$node.val() === formattedDate ? true : null,
                                            activedescendant: isHighlighted ? true : null,
                                            disabled: isDisabled ? true : null
                                        })
                                    ),
                                    '',
                                    _.ariaAttr({ role: 'presentation' })
                                ] //endreturn
                            }
                        })
                    ] //endreturn
                }
            })
        ),
        settings.klass.table,
        'id="' + calendar.$node[0].id + '_table' + '" ' + _.ariaAttr({
            role: 'grid',
            controls: calendar.$node[0].id,
            readonly: true
        })
    ) +

    // * For Firefox forms to submit, make sure to set the buttons’ `type` attributes as “button”.
    _.node(
        'div',
        _.node( 'button', settings.today, settings.klass.buttonToday,
            'type=button data-pick=' + nowObject.pick +
            ( isOpen && !calendar.disabled(nowObject) ? '' : ' disabled' ) + ' ' +
            _.ariaAttr({ controls: calendar.$node[0].id }) ) +
        _.node( 'button', settings.clear, settings.klass.buttonClear,
            'type=button data-clear=1' +
            ( isOpen ? '' : ' disabled' ) + ' ' +
            _.ariaAttr({ controls: calendar.$node[0].id }) ) +
        _.node('button', settings.close, settings.klass.buttonClose,
            'type=button data-close=true ' +
            ( isOpen ? '' : ' disabled' ) + ' ' +
            _.ariaAttr({ controls: calendar.$node[0].id }) ),
        settings.klass.footer
    ) //endreturn
} //DatePicker.prototype.nodes




/**
 * The date picker defaults.
 */
DatePicker.defaults = (function( prefix ) {

    return {

        // The title label to use for the month nav buttons
        labelMonthNext: 'Next month',
        labelMonthPrev: 'Previous month',

        // The title label to use for the dropdown selectors
        labelMonthSelect: 'Select a month',
        labelYearSelect: 'Select a year',

        // Months and weekdays
        monthsFull: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
        monthsShort: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
        weekdaysFull: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ],
        weekdaysShort: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],

        // Today and clear
        today: 'Today',
        clear: 'Clear',
        close: 'Close',

        // Picker close behavior
        closeOnSelect: true,
        closeOnClear: true,

        // The format to show on the `input` element
        format: 'd mmmm, yyyy',

        // Classes
        klass: {

            table: prefix + 'table',

            header: prefix + 'header',

            navPrev: prefix + 'nav--prev',
            navNext: prefix + 'nav--next',
            navDisabled: prefix + 'nav--disabled',

            month: prefix + 'month',
            year: prefix + 'year',

            selectMonth: prefix + 'select--month',
            selectYear: prefix + 'select--year',

            weekdays: prefix + 'weekday',

            day: prefix + 'day',
            disabled: prefix + 'day--disabled',
            selected: prefix + 'day--selected',
            highlighted: prefix + 'day--highlighted',
            now: prefix + 'day--today',
            infocus: prefix + 'day--infocus',
            outfocus: prefix + 'day--outfocus',

            footer: prefix + 'footer',

            buttonClear: prefix + 'button--clear',
            buttonToday: prefix + 'button--today',
            buttonClose: prefix + 'button--close'
        }
    }
})( Picker.klasses().picker + '__' )





/**
 * Extend the picker to add the date picker.
 */
Picker.extend( 'pickadate', DatePicker )


}));





/**
 * Registers the handles on the side
 */
(function($){
	$.fn.calculationForm = function(settings){
		var config = {};
		
		if(settings) $.extend(config, settings);
		
		this.each(function(){
			var form = $(this);
			
			form.find('label.input-prefix.from,label.input-suffix.from').each(function(){
				var me = $(this);
				$('select#calculation_' + me.attr('data-from')).change(function(){
					me.text($(this).find('> :selected').text());
				});
			});
			
			form.find('fieldset.calculation > div.visible-switch').each(function(){
				var me = $(this);
				var sources = $('[name="calculation[' + $(this).attr('data-variable') + ']"]');
				var value = $(this).attr('data-value');
				
				sources.each(function(){
					var source = $(this);
					
					if(source.attr('type')=='radio'){
						source.change(function(){
							sources.each(function(){
								if($(this).val()==value){
									me[$(this).prop('checked') ? 'removeClass' : 'addClass']('hidden').trigger('visible-switch');
								}
							});
						});
					}else if(source.attr('type')=='checkbox'){
						if(source.val()==value){
							source.change(function(){
								me[source.prop('checked') ? 'removeClass' : 'addClass']('hidden').trigger('visible-switch');
							});
						}
					}else{
						source.change(function(){
							me[source.val()==value ? 'removeClass' : 'addClass']('hidden').trigger('visible-switch');
						});
					}
				});
				
				sources.closest('div[data-variable]').on('visible-switch', function(){
					if($(this).hasClass('hidden')){
						me.addClass('hidden').trigger('visible-switch');
					}else{
						sources.change();
					}
				});
			});
			form.find('fieldset.calculation > div.visible-switch.hidden').trigger('visible-switch');
			
			form.find('fieldset.calculation > div[data-formula]').each(function(){
				var me = $(this);
				var fields = me.attr('data-formula').split(',');
				for(var i=0; i<fields.length; i++){
					(function(input){
						var value = input.val();
						var busy = false;
						var queue = false;
						
						var __get = function(){
							queue = false;
							
							var values = $('#calculation form').serializeForm();
							values.field = me.attr('data-name');
							values.fields = me.attr('data-formula');
							
							json.post('/ajax/calculations/field', values, function(data){
								busy = false;
								if(queue){
									__get();
								}else{
									if(data.success=='OK'){
										me.find('input').val(data.value);
									}
								}
							}, function(ex, response){
								busy = false;
							});
						};
						
						var _evt = function(evt){
							if(value==input.val()) return;
							value = input.val();
							
							if(busy){
								queue = true;
							}else{
								__get();
							}
						};
						input.change(_evt).keyup(_evt);
					})(form.find('fieldset.calculation [name="calculation[' + fields[i] + ']"]'));
				}
			});
			
			form.find('fieldset.calculation > div > div.field[data-type="number"] > span.input > input[type="text"]').keyup(function(){
				var value = $(this).val();
				if(value.match(/\d+/g)){
					var caret = $(this).caret();
					var _cs = value.substr(0, caret);
					if(_cs.match(/\d|,/g)){
						caret = _cs.match(/\d|,/g).join('').length;
					}else{
						caret = 0;
					}
					
					value = value.match(/\d|,/g).join('');
					var parts = value.match(/(\d+)(,(\d+,?)*)?/);
					
					var number = '';
					
					for(var i=0; i<parts[1].length; i++){
						var index = parts[1].length - i - 1;
						if(i > 2 && (i%3)==0){
							number = parts[1].charAt(index) + '.' + number;
						}else{
							number = parts[1].charAt(index) + number;
						}
					}
					if(parts[2]){
						number+= ',';
						if(parts[3]) number+= parts[3].match(/\d/g).join('');
					}
					
					if(caret <= parts[1].length){
						if((parts[1].length%3)!=0){
							caret += Math.floor(((3-(parts[1].length%3)) + caret) / 3);
						}else{
							caret += Math.floor(caret / 3);
						}
					}else{
						caret += Math.floor(parts[1].length / 3);
					}
					if($(this).val()!=number){
						$(this).val(number);
						$(this).caret(caret);
					}
				}
				$(this).parent().find('input[type="number"]').val(value.replace('.', '').replace(',', '.'));
			}).keyup();
			
			form.find('fieldset.calculation > div > div.field[data-type="number"] > span.input > input[type="number"]').keyup(function(){
				$(this).parent().find('input[type="text"]').val($(this).val().replace('.', ','));
			}).change(function(){
				$(this).parent().find('input[type="text"]').val($(this).val().replace('.', ','));
			}).blur(function(){
				$(this).parent().find('input[type="text"]').val($(this).val().replace('.', ','));
			});
			
			
			form.find('fieldset.calculation > div > div.field[data-type="date"] > span.input > input[type="text"]').each(function(){
				var me = $(this);
				
				me.after('<input type="text">');
				
				var max = new Date();
				var years = 140;
				
				if(me.attr('data-max')){
					max = new Date(me.attr('data-max'));
				}else{
					max.setFullYear(max.getFullYear() + 30);
				}
				
				if(me.attr('data-min')){
					var min = new Date(me.attr('data-min'));
					years = max.getFullYear() - min.getFullYear();
				}
				var update = true;
				var calender = me.parent().find('>input+input');
				calender.pickadate({
					monthsFull: [ 'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december' ],
					monthsShort: [ 'jan', 'feb', 'maa', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec' ],
					weekdaysFull: [ 'zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag' ],
					weekdaysShort: [ 'zo', 'ma', 'di', 'wo', 'do', 'vr', 'za' ],
					today: 'vandaag',
					clear: 'verwijderen',
					close: 'sluiten',
					firstDay: 1,
					format: 'dd-mm-yyyy',
					formatSubmit: 'dd-mm-yyyy',
					selectYears: years,
					selectMonths: true,
					max: max,
					onSet: function(context) {
						if(update) me.val(calender.val());
					}
				});
				var picker = calender.pickadate('picker')
				me.keyup(function(){
					var matches = me.val().match(/^\s*(\d{1,2})(?:(\D*)(?:(\d{1,2})(?:(\D*)(\d{1,4})?)?)?)?/);
					if(matches){
						if(typeof(matches[3])!='undefined') matches[2] = '-';
						if(typeof(matches[5])!='undefined') matches[4] = '-';
						var output = matches.slice(1).join('');
						console.log(matches, output);
						
						if(me.val()!=output){
							me.val(output);
						}
					}
					if(me.val().match(/^\d{1,2}-\d{1,2}-\d{4}$/)){
						update = false;
						picker.set('select', me.val(), { format: 'dd-mm-yyyy' });
						update = true;
					}
				});
			});
			
			var __submit = function(){
				var values = form.serializeForm();
				values.embed = $('#calculation').attr('data-embed')=='true' ? 'true' : 'false';
				
				var title = $('h1').text();
				
				json.post('/ajax/calculations/calculation', values, function(data){
					$('#calculation form .error').removeClass('error');
					
					if(data.success=='OK'){
						if($('#calculation').attr('data-embed')!='true'){
							window.location = data.url;
						}else{
							if(typeof(_gaq)!='undefined') _gaq.push(['_trackEvent', 'berekening', title]);
							$('#calculation').html(data.view);
							window.location.hash = data.code;
							$('.social-share').share();
							$('.stars.input').rating();
							$('html,body').animate({scrollTop: $('#calculation').offset().top}, 'slow');
							askQuestion();
						}
					}else if(data.error=='Invalid'){
						$('#calculation form').traverse(data.errors, function(item, value){
							item.parent().find('[type="number"]').addClass('error').attr('title', value);
							item.addClass('error').attr('title', value);
						}, 'calculation');
					}
				}, function(ex, response){
					alert(response);
				});
			};
			
			$('fieldset.calculation > div > div.field > input[type="submit"]').click(function(evt){
				evt.preventDefault();
				__submit();
			});

			$('fieldset.calculation > div > div.field > input[type="submit"]').attr('disabled', false);
			
			form.submit(function(evt){
				evt.preventDefault();
				__submit();
			});
			
			form.find('fieldset.calculation div.help > span').click(function(){
				if($(this).parent().hasClass('open')){
					$(this).parent().removeClass('open');
					$(this).parent().find('> div').height(0);
				}else{
					var parent = $(this).parent();
					parent.addClass('open');
					
					var height = parent.find('> div > div').height();
					height+= parseInt(parent.find('> div > div').css('margin-top').match(/(\d+)px/)[1]);
					height+= parseInt(parent.find('> div > div').css('margin-bottom').match(/(\d+)px/)[1]);
					height+= parseInt(parent.find('> div > div').css('padding-top').match(/(\d+)px/)[1]);
					height+= parseInt(parent.find('> div > div').css('padding-bottom').match(/(\d+)px/)[1]);
					
					parent.find('> div').height(height);
				}
			});
			
			if(typeof(SelectFancy)!='undefined'){
				SelectFancy();
			}else{
				$('select.select-fancy').each(function(){
					$(this).removeClass('select-fancy');
					$(this).parent().selectFancy();
				});
			}
			// END
		});
	};
})(jQuery);

$(window).scroll(function () {
	var top = $(window).scrollTop();
	if($('aside .banner-desktop.static').hasClass('floating')){
		if(top < 655) $('aside .banner-desktop.static').removeClass('floating');
	}else{
		if(top > 655) $('aside .banner-desktop.static').addClass('floating');
	}
});

function askQuestion(){
	$('.ask-question').dialog({
		content: function(source, dialog){
			dialog.addClass('clean');
			dialog.setCloseText('Sluit dit venster');

			json.get('/ajax/calculations/question', function(data){
				dialog.setContent(data.view);
				dialog.find('input[type="submit"]').click(function(){
					var params = dialog.find('.question-form').serializeForm();
					params.calculation_id = source.attr('data-id');

					json.post('/ajax/calculations/question', params, function(data){
						if(data.success=='OK'){
							dialog.setContent(data.view);
						}else{
							dialog.find('.question-form .error').each(function(){
								$(this).removeClass('error').attr('title', '');
							});
							dialog.find('.question-form').traverse(data.errors, function(element, item){
								element.addClass('error').attr('title', item);
							});
						}
					}, function(ex, response){
						dialog.setContent('Er is een fout opgetreden');
						dialog.show();
					});
				});

				dialog.show();
			}, function(ex, response){
				dialog.setContent('Er is een fout opgetreden');
				dialog.show();
			});
		}
	});
}

(function($){
	$.fn.flipCounter = function(settings){
		var config = {
		};

		if(settings) $.extend(config, settings);
		var objects = [];

		this.each(function(){
			var item = $(document.createElement('span'));

			var html = '';
			html+= '<span class="current"><span>' + $(this).text() + '</span></span>';
			html+= '<span ><span>' + $(this).text() + '</span></span>';
			html+= '<span class="next"><span></span></span>';
			html+= '<span ><span></span></span>';

			item.html(html);
			$(this).replaceWith(item);

			objects.push({
				flipUp: function(fast){
					item[fast ? 'addClass': 'removeClass']('fast');
					var value = parseInt(item.find('> .current > span').text());
					var next = (value + 1) % 10;

					item.find('> .next > span').text(next);
					item.find('> .next + span > span').text(next);

					item.addClass('flip');
					setTimeout(function(){
						item.find('> .current > span').text(next);
						item.find('> .current + span > span').text(next);
						item.removeClass('flip');
					}, fast ? 20 : 550);

					return next==0;
				},
				flipTo: function(value, fast){
					item[fast ? 'addClass': 'removeClass']('fast');

					item.find('> .next > span').text(value);
					item.find('> .next + span > span').text(value);

					item.addClass('flip');
					setTimeout(function(){
						item.find('> .current > span').text(value);
						item.find('> .current + span > span').text(value);
						item.removeClass('flip');
					}, fast ? 180 : 550);
				}
			});
		});

		return objects;
	};
})(jQuery);


/**
 * Registers the handles on the side
 */
(function($){
	$.fn.share = function(settings){
		var config = {};

		if(settings) $.extend(config, settings);

		this.each(function(){
			var me = $(this);

			var info			= {};
			info.url			= window.location;
			info.title			= $($('h1')[0]).text();
			info.description	= '';

			me.find('.facebook').click(function(evt){
				evt.preventDefault();

				var address = 'http://www.facebook.com/share.php?u=' + escape(info.url);
				window.open(address,'facebook-popup', 'width=700,height=500,scrollbars=no,toolbar=no,location=no');
			});

			me.find('.twitter').click(function(evt){
				evt.preventDefault();

				var address = 'http://twitter.com/share?url=' + escape(info.url) + '&text=' + escape(info.title);
				window.open(address,'twitter-popup', 'width=650,height=400,scrollbars=yes,toolbar=no,location=no');
			});

			me.find('.linkedin').click(function(evt){
				evt.preventDefault();

				var address = 'http://www.linkedin.com/shareArticle?mini=true&url=' + escape(info.url) + '&title=' + escape(info.title) + '&summary=' + escape(info.description);
				window.open(address,'linkedin-popup', 'width=520,height=570,scrollbars=yes,toolbar=no,location=no');
			});

			me.find('.googleplus').click(function(evt){
				evt.preventDefault();

				var address = 'mailto:?SUBJECT=' + escape(info.title) + '&BODY=' +  escape(info.url);
				window.location.href = address;
	

			});
		});
	};
})(jQuery);

/**
 * Registers the handles on the side
 */
(function($){
	$.fn.rating = function(settings){
		var config = {};

		if(settings) $.extend(config, settings);

		this.each(function(){
			var me = $(this);
			if(!me.data('installed')){
				me.data('installed', true);
				me.find('> span > span').click(function(evt){
					var index = me.find('> span > span').index(this);
					var base = (5 - Math.floor(index / 2)) * 2;
					var value = base - ($(this).index() ? 0 : 1);

					me.find('> span.on,> span.on.half').removeClass('on').removeClass('half');
					$(this).parent().addClass($(this).index() ? 'on' : 'on half');

					$.post('/ajax/calculations/rating', {action: 'vote', id: me.attr('data-id'), value:value}, function(response){
						json(response, function(data){
							me.parent().find('[itemprop="ratingValue"]').html(data.value);
							me.parent().find('[itemprop="reviewCount"]').html(data.total);

							if(typeof(data.html)!='undefined'){
								$.dialog({
									content: function(source, dialog){
										dialog.setContent(data.html);
										dialog.setWidth(500);
										dialog.find('[type="submit"]').click(function(){
											$.post('/ajax/calculations/rating', {action: 'message', id: me.attr('data-id'), value:value, email: dialog.find('[name="email"]').val(), reden:dialog.find('[name="reden"]').val()}, function(response){
												json(response, function(data){
													if(data.success=='OK'){
														me.parent().find('[itemprop="ratingValue"]').html(data.value);
														me.parent().find('[itemprop="reviewCount"]').html(data.total);
														dialog.close();
													}else{

														dialog.find('.error').removeClass('error').attr('title', '');
														dialog.find('fieldset').traverse(data.errors, function(item, value){
															item.addClass('error').attr('title', value);
														});
													}
												}, function(ex){
												});
											}, 'text');
										})
										dialog.show();
									}
								});
							}else if(typeof(data.tip)!='undefined'){
								showtip(evt.pageX, evt.pageY, data.tip);
							}else{
								showtip(evt.pageX, evt.pageY, 'Bedankt voor je beoordeling');
							}
						}, function(ex){
						});
					}, 'text');
				});
			}
		});
	};
})(jQuery);

(function($){
	$.fn.ratingafstand = function(settings){
		var config = {};

		if(settings) $.extend(config, settings);

		this.each(function(){
			var me = $(this);
			if(!me.data('installed')){
				me.data('installed', true);
				me.find('> span > span').click(function(evt){
					var index = me.find('> span > span').index(this);
					var base = (5 - Math.floor(index / 2)) * 2;
					var value = base - ($(this).index() ? 0 : 1);

					me.find('> span.on,> span.on.half').removeClass('on').removeClass('half');
					$(this).parent().addClass($(this).index() ? 'on' : 'on half');

					$.post('/ajax/afstand/rating', {action: 'vote', id: me.attr('data-id'), value:value}, function(response){
						json(response, function(data){
							me.parent().find('[itemprop="ratingValue"]').html(data.value);
							me.parent().find('[itemprop="reviewCount"]').html(data.total);

							if(typeof(data.html)!='undefined'){
								$.dialog({
									content: function(source, dialog){
										dialog.setContent(data.html);
										dialog.setWidth(500);
										dialog.find('[type="submit"]').click(function(){
											$.post('/ajax/afstand/rating', {action: 'message', id: me.attr('data-id'), value:value, email: dialog.find('[name="email"]').val(), reden:dialog.find('[name="reden"]').val()}, function(response){
												json(response, function(data){
													if(data.success=='OK'){
														me.parent().find('[itemprop="ratingValue"]').html(data.value);
														me.parent().find('[itemprop="reviewCount"]').html(data.total);
														dialog.close();
													}else{

														dialog.find('.error').removeClass('error').attr('title', '');
														dialog.find('fieldset').traverse(data.errors, function(item, value){
															item.addClass('error').attr('title', value);
														});
													}
												}, function(ex){
												});
											}, 'text');
										})
										dialog.show();
									}
								});
							}else if(typeof(data.tip)!='undefined'){
								showtip(evt.pageX, evt.pageY, data.tip);
							}else{
								showtip(evt.pageX, evt.pageY, 'Bedankt voor je beoordeling');
							}
						}, function(ex){
						});
					}, 'text');
				});
			}
		});
	};
})(jQuery);


/**
 * Registers the handles on the side
 */
(function($){
	$.fn.addToHome = function(settings){
		var config = {};

		if(settings) $.extend(config, settings);

		this.each(function(){
			var me = $(this);

			me.addClass('add-to-home');
			me.html('<div><div>Om deze webapp op je telefoon te installeren, klik op <span></span> en dan <strong>Toevoegen aan startscherm</strong>.</div><a href="javascript:void(0)">X</a></div>');
			me.find('> div > a').click(function(evt){
				evt.preventDefault();
				me.remove();
				$.post('/', {action: 'add-to-home'});
			});
		});
	};
	$.addToHome = function(){
		var item = $(document.createElement('div'));
		$(document.body).append(item);
		item.addToHome();
	};
})(jQuery);

function showtip(left, top, contents){
	var tip = $(document.createElement('div'));
	tip.addClass('tip');
	tip.html('<div></di>');
	tip.find('>div').html(contents);
	tip.css({left:left, top:top});
	$(document.body).append(tip);
	tip.fadeIn(200).delay(1000).fadeOut(500, function(){ $(this).remove(); });
}


(function($){
	$.fn.enlargeImage = function(settings){
		var config = {};
		if(settings) $.extend(config, settings);
		this.each(function(){
			var me = $(this);
			if(me.hasClass('enlarge')) return;
			me.addClass('enlarge');
			me.click(function(){
				var image = new Image();
				image.onload = function(){
					if((me.width() / image.width) < 0.7 || (me.height() / image.height) < 0.7){
						var viewer = $('<div class="image-viewer"><div><div><div><img src=""></div></div></div><span></span></div>');
						viewer.find('img').attr('src', me.attr('src'));
						viewer.find('span').click(function(){
							viewer.remove();
							$('body').css('overflow', 'auto');
						});
						$('body').append(viewer);
						$('body').css('overflow', 'hidden');
					}
				}
				image.src = me.attr('src');
			});
		});
	};
})(jQuery);


(function($){
	$.fn.lazy = function(settings){
		var config = {};

		if(settings) $.extend(config, settings);

		this.each(function(){
			var me = $(this);
			if(me.hasClass('lazy')) return;

			me.addClass('lazy');
			var __load = function(){
				var view = {
					top: $(window).scrollTop(),
					bottom: $(window).scrollTop() + $(window).height()
				};

				if((me.offset().top + me.height()) > view.top && me.offset().top < view.bottom){
					me.addClass('loading');

					me.on(function(){
						me.removeClass('loading').removeClass('error').addClass('loaded');
					}).on(function(){
						me.addClass('error');

						setTimeout(function(){
							me.removeClass('loading');
						}, 1000);
					});
					if(me.attr('data-src')){
						me.attr('src', me.attr('data-src'));
					}else if(me.attr('data-background-image')){
						me.css('background-image', 'url(\'' + me.attr('data-background-image') + '\')');
					}
				}
			};

			$(window).scroll(function(){ __load(); });
			__load();
		});
	};
})(jQuery);


$(document).ready(function() {
	$('img[data-src],div[data-background-image]').lazy();
	$('img').enlargeImage();

	var stickyTopStart, stickyParentHeight;
	var elem = $('nav.most-searched');
	if (elem.length > 0) {
		stickyTopStart = elem.offset().top;

		$(window).scroll(function() {
			var elem = $('nav.most-searched');
			var stickyTop = elem.offset().top;
			var windowTop = $(window).scrollTop();

			if (stickyTop < windowTop + 30 || stickyTop > stickyTopStart) {
				elem.stop().animate(
					{'top': Math.min(Math.max(0, windowTop + 30 - stickyTopStart), stickyParentHeight)}
				);
			}
		});
	}

	var elem = $('nav.most-searched');
	if (elem.length > 0) {
		var marginTop = elem.css('top');
		elem.css('top', 0);
		stickyParentHeight = elem.parent().height() - stickyTopStart + elem.parent().offset().top - elem.height();
		elem.css('top', marginTop);
	}

	$('table').after('<div class="swipe"></div>');
});

$(document).ready(function(){
	var lastUrl = null;
	window.onhashchange = function(){
		var currentUrl = window.location.toString();
		if(lastUrl==null){
			lastUrl = currentUrl;
		}else{
			if(currentUrl.indexOf('#')<0 && lastUrl.indexOf('#')>=0){
				window.location.reload();
			}
		}
	};
	$('.social-share').share();

	$('#calculation form').each(function(){
		if(window.location.hash.length > 0){

			json.get('/ajax/calculations/result?code=' + window.location.hash.substr(1), function(data){
				if(data.success=='OK'){
					$('#calculation').html(data.view);
					$('.social-share').share();
					$('.stars.input').rating();
					askQuestion();
					$('img').enlargeImage();

					/*var pymt = document.createElement("script");
					pymt.type = "text/javascript";pymt.src = "//wwa.pacific-yield.com/yield/yieldtag.php?pi=319&psi=698&cr=1447341782&cb=" + Math.random();
					pymt.setAttribute("async", "true");
					document.body.appendChild(pymt);*/
				}
			}, function(ex, response){
				alert(response);
			});
		}

		$(this).calculationForm();
	});

	$('#source_id').change(function(){
		var values = $('#calculation form').serializeForm();

		json.get('/ajax/calculations/form/' + $(this).val() + '/' + $(this).attr('data-id'), function(data){
			if(data.success=='OK'){
				$('#calculation div.fields').html(data.html);
				$('#calculation form').calculationForm();

				$('#calculation form').traverse(values, function(element, item){
					if(element.attr('name').match(/^calculation\[/)){
						element.val(item).change().keyup();
					}
				});
			}
		}, function(ex, response){
			alert(response);
		});
	});

	if($('fieldset.iframe.open input[type="submit"]').length > 0 && $('fieldset.iframe input[name="newwindow"]').val() > 0){
		window.location = $('fieldset.iframe input[name="url"]').val();
	}else{
		$('fieldset.iframe.open input[type="submit"]').dialog({
			content: function(source, dialog){
				var title = $('h1').text();
				if(typeof(_gaq)!='undefined') _gaq.push(['_trackEvent', 'berekening', title]);

					var fieldset = source.parent();

					var url		= $('fieldset.iframe input[name="url"]').val();
					var code	= $('fieldset.iframe input[name="code"]').val();
					var width	= $('fieldset.iframe input[name="width"]').val();
					var height	= $('fieldset.iframe input[name="height"]').val();
					var bron	= $('fieldset.iframe input[name="bron"]').val();
					var mobiel	= $('fieldset.iframe input[name="mobiel"]').val();

					if(url){
						dialog.setContent('<iframe src="#" style="height: 400px; width: 100%; border: 0px;" scrolling="yes"></iframe><div class="source">Bron: <span>BRON</span></div>');
						dialog.find('>iframe').attr('src', url);
						dialog.find('>iframe').height(height ? height : 500);
					}else{
						//dialog.setContent(code + '<div class="source">Bron: <span>BRON</span></div>');

						var src = $('fieldset.iframe').attr('data-url');
						if(src.indexOf('#')>0) src = src.substr(0, src.indexOf('#'));
						if(src.indexOf('?')>0) src = src.substr(0, src.indexOf('?'));

						dialog.setContent('<iframe src="#" style="height: 400px; width: 100%; border: 0px;" scrolling="yes"></iframe><div class="source">Bron: <span>BRON</span></div>');
						dialog.find('>iframe').attr('src', src + '/embed');
						dialog.find('>iframe').height(height ? height : 500);
					}

					if(width) dialog.setWidth(width);
					dialog.find('>div>span').text(bron);
					dialog.show();
			}
		}).click();
	}

	$('fieldset.iframe:not(.open) input[type="submit"]').click(function(evt){
    if($('fieldset.iframe input[name="newwindow"]').val() > 0){
        window.open($(this).attr('data-url'));
    }else {
        window.location = $(this).attr('data-url');
    }
});

	if(typeof(SelectFancy)!='undefined'){
		SelectFancy();
	}else{
		$('select.select-fancy').each(function(){
			$(this).removeClass('select-fancy');
			$(this).parent().selectFancy();
		});
	}
	askQuestion();

	$('input#searchbar').smartSearch({
		search: function(search, instance){
			var url = '/ajax/calculations/search?q=' + escape(search);

			json.get(url, function(data){
				instance.setItems(data.items);
			}, function(ex, response){
				alert(ex + ', ' + response);
			});
		},
		left: 0,
		top: function(){ return ($('body.home fieldset').length > 0 ? $('body.home fieldset') : $('form#search')).height(); },
		width: function(){ return ($('body.home fieldset').length > 0 ? $('body.home fieldset') : $('form#search')).width(); },
		onconfirm: function(){ return false; },
		onclick: function(source){
			return false;
			source.parent('form').submit();
		}
	});

	$('a[href*=\\#]').on("click",function(e){
		if(this.hash.match(/\^#[a-z0-9-_]$/i)){
			var t = $(this.hash);
			var t = t.length && t || $('[name=' + this.hash.slice(1) + ']');
			if (t.length) {
				var tOffset = t.offset().top;
				$('html,body').animate({scrollTop: tOffset - 20}, 'slow');
				e.preventDefault();
			}
			}
	});

	if(window.location.hash){
		if(window.location.hash.match(/\^#[a-z0-9-_]$/i)){
			var t = $(window.location.hash);
			var t = t.length && t || $('[name=' + window.location.hash.substr(1) + ']');
			if (t.length) {
				var tOffset = t.offset().top;
				$('html,body').animate({scrollTop: tOffset - 20}, 'slow');
			}
		}
	}

	$('section.page .most-searched ol li a').each(function(){
		var size = 100;
		while($(this).parent().height() > 50) {
			$(this).css('font-size', (--size) + '%');
		}
	});

	$('section.page .most-searched').each(function(){
		var me = $(this);
		me.find('> h2').click(function(){
			me[!me.hasClass('open') ? 'addClass' : 'removeClass']('open');
		});
	});

	$('.desktop-button > a').click(function(evt){
		evt.preventDefault();
		$('html').addClass('desktop');
		$.post('/', {action: 'desktop'});
	});

	$('#reaction-form input[type="submit"]').click(function(){
		var params = $('#reaction-form .question-form').serializeForm();
		params.parent_id = $('#reaction-form').attr('data-id');

		json.post('/ajax/calculations/reaction', params, function(data){
			if(data.success=='OK'){
				$('#reaction-form').html(data.view);
				$('#reactions').append(data.update);
				if(typeof(data.reactionCount)!='undefined'){
					if(data.reactionCount>1){
						$('#reactions-count .notice').text('Er zijn ' + data.reactionCount + ' antwoorden gegeven');
					}else if(data.reactionCount==1){
						$('#reactions-count .notice').text('Er is 1 antwoord gegeven');
					}else{
						$('#reactions-count .notice').text('Er is nog niet gereageerd op deze vraag. Reageer jij?');
					}
				}
			}else{
				$('#reaction-form .question-form .error').each(function(){
					$(this).removeClass('error').attr('title', '');
				});
				$('#reaction-form .question-form').traverse(data.errors, function(element, item){
					element.addClass('error').attr('title', item);
				});
			}
		}, function(ex, response){
		});
	});

	$('.rating.normal .stars.input').rating();

	$('#afstand .rating.afstand .stars.input').ratingafstand();

	$('nav.questions').each(function(){
		var me = $(this);
		me.find('> ul > li.loadmore').click(function(){
			var more = $(this);
			var params = {
				calculation_id: me.attr('data-id'),
				offset: me.find('> ul > li:not(.loadmore)').length
			};
			$.get('/ajax/calculations/questions', params, function(response){
				json(response, function(data){
					more.before(data.view);
					more.find('>a>span').text(data.remain);
					if(data.remain <= 0) more.hide();
				}, function(ex){
				});
			}, 'text');
		});
	});
	if($('body').attr('data-tracking')){
		setTimeout(function(){
			$.post('/ajax/advert/callback', {data: $('body').attr('data-tracking')});
		}, 100);
	}

	$('[data-track]').click(function(){
		$.post('/ajax/advert/track', {data: $(this).attr('data-track')});
	});
	$('a[data-href]').click(function(){
		window.open($(this).attr('data-href'));
	});
});


$(document).ready(function(){
	return;
	var initial = $('body.home .intro .counter').text();
	var counter = $('.counter > em').flipCounter();
	setTimeout(function(){
		$('body.home .intro h1 > span').text('Op naar');

		var current = initial;

		var interval = setInterval(function(){
			current++;
			if(counter[2].flipUp(true)){
				if(counter[1].flipUp()){
					counter[0].flipUp();
				}
			}
			if(current==500){
				clearInterval(interval);
				setTimeout(function(){
					$('body.home .intro h1 > span').text('Zoek in');
					counter[2].flipTo(initial.charAt(2));
					counter[1].flipTo(initial.charAt(1));
					counter[0].flipTo(initial.charAt(0));
				}, 2000);
			}
		}, 80);

	}, 5000);
});

function updateTool(){
	var styles = [];

	$('.input-prefix.color').each(function(){
		var input = $(this).parent().find('input');
		if(input.val().length > 0){
			styles.push(input.attr('name') + '=' + escape(input.val()));
		}
	});

	$('#font-family').each(function(){
		var input = $(this);
		if(input.val().length > 0){
			styles.push(input.attr('name') + '=' + escape(input.val()));
		}
	});

	window.location.hash = $('#url').val();

	styles.push('url=' + escape($('#url').val()));


	var url = 'https://www.berekenen.nl/tools/embed?' + styles.join('&');

	$('#preview').attr('src', url);
}

$(document).ready(function(){
	$('.input-prefix.color').each(function(){
		var me = $(this);
		me.ColorPicker({
			color: me.val(),
			onShow: function (colpkr) {
				$(colpkr).fadeIn(500);
				return false;
			},
			onHide: function (colpkr) {
				$(colpkr).fadeOut(500);
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				me.find('span').css('backgroundColor', '#' + hex);
				me.find('span').removeClass('nocolor');
				me.parent().find('input').val(hex);
				updateTool();
			}
		});
		me.parent().find('input').keyup(function(){
			me.ColorPickerSetColor($(this).val());
			me.find('span').css('backgroundColor', '#' + $(this).val());
			updateTool();
		});
	});

	$('#font-family,#url').change(function(){ updateTool(); });

	$('#generate-code,#generate-code2').click(function(){
		var styles = [];

		$('.input-prefix.color').each(function(){
			var input = $(this).parent().find('input');
			if(input.val().length > 0){
				styles.push(input.attr('name') + ':' + input.val());
			}
		});

		$('#font-family').each(function(){
			var input = $(this);
			if(input.val().length > 0){
				styles.push(input.attr('name') + ':' + input.val());
			}
		});

		var html = '';
		html+= '<div' + (styles.length ? ' data-style="' + styles.join(';')+ '"' : '') + '>&copy; <a href="https://www.berekenen.nl/' + $('#url').val() + '">berekenen.nl</a></div>\n';
		html+= '<script src="https://www.berekenen.nl/tools.js"></script>';

		$('#embed-code').val(html).fadeIn(500);

		$('html,body').animate({scrollTop: $('#embed-code').offset().top}, 'slow');
	});

	if($('select#url').length && window.location.hash){
		var value = null;
		$('select#url option').each(function(){
			if($(this).attr('data-url') == window.location.hash.substr(1)){
				value = $(this).attr('value');
			}
		});
		$('select#url').val(value).change();
	}else if($('select#url').length){
		$('select#url').change();
	}

});

$(document).ready(function(){
	$('#valuta-tabs a').click(function(evt){
		evt.preventDefault();

		$('.valuta-list').css('display', 'none');

		$($(this).attr('href')).css('display', 'block');
	});


	$('aside .banner-desktop:not(.static)').each(function(){
		var me = $(this);
		var top = me.offset().top;
		$(window).scroll(function(){
			if($(window).scrollTop() > (top + 10)){
				me.css({top: 10, position: 'fixed'});
			}else if($(window).scrollTop() < (top + 10)){
				me.css({position: 'static'});
			}
		});
	});

	$('body').click(function(e) {
		Cookies.set('cookies_allowed', true);
		$('.cookie_place_reserve').hide();
		$('#cookie_notice_mobile').hide();
		$('#cookie_notice_desktop').hide();
	});

	window.onscroll = function (e) {
		Cookies.set('cookies_allowed', true);
		$('.cookie_place_reserve').hide();
		$('#cookie_notice_mobile').hide();
		$('#cookie_notice_desktop').hide();
	}

	$('body').bind('touchmove', function(e) {
		Cookies.set('cookies_allowed', true);
		$('.cookie_place_reserve').hide();
		$('#cookie_notice_mobile').hide();
		$('#cookie_notice_desktop').hide();
	});
});

(function($) {
	$.fn.mobileMenu = function(settings){
		var config = {};
		
		if(settings) $.extend(config, settings);
	
		this.each(function(){
			var source = $(this);
			var menu = null;
			
			source.click(function(){
				if(menu==null){
					menu = $(this).clone();
					menu.addClass('pop-up');
					
					var form = $(document.createElement('form'));
					form.attr({action: '/zoeken'});
					form.html('<label><span><input type="text" name="q"></span><em></em></label>');
					menu.find('> ul').before(form);
					
					var close = $(document.createElement('span'));
					close.click(function(){
						menu.removeClass('open');
					});
					menu.append(close);
					
					$(document.body).append(menu);
					
					form.find('input').keydown(function(evt){
						var value = $(this).val();
						
						if(value.length > 1){
							var url = '/ajax/calculations/search?q=' + escape(value);
							json.get(url, function(data){
								menu.find('> ul > li').remove();
								for(var i=0; i<data.items.length; i++){
									var item = data.items[i];
									var li = $(document.createElement('li'));
									li.html('<a></a>');
									li.find('> a').text(item.text);
									
									if(typeof(item.url)!='undefined'){
										li.find('> a').attr('href', item.url);
									}else if(typeof(item.value)!='undefined'){
										li.find('> a').attr('href', '/zoeken?q=' + escape(item.value));
									}else{
										li.find('> a').attr('href', '/zoeken?q=' + escape(item.text));
									}
									menu.find('> ul').append(li);
								}
							}, function(ex, response){
								alert(ex + ', ' + response);
							});
						}else{
							menu.find('> ul > li').remove();
							menu.find('> ul').append(source.find('> ul > li').clone());
						}
					});
				}
				setTimeout(function(){
					if(menu.hasClass('open')){
						menu.removeClass('open');
					}else{
						menu.addClass('open');
					}
				}, 10);
				
				
			});
		});
		return this;
	};
})(jQuery);


(function($) {
	$.fn.mobileSearch = function(settings){
		var config = {};
		
		if(settings) $.extend(config, settings);
	
		this.each(function(){
			var source = $(this);
			var menu = null;
			
			source.click(function(){
				if(menu==null){
					menu = $(document.createElement('nav'));
					menu.addClass('pop-up');
					menu.addClass('no-full');
					menu.addClass('right');
					menu.html('<ul></ul>');
					
					var form = $(document.createElement('form'));
					form.attr({action: '/zoeken'});
					form.html('<label><span><input type="text" name="q" placeholder="Zoek je berekening"></span><em></em></label>');
					menu.find('> ul').before(form);
					
					
					$(document.body).append(menu);
					
					form.find('input').keydown(function(evt){
						var value = $(this).val();
						
						if(value.length > 1){
							var url = '/ajax/calculations/search?q=' + escape(value);
							json.get(url, function(data){
								menu.find('> ul > li').remove();
								for(var i=0; i<data.items.length; i++){
									var item = data.items[i];
									var li = $(document.createElement('li'));
									li.html('<a></a>');
									li.find('> a').text(item.text);
									
									if(typeof(item.url)!='undefined'){
										li.find('> a').attr('href', item.url);
									}else if(typeof(item.value)!='undefined'){
										li.find('> a').attr('href', '/zoeken?q=' + escape(item.value));
									}else{
										li.find('> a').attr('href', '/zoeken?q=' + escape(item.text));
									}
									menu.find('> ul').append(li);
								}
							}, function(ex, response){
								alert(ex + ', ' + response);
							});
						}else{
							menu.find('> ul > li').remove();
							menu.find('> ul').append(source.find('> ul > li').clone());
						}
					});
				}
				setTimeout(function(){
					if(menu.hasClass('open')){
						menu.removeClass('open');
					}else{
						menu.addClass('open');
					}
				}, 10);
				
				
			});
		});
		return this;
	};
})(jQuery);

$(document).ready(function(){
	$('header nav').mobileMenu();
	
	$('header > div > span').mobileSearch();
});

function autocomplete() {
	if(document.getElementById('SearchPlaatsVan')){
		var placesAutocomplete = places({
		    appId: 'plL3WG5LBQDA',
		    apiKey: 'af14e24e27727286e2d95292e6fb3193',
		    container: document.querySelector('#SearchPlaatsVan')
		});

		var $address = document.querySelector('#SearchPlaatsVan')
		placesAutocomplete.on('change', function(e) {
		    $address.textContent = e.suggestion.value
		});

		placesAutocomplete.on('clear', function() {
		    $address.textContent = 'none';
		});

		var placesAutocomplete = places({
		    appId: 'plL3WG5LBQDA',
		    apiKey: 'af14e24e27727286e2d95292e6fb3193',
		    container: document.querySelector('#SearchPlaatsNaar')
		});

		var $address = document.querySelector('#SearchPlaatsNaar')
		placesAutocomplete.on('change', function(e) {
		    $address.textContent = e.suggestion.value
		});

		placesAutocomplete.on('clear', function() {
		    $address.textContent = 'none';
		});

		// var input = document.getElementById('SearchPlaatsVan');
	// 	var autocomplete = new google.maps.places.Autocomplete(input);
		
		// var input2 = document.getElementById('SearchPlaatsNaar');
	// 	var autocomplete2 = new google.maps.places.Autocomplete(input2);	
	}

}


function getResult(){
	var item = new Array();
	hash= window.location.hash.substring(1); //verkrijg de hash zonder #
	action = 'getresult';
	var url = window.location.origin + '/a-z/afstand';
	$.post(url, {hash: hash, action: action}, function(response){
		//console.log(response);
		$('#afstand')[0].innerHTML = response;
		
		loadMap();
	});
}

function init(){
	getResult();
}

$(document).ready(function(){
	if(window.location.hash.substring(1) && $('#afstand').length){
		init(); 
	}else{
		if($('#afstand').length) autocomplete();	
	}
});

$(window).on('hashchange', function (e) {
	if($('#map-canvas').length) init();
});

if (window.location.hash) {
	$(window).trigger('hashchange')
}
var time = 0;
var distance = 0;
var lineLenght;
var start;
var end;
var mode;


function getData(){
	var data = $('#map');
	mode = data.attr('data-mode');
	start = new google.maps.LatLng(data.attr('data-vanlat'),data.attr('data-vanlong')) 
	end = new google.maps.LatLng(data.attr('data-naarlat'),data.attr('data-naarlong'))
}


function seconds2time (seconds) {
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    var seconds = seconds - (hours * 3600) - (minutes * 60);
    var timeIntern = "";

    if (hours != 0) {
      timeIntern = hours+" uur ";
    }
    if (minutes != 0 || time !== "") {
      minutes = (minutes < 10 && timeIntern !== "") ? "0"+minutes : String(minutes);
      timeIntern += minutes +" minuten";
    }
    if (timeIntern === "") {
     	timeIntern = "Er is geen tijd bekend";
    }
    else {
      
    }
    return timeIntern;
}

function roundKm(number){
	var number = Math.round( number * 10 ) / 10;
	var number = number.toFixed(1);
	var number = parseFloat(number)

	return number;
}



var directionsDisplay;
var directionsService;
var bounds;
var polyLengthInMeters;

function initialize() {
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsService = new google.maps.DirectionsService();
	bounds = new google.maps.LatLngBounds();
	bounds.extend(start);
	bounds.extend(end);
	
	mapOptions = {
		mapTypeId : 'roadmap'
	};
	var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById('directions-panel'));

	var LineCoordinates = [start, end];
	var Line = new google.maps.Polyline({
		path : LineCoordinates,
		geodesic : true,
		strokeColor : '#FF0000',
		strokeOpacity : 1.0,
		strokeWeight : 2
	});

	Line.setMap(map);
	
	polyLengthInMeters = google.maps.geometry.spherical.computeLength(Line.getPath().getArray());
	lineLenght = roundKm((polyLengthInMeters / 1000));
	document.getElementById('line').innerHTML += lineLenght + ' km';
}

function calcRoute() {

	var selectedMode = mode;
	var request = {
		origin : start,
		destination : end,
		travelMode : google.maps.TravelMode[selectedMode]
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			// Display the distance:

			distance = roundKm((response.routes[0].legs[0].distance.value / 1000));
			document.getElementById('distance').innerHTML = distance + ' km';
			time = seconds2time(response.routes[0].legs[0].duration.value);
			// Display the duration:
			document.getElementById('duration').innerHTML = time;
			replaceVariables();
			directionsDisplay.setDirections(response);
		}
	});

}

function loadMap(){
	if($('#map-canvas').length){
		getData();
		initialize();
		calcRoute();
	}
}

function goPost(url, params){
	if(url!=null && typeof(url)=='object') url = url.href;

	var form = $('<form method="post"></form>').appendTo(document.body);
	if(url!=null) form.attr('action', url);
	
	for(x in params){
		form.append('<input type="hidden" name="' + x + '" value="' + params[x] + '"/>');
	}
	
	form.submit();
	return false;
}

$('.tab-item').on('click', function(){
	if( !$(this).parent().hasClass('active') ){
		var mode = $(this).data('mode');
		var van = $( "div#van" ).text();
		var naar = $( "div#naar" ).text(); 
		var url = '/afstand';
		var params = {van:van, naar:naar, mode:mode}; 
		goPost(url, params);
	}
});

function replaceVariables(){
	
	$('p').each(function() {
	    var text = $(this).text().replace('{afstandrecht}', lineLenght).replace('{afstandvervoer}', distance).replace('{tijd}', time);
	    $(this).text(text);
	});
}

$(document).ready(function() {
	setTimeout(loadMap, 150);
});