var educationRecord			= "";
var experienceRecord		= "";
var educationRecordCount	= 1;
var experienceRecordCount	= 1;

$(document).ready(function(){
	$("#vacancy #preview").each(function(){
		$(document).blur(function(){
			$("#preview").parent().attr("action", "");
			$("#preview").parent().attr("target", "_self");
		});
		$(this).click(function(){
			$(this).parent().attr("action", "/management/vacancies/preview.php");
			$(this).parent().attr("target", "_blank");
		});
	});
	
	$("#vacancy #save").click(function(){
		$(this).parent().attr("action", "");
		$(this).parent().attr("target", "_self");
	});
	
	$("#vacancy #concept").click(function(){
		if(confirm("Weet u zeker dat u deze vacature als concept op wilt slaan?")) {
			$(this).parent().unbind('submit');
		}
	});
	
	$("#vacancy").css("display", "block");
	
	// Initialize multiselect
	$("#search-a-job form").each(function(){
		$(this).attr("id", "hasJS");
		$(this).find("select").multiSelect({
			select_all_min: 4,
			no_selection: "Selecteer...",
			selected_text: " items geselecteerd",
			selected_all: "Alles selecteren"
		});
	});
	
	$(".hasJS").css("display", "none");
	
	// Initialize login form
	$("#loginBtn a").click(function() {
		if($(".loginForm.dropdown").css("display") == "none") {
			$(".loginForm.dropdown").show("slow",function() {
				$(this).find("#username").focus();
			});
		}
		else {
			$(".loginForm.dropdown").hide("slow");
		}
		return false;
	});
	$(".loginForm input").focus(function() {
		this.select();
	});
	
	// Initialize CV flexible form fields
	$(".education-record:first").each(function() {
		educationRecord = $(this);
	});
	$(".experience-record:first").each(function() {
		experienceRecord = $(this);
	});
	$(".education-record:last").each(function() {
		educationRecordCount = parseInt(this.id.match(/\d+$/)) + 1;
	});
	$(".experience-record:last").each(function() {
		experienceRecordCount = parseInt(this.id.match(/\d+$/)) + 1;
	});
	$("#addEducationBtn").click(function() {
		// Clone object and events
		$(this).before(educationRecord.clone(true));
		$(".education-record:last, .education-record:last > *").each(function() {
			$(this).find("input").each(function() {
				$(this).val('');
			});
			if(parseInt(this.id.match(/\d+/)) > 0) {
				this.id = this.id.replace(/\d+/, educationRecordCount);
			}
		});
		educationRecordCount++;
		addDeleteFunction();
		return false;
	});
	$("#addExperienceBtn").click(function() {
		// Clone object and events
		$(this).before(experienceRecord.clone(true));
		$(".experience-record:last, .experience-record:last > *").each(function() {
			$(this).find("input").each(function() {
				$(this).val('');
			});
			if(parseInt(this.id.match(/\d+/)) > 0) {
				this.id = this.id.replace(/\d+/, experienceRecordCount);
			}
		});
		experienceRecordCount++;
		addDeleteFunction();
		return false;
	});
	// Functionality for form record deletion
	addDeleteFunction();
	
	// Functionality for search engine
	buildMultiselects();
	
	// Initialize Google maps functionality
	if(typeof(load) == "function"){
		setTimeout(load, 300);
	}
	
	// Initialize job search setting form
	$("#resultsPerPage, #orderBy").change(function() {
		$(this).parent().submit();
	});
	$("#jobSearchSettings").addClass("hidden");
	
	// Initialize formbuilder date components
	$(".input_date").each(function() {
		dateArray = $(this).val().split("-");
		y = dateArray[0] == undefined ? '' : dateArray[0];
		m = dateArray[1] == undefined ? '' : dateArray[1];
		d = dateArray[2] == undefined ? '' : dateArray[2];
		
		input_date = createDateSubBox({
			'id': $(this).attr('id')+'-d',
			'class': 'datesmall',
			'value': d,
			'maxlength': 2
		})
		+createDateSubBox({
			'id': $(this).attr('id')+'-m',
			'class': 'datesmall',
			'value': m,
			'maxlength': 2
		})
		+createDateSubBox({
			'id': $(this).attr('id')+'-y',
			'class': 'datelarge',
			'value': y,
			'maxlength': 4
		});
		
		$(this).after(input_date);
		
		$("#"+$(this).attr('id')+"-d").bind("keydown", numericInput);
		$("#"+$(this).attr('id')+"-m").bind("keydown", numericInput);
		$("#"+$(this).attr('id')+"-y").bind("keydown", numericInput);
		
		$("#"+$(this).attr('id')+"-d").bind("keyup", input_date_update);
		$("#"+$(this).attr('id')+"-m").bind("keyup", input_date_update);
		$("#"+$(this).attr('id')+"-y").bind("keyup", input_date_update);
		
		$(this).css('display', 'none');
	});
	
	if(jQuery.browser.msie){
		buttonfix();
	}
	
	$("#subnav .hassubs").each(function(){
		if(!$(this).hasClass("open") && !$(this).hasClass("active")) {
			$(this).find("ul").css("display", "none");
		}
	});
	
	/*$("#cv-plaatsen #education-container").each(function() {
		var validater2 = $("#cv-plaatsen").validate({
			rules: {
				"education[]": {
					required: true
				},
				"date_finished[]": {
					required: true
				}
			},
			messages: {
				"education[]": {
					required: "Vult u alstublieft een opleiding in"
				},
				"date_finished[]": {
					required: "Vult u alstublieft de corresponderende diplomadatum in"
				}
			}
		});
	});*/
});

