$(document).ready(function() {
	var w = '.widget.submenu';
	$(w + ' ul').hide();
	//Select active link
	var current = $(w + ' a.current');
	if (current.length === 0) {
		current = $(w + ' ul:first').show();
	} else {
		current.parents('ul').show();
		$(w + ' a.current + ul').show();
	}
	
	/*$(w + ' li').click(function(e) {
		$(this).children('ul').toggle();
		return false;
	});*/
});/**
 * Modified for Vitae by Warnar Boekkooi
 */
(function($) {	
	/*
    * ui.dropdownchecklist
    *
    * Copyright (c) 2008-2009 Adrian Tosca
    * Dual licensed under the MIT (MIT-LICENSE.txt)
    * and GPL (GPL-LICENSE.txt) licenses.
    *
    */
    // The dropdown check list jQuery plugin transforms a regular select html element into a dropdown check list.
    $.widget("ui.dropdownchecklist", {
        // Creates the drop container that keeps the items and appends it to the document
        _appendDropContainer: function() {
    		// the container is wrapped in a div + initially hidden
            var wrapper = $('<div class="ui-dropdownchecklist-dropcontainer-wrapper" style="position: absolute; left: -3300px; top: -3300px; width: 3000px"/>');
	        wrapper.append($('<div class="ui-dropdownchecklist-dropcontainer" style="overflow-y:auto"/>')); // the actual container
			$(document.body).append(wrapper);
			//wrapper.insertAfter(this.sourceSelect);
            // flag that tells if the drop container is shown or not
            wrapper.drop = false;

			// Add close + remove select
			var footer = $('<div class="ui-dropdownchecklist-dropcontainer-footer"><span class="ui-dropdownchecklist-dropcontainer-footer-close"/></div>');
						
			var deselect = $('<span/>').text('alles deselecteren');
			var self = this;
			deselect.click(function(event) {			
				wrapper.find("input:checked:not([disabled])").each(function(){
					$(this).removeAttr('checked');
					self._syncSelected($(this));
				});
				
				event.stopImmediatePropagation();
			});
			footer.append(deselect);
						
            wrapper.append(footer);
			
			if ($.browser.msie) {
				wrapper.prepend($('<div class="bdr-rgt"/>'));
				footerBdr = $('<div class="bdr-blr"><div class="bdr-bl"/><div class="bdr-b"/><div class="bdr-br"/></div>');
				wrapper.append(footerBdr);
			}
			
            return wrapper;
        },
		_isDropDownKeyShortcut: function(e) {
			return e.altKey && ($.ui.keyCode.DOWN == (e.keyCode || e.which));// Alt + Down Arrow
		},
		_isDroDownCloseKey: function(e) {
			return $.ui.keyCode.ESCAPE == (e.keyCode || e.which);
		},
		_handleKeyboard: function(e) {
			var self = this;
			if (self._isDropDownKeyShortcut(e)) {
				e.stopPropagation();
				self._toggleDropContainer();
				self.dropWrapper.find("input:first").focus();
			} else if (self.dropWrapper != null && self.dropWrapper.drop && self._isDroDownCloseKey(e)) {
				self._toggleDropContainer();
			}
		},
        // Creates the control that will replace the source select and appends it to the document
        // The control resembles a regular select with single selection
        _appendControl: function() {
            var self = this, sourceSelect = this.sourceSelect;
			
            var sourceParent = $(self.element).parent();

            // the controls is wrapped in a span with inline-block display
			var wrapper = sourceParent.children('span.ui-dropdownchecklist-wrapper')
				.disableSelection()
				.css({
	                display: "inline-block",
	                cursor: "default"
	            });

            // the actual control, can be styled to set the border and drop right image
			var control = wrapper.children('span.ui-dropdownchecklist')
				.css({
	                display: "inline-block"
	            })
            	.attr("tabIndex", 0)
            	.keyup(function(e) {self._handleKeyboard(e);});

            // the text container keeps the control text that is build from the selected (checked) items
			var textContainer = control.children('span.ui-dropdownchecklist-text')
				.disableSelection()
				.css({
	                display: "inline-block",
	                overflow: "hidden"
	            });

            // add the hover styles to the control
            wrapper.hover(function() {
                if (!self.disabled) {
                    control.toggleClass("ui-dropdownchecklist-hover");
                }
            }, function() {
                if (!self.disabled) {
                    control.toggleClass("ui-dropdownchecklist-hover");
                }
            })
            // clicking on the control toggles the drop container
            .click(function(event) {
                if (!self.disabled) {
                    event.stopPropagation();
                    self._toggleDropContainer();
                }
            });

            return wrapper;
        },
        // Creates a drop item that coresponds to an option element in the source select
        _createDropItem: function(index, value, text, checked, disabled, indent) {
            var self = this;
            // the item contains a div that contains a checkbox input and a span for text
            // the div
            var itemClasses = 'ui-dropdownchecklist-item ' + 
            	(indent ? 'ui-dropdownchecklist-indent ' : '') +
            	(self.options.noCheckbox ? 'ui-dropdownchecklist-no-checkbox ' : '') + 
            	(disabled ? 'ui-dropdownchecklist-item-disabled' : '');
            
            var item = '<div style="white-space:nowrap" class="' + itemClasses + '">';
            
            var checkedString = checked ? ' checked="checked"' : '';
			var disabledString = disabled ? ' disabled="disabled"' : '';
			var idBase = (self.sourceSelect.attr("id") || "ddcl");
			var id = idBase + index;
			var checkBoxClass = 'ui-dropdownchecklist-checkbox '+ 
    			(checked ? 'checked' : '');
			
            var checkBox;
            if (self.initialMultiple) { // the checkbox
                checkBox = '<input type="checkbox" value="' + value + '" index="' + index + '" id="' + id + '"' + checkedString + disabledString + '/>';
            } else { // the radiobutton
                checkBox = '<input type="radio" value="' + value + '" index="' + index + '" id="' + id + '" name="' + idBase + '"' + checkedString + disabledString + '/>';
            }
            item += checkBox + "</div>";            
            item = $(item);
            
            // the text
            var labelClass =  'ui-dropdownchecklist-text ' + 
        		(checked ? 'checked' : '');
            	
            var label = $('<label style="cursor: default" for="' + id + '" class="' + labelClass + '"/>').text(text);
			item.append(label);
            return item;
        },
		_createGroupItem: function(text) {
			var group = $('<div class="ui-dropdownchecklist-group" style="white-space: nowrap" />');
            var label = $('<span class="ui-dropdownchecklist-text" style="cursor: default;width: 100%"/>').text(text);
			group.append(label);
			return group;
		},
        // Creates the drop items and appends them to the drop container
        // Also calculates the size needed by the drop container and returns it
        _appendItems: function() {
            var self = this, sourceSelect = this.sourceSelect, dropWrapper = this.dropWrapper;
            var dropContainerDiv = dropWrapper.find(".ui-dropdownchecklist-dropcontainer");
            dropContainerDiv.css({ "float": "left" }); // to allow getting the actual width of the container
			sourceSelect.children().each(function(index) { // when the select has groups
				var opt = $(this);
                if (opt.is("option")) {
                    self._appendOption(opt, dropContainerDiv, index, false);
                } else {
                    var text = opt.attr("label");
                    var group = self._createGroupItem(text);
                    dropContainerDiv.append(group);
                    self._appendOptions(opt, dropContainerDiv, index, true);
                }
			});
			
			// Bind events to the checkboxes and labels
            // check/uncheck the item on clicks on the entire item div
            var checkItem = function(e) {
                e.stopPropagation();
				var checkBox = e.currentTarget.tagName == 'LABEL' ? $(e.currentTarget).prev() : $(e.currentElement).find('input');
				if ($(checkBox).attr("disabled") != true && $(checkBox).attr("disabled") != "disabled" ) {
	                var checked = checkBox.attr("checked");
	                checkBox.attr("checked", !checked);
	                self._syncSelected(checkBox);
	                self.sourceSelect.trigger("change", 'ddcl_internal');
				}
				return false;
            };
			dropContainerDiv.find('div.ui-dropdownchecklist-item').hover(function() {
	                item.addClass("ui-dropdownchecklist-item-hover");
	            }, function() {
	                item.removeClass("ui-dropdownchecklist-item-hover");
	            })
	            .keyup(function(e) {self._handleKeyboard(e);})
	            .click(checkItem);
            // clicking on the checkbox synchronizes the source select
			dropContainerDiv.find('div.ui-dropdownchecklist-item input[type='+(self.initialMultiple?'checkbox':'radio')+']').click(function(e) {
				e.stopPropagation();
				if (!disabled) {
	                self._syncSelected($(this));
	                self.sourceSelect.trigger("change", 'ddcl_internal');
				}
	        });
			dropContainerDiv.find('div.ui-dropdownchecklist-item label').click(checkItem);
			
			//self._appendOptions(sourceSelect, dropContainerDiv, false); // when no groups
            var divWidth = dropContainerDiv.outerWidth() + 18;
            var divHeight = dropContainerDiv.outerHeight();
            dropContainerDiv.css({ "float": "" }); // set it back
            return { width: divWidth, height: divHeight };
        },
		_appendOptions: function(parent, container, parentIndex, indent) {
			var self = this;
			parent.children("option").each(function(index) {
                var option = $(this);
                var childIndex = (parentIndex + "." + index);
                self._appendOption(option, container, childIndex, indent);
            });
		},
        _appendOption: function(option, container, index, indent) {
            var self = this;
            var text = option.text();
            var value = option.val();
            var selected = option.attr("selected");
			var disabled = option.attr("disabled");
            var item = self._createDropItem(index, value, text, selected, disabled, indent);            
            container.append(item);
        },
        // Synchronizes the items checked and the source select
        // When firstItemChecksAll option is active also synchronizes the checked items
        // senderCheckbox parameters is the checkbox input that generated the synchronization
        _syncSelected: function(senderCheckbox) {
            var self = this, options = this.options, sourceSelect = this.sourceSelect, dropWrapper = this.dropWrapper;
            
            /**
             * if select is hacky and wants to look like single-select, allow it.
             * clear all already selected neighbours
             */
            if (sourceSelect.hasClass('widget-forceSingle')) {
            	$('input[id!='+senderCheckbox.attr('id')+']', 
            			senderCheckbox.parent().parent()
            		).attr('checked', false);
            }
            
            var allCheckboxes = dropWrapper.find("input:not([disabled])");
            if (options.firstItemChecksAll) {
                // if firstItemChecksAll is true, check all checkboxes if the first one is checked
                if (senderCheckbox.attr("index") == 0) {
                    allCheckboxes.attr("checked", senderCheckbox.attr("checked"));
                } else {
                    // check the first checkbox if all the other checkboxes are checked
                    var allChecked;
                    allChecked = true;
                    allCheckboxes.each(function(index) {
                        if (index > 0) {
                            var checked = $(this).attr("checked");
                            if (!checked) allChecked = false;
                        }
                    });
                    var firstCheckbox = allCheckboxes.filter(":first");
                    firstCheckbox.attr("checked", false);
                    if (allChecked) {
                        firstCheckbox.attr("checked", true);
                    }
                }
            }

            // do the actual synch with the source select
            var selectOptions = sourceSelect.get(0).options;
            allCheckboxes.each(function(index) {
				var elt = $(this);
				var checked = elt.attr("checked");
                $(selectOptions[index]).attr("selected", checked);
				
				if (checked) {
					elt.next().addClass('checked');
					elt.addClass('checked');
				} else {
					elt.next().removeClass('checked');
					elt.removeClass('checked');
				}
            });

            // update the text shown in the control
            self._updateControlText();
        },
        _sourceSelectChangeHandler: function(event) {
            var self = this, dropWrapper = this.dropWrapper;
            if(this.dropWrapper != null) {
            	dropWrapper.find("input").val(self.sourceSelect.val())
            		.removeClass('checked')
            		.next().removeClass('checked');
            	dropWrapper.find("input:checked").addClass('checked').next().addClass('checked');
            }
			
        	// update the text shown in the control
        	self._updateControlText();
        },
        // Updates the text shown in the control depending on the checked (selected) items
        _updateControlText: function() {
            var self = this, sourceSelect = this.sourceSelect, options = this.options, controlWrapper = this.controlWrapper;
            var firstSelect = sourceSelect.find("option:first");
            var allSelected = null != firstSelect && firstSelect.attr("selected");
            var selectOptions = sourceSelect.find("option");
            var text = self._formatText(selectOptions, options.firstItemChecksAll, allSelected);
            var controlLabel = controlWrapper.find(".ui-dropdownchecklist-text");
            controlLabel.text(text).attr("title", text);
        },
        // Formats the text that is shown in the control
        _formatText: function(selectOptions, firstItemChecksAll, allSelected) {
            var text;
            if (null != this.options.textFormatFunction) {
                return this.options.textFormatFunction(selectOptions);
            } else if (firstItemChecksAll && allSelected) {
                // just set the text from the first item
                text = selectOptions.filter(":first").text();
            } else {
                // concatenate the text from the checked items
                text = "";
                selectOptions.each(function() {
                    if ($(this).attr("selected")) {
                        text += $(this).text() + ", ";
                    }
                });
                if (text.length > 0) {
                    text = text.substring(0, text.length - 2);
                }
            }
            if (text == "") text = this.options.emptyText;
            return text;
        },
        // Shows and hides the drop container
        _toggleDropContainer: function() {        	
            var self = this, dropWrapper = this.dropWrapper, options = this.options, controlWrapper = this.controlWrapper;

        	if(this.dropWrapper == null) {
        		// create the drop container where the items are shown
                var dropWrapper = self._appendDropContainer();
                self.dropWrapper = dropWrapper;

                // append the items from the source select element
                var dropCalculatedSize = self._appendItems();

                // updates the text shown in the control
                //self._updateControlText(controlWrapper, dropWrapper, sourceSelect);

                // set the sizes of control and drop container
                self._setSize(dropCalculatedSize);

                // BGIFrame for IE6
    			if (options.bgiframe && typeof self.dropWrapper.bgiframe == "function") {
    				self.dropWrapper.bgiframe();
    			}
    			
        		dropWrapper = self.dropWrapper;
        	}
        	
            // hides the last shown drop container
            var hide = function() {
                var instance = $.ui.dropdownchecklist.drop;
                if (null != instance) {
                    instance.dropWrapper.css({
                        top: "-3300px",
                        left: "-3300px"
                    });
                    instance.controlWrapper.find(".ui-dropdownchecklist").toggleClass("ui-dropdownchecklist-active");
					instance.dropWrapper.find("input").attr("tabIndex", -1);
                    instance.dropWrapper.drop = false;
                    $.ui.dropdownchecklist.drop = null;
                    $(document).unbind("click", hide);
					self.sourceSelect.trigger("blur");
                }
            };
            // shows the given drop container instance
            var show = function(instance) {
                if (null != $.ui.dropdownchecklist.drop) {
                    hide();
                }
                instance.dropWrapper.css({
                    top: instance.controlWrapper.offset().top + instance.controlWrapper.outerHeight() + "px",
                    left: instance.controlWrapper.offset().left + "px"
                });
				var ancestorsZIndexes = controlWrapper.parents().map(
					function() {
						var zIndex = $(this).css("z-index");
						return isNaN(zIndex) ? 0 : zIndex;}
					).get();
				var parentZIndex = Math.max.apply(Math, ancestorsZIndexes);
				if (parentZIndex > 0) {
					instance.dropWrapper.css({
						zIndex: (parentZIndex+1)
					});
				}
                instance.controlWrapper.find(".ui-dropdownchecklist").toggleClass("ui-dropdownchecklist-active");
				instance.dropWrapper.find("input").attr("tabIndex", 0);
                instance.dropWrapper.drop = true;
                $.ui.dropdownchecklist.drop = instance;
                $(document).bind("click", hide);
				self.sourceSelect.trigger("focus");
            };
            if (dropWrapper.drop) {
                hide(self);
            } else {
                show(self);
            }
        },
        _setSizeControl: function() {
        	var options = this.options, controlWrapper = this.controlWrapper;
        	
        	var controlWidth;
            // use the width from options if set, otherwise set the same width as the drop container
            if (options.width) {
                controlWidth = parseInt(options.width);
            } else {
            	var widthExtra = parseInt(controlWrapper.parent().css('padding-left')) + parseInt(controlWrapper.parent().css('padding-left'));
            	widthExtra += controlWrapper.width() - controlWrapper.find(".ui-dropdownchecklist-text").width();
            	
            	controlWidth = controlWrapper.parent().innerWidth() - widthExtra;
                //controlWidth = dropCalculatedSize.width;
                var minWidth = options.minWidth;
                // if the width is to small (usually when there are no items) set a minimum width
                if (controlWidth < minWidth) {
                    controlWidth = minWidth;
                }
            }
            controlWrapper.find(".ui-dropdownchecklist-text").css({
                width: controlWidth + "px"
            });
        },
        // Set the size of the control and of the drop container
        _setSize: function(dropCalculatedSize) {
            var options = this.options, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;

            // for the drop container get the actual (outer) width of the control.
            // this can be different than the set one depening on paddings, borders etc set on the control
            var controlOuterWidth = controlWrapper.outerWidth();

            // the drop container height can be set from options
            var dropHeight = options.maxDropHeight ? parseInt(options.maxDropHeight) : dropCalculatedSize.height;
            // ensure the drop container is not less than the control width (would be ugly)
            var dropWidth = dropCalculatedSize.width < controlOuterWidth ? controlOuterWidth : dropCalculatedSize.width;

            $(dropWrapper).css({
                width: dropWidth + "px"/*,
                height: dropHeight +  + "px"*/
            });

            dropWrapper.find(".ui-dropdownchecklist-dropcontainer").css({
                height: dropHeight + "px"
            });
        },
        // Initializes the plugin
        _init: function() {
            var self = this, options = this.options;

            // sourceSelect is the select on which the plugin is applied
            var sourceSelect = self.element;
            self.initialDisplay = sourceSelect.css("display");
            sourceSelect.css("display", "none");
            self.initialMultiple = sourceSelect.attr("multiple");
            // i removed this because 
            //sourceSelect.attr("multiple", "multiple");
            self.sourceSelect = sourceSelect;
            
            // take a look if source select has multiple behaviour or is forced to be not multiple
            // this means change of display style
            options.noCheckbox = !sourceSelect.attr('multiple') || sourceSelect.hasClass('widget-forceSingle');

            // append the control that resembles a single selection select
            var controlWrapper = self._appendControl();
            self.controlWrapper = controlWrapper;
            
            self._setSizeControl();
            self._updateControlText();

          // listen for change events on the source select element
          // ensure we avoid processing internally triggered changes
          self.sourceSelect.change(function(event, eventName) {
            if (eventName != 'ddcl_internal') {
                self._sourceSelectChangeHandler(event);
            }
          });
        },
        enable: function() {
            this.controlWrapper.find(".ui-dropdownchecklist").removeClass("ui-dropdownchecklist-disabled");
            this.disabled = false;
        },
        disable: function() {
            this.controlWrapper.find(".ui-dropdownchecklist").addClass("ui-dropdownchecklist-disabled");
            this.disabled = true;
        },
        destroy: function() {
            $.widget.prototype.destroy.apply(this, arguments);
            this.sourceSelect.css("display", this.initialDisplay).attr("multiple", this.initialMultiple);
            this.controlWrapper.unbind().remove();
            this.dropWrapper.remove();
        }
    });

    $.extend($.ui.dropdownchecklist, {
        defaults: {
            width: null,
            maxDropHeight: null,
            firstItemChecksAll: false,
            minWidth: 50,
            bgiframe: false,
			emptyText: ""
        }
    });

})(jQuery);$(document).ready(function() {
	var cache = {};
	$('input#pcplaats').autocomplete({
		source: function(request, response) {
			if (cache.term == request.term && cache.content) {
				response(cache.content);
				return;
			}
			if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
				response($.ui.autocomplete.filter(cache.content, request.term));
				return;
			}
			$.ajax({
				url: "/vacatures/autocomplete/",
				dataType: "json",
				data: request,
				success: function(data) {
					cache.term = request.term;
					cdata = $.map(data, function(item) {
						return {
							label: item.city + ' ('+item.postcode+')',
							value: item.numeric ? item.postcode : item.city,
							id: item.postcode,
							isnum: item.numeric ? 1 : 0
						}
					});
					cache.content = cdata;
					response(cdata);
				}
			});
		},
		minLength: 2,
		select: function(event, ui) {
			if (ui.item) {
				$('#postcode-element').val(ui.item.id);
			}
		}
	});

	$('label.hint').hint();
	$('select.custom').dropdownchecklist({
		maxDropHeight: 100,
		textFormatFunction: function(options) {
			var mylabel = typeof $(options[0]).parent().attr('my-label') == 'undefined' || $(options[0]).parent().attr('my-label') == '' ? 'geen' : $(options[0]).parent().attr('my-label');
            var selectedOptions = options.filter(":selected");
            var countOfSelected = selectedOptions.size();
            var size = options.size();
            switch(countOfSelected) {
                case 0: return mylabel;
                case 1: return selectedOptions.text();
                case size: return "alles";
                default: return countOfSelected + ' ' + $(options[0]).parent().attr('data-plural');
            }
        }
	});

	$('#top-bar .search').focus(function(){
		var self = $(this);
		self.addClass('search-full');
	}).blur(function(){
		var self = $(this);
		setTimeout(function() { self.removeClass('search-full'); }, 200);
	});

	// Add iframe dialog to the page
	var layerBtns = $('.showinlayer');
	if(layerBtns.length > 0) {
		var iframe = $('<iframe width="100%" height="100%" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" />');
		var dialog = $('<div />').attr({ id: 'layerDialog' }).append(iframe);
		$('body').append(dialog);

		dialog.dialog({ autoOpen: false, modal: true, width: 'auto', resizable: false, autoResize: true,  close: function(event, ui) { iframe.attr({ src: '' }); } });

		iframe.bind('load', function(){
			var h = iframe.contents();
			if(h.length > 0) {
				h=h.find('body').outerHeight();
				iframe.css({height: h + 30});
			}
		});

		layerBtns.bind('click', function(event){
			event.preventDefault();

			var self = $(this);

			// Change href
			var uri = self.attr('href').split('?');
			var src = uri[0];
			if (src.substring(src.length-1) != '/') {
				src += '/';
			}
			if (src.indexOf('iframe') < 0) {
				src += 'iframe/1/';
			}
			uri[0] = src;

			iframe
				.attr({src: uri.join('?')})
				.css({ height: self.attr('data-height'), width: self.attr('data-width') });
			dialog.dialog('option', 'title', self.attr('title'));
			dialog.dialog('open');
		});
	}
});
jQuery.fn.extend({
	hint: function() {
		return this.each(function(){
			var label = jQuery(this);
			var input = label.parent().find('#' + label.attr('for'));


			if (jQuery.browser.safari && input.attr('type') == 'file') {
				label.hide();
				return;
			}

			var hide = function() {
			  label.css({ textIndent: -10000 });
			};

			var show = function() {
			  if (input.val() == '') {
				  label.css({ textIndent: 0 });
			  }
			};

			// handlers
			input.focus(hide).blur(show);
		  	label.click(function(event){
		  		input.focus();
		  		return false;
		  	});

			if (input.val() != '') {
				hide();
			}
		});
	}
});
function closeLayerDialog() {
	$('#layerDialog').dialog('close');
}



$(document).ready(function() {
	var b=document.body;
	if (1044 > b.clientWidth) {
		$(b).addClass('small-screen');
	}
})