function buttonfix() {
    var buttons = document.getElementsByTagName('button');
    for (var i=0; i<buttons.length; i++) {
        if(buttons[i].onclick) continue;
        
        buttons[i].onclick = function () {
            for(j=0; j<this.form.elements.length; j++)
                if( this.form.elements[j].tagName == 'BUTTON' )
                    this.form.elements[j].disabled = true;
            this.disabled=false;
            this.value = this.attributes.getNamedItem("value").nodeValue ;
        }
    }
}

$(window).unload(function(){
	if(typeof(GUnload) == "function"){
		GUnload();
	}
});

function createDateSubBox(params){
	input = '<input type="text" ';
	for(attr in params){
		input += attr+'="'+params[attr]+'" ';
	}
	input += '/>';
	
	return input;
}

function numericInput(e){
	var key = e.which;
	if ((key == 8 || key == 46 || key == 16 || key == 35 || key == 36 ||key == 9) || 	// Backspace, Del, Shift, -, End, Home, Tab
		(key >= 48 && key <= 57)  || 	// 0-9 at top of keyboard
		(key >= 96 && key <= 105) || 	// 0-9 at numpad
		(key >= 37 && key <= 40)){   	// arrows
		return true;
	 }
	 return false;
}

function input_date_update(e) {
	master = "#"+$(e.target).attr("id").substr(0,$(e.target).attr("id").length -2);
	dateArray = $(master).val().split("-");
	var key = e.which;
	
	if(key == 9 || key == 16){
		return;
	}
	
	switch($(e.target).attr("id").substr($(e.target).attr("id").length -1, 1)){
		case "d":
			$(master).val(dateArray[0]+"-"+dateArray[1]+"-"+$(e.target).val());
			
			if($(e.target).val().length == 2){
				$(e.target).next().focus();
				$(e.target).next().select();
				e.stopPropagation();
			}
			break;
		case "m":
			$(master).val(dateArray[0]+"-"+$(e.target).val()+"-"+dateArray[2]);
			
			if($(e.target).val().length == 2){
				$(e.target).next().focus();
				$(e.target).next().select();
				e.stopPropagation();
			}
			break;
		default:
			$(master).val($(e.target).val()+"-"+dateArray[1]+"-"+dateArray[2]);
			break;
	}
}

function addDeleteFunction(){
	$(".delete-record").click(function(){
		$(this).parent().remove();
		return false;
	});
}

function setupTinyMCE(editor_id, body, doc) {
	body.innerHTML = body.innerHTML == "" ? '<p>&nbsp;</p>' : body.innerHTML;
}

if(typeof(tinyMCE) == 'object'){
	tinyMCE.init({
		mode : "specific_textareas",
		editor_selector : "rte",
		theme : "nedbase",
		// langpack for 3.2.1 not available yet
		// language : "nl",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		plugins : "paste",
		theme_advanced_buttons1 : "cut,copy,paste,pastetext,pasteword,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull",
		theme_advanced_buttons2 : "bullist,numlist,|,undo,redo,|,link,unlink",
		theme_advanced_buttons3 : "",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_path : false,
		theme_advanced_resizing : true,
		valid_elements : "p,a[href|target=_blank],strong/b,em/i,br,ul,ol,li",
		width : 534,
		theme_advanced_resizing_min_width: 534,
		theme_advanced_resizing_max_width: 534,
		theme_advanced_resize_horizontal : false,
		paste_auto_cleanup_on_paste : true,
		apply_source_formatting : true,
		forced_root_block : 'p',
		editor_css : "/include/css/editor_ui.css",
		content_css : "/include/css/editor.php"
	});
	
	function preSubmit(event){
		// Put tinyMCE editor contents in corresponding textarea before validating
		tinyMCE.triggerSave();
	}
	
	function preCheck(event){
		if(event.target.target == "_blank") {
			return true;
		}
		return false;
	}
}