﻿var monthOptions;

$(document).ready(function() {
	

	//$("table.draggable").live("mouseover", function() {
	//	$(this).draggable();
	//});

	if(!$.cookies.test()) {
		alert("Zur Nutzung des Lebenslaufgenerators müssen im Browser Cookies aktiviert sein!");
	}

	$("#datepicker_birthday").datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '1950:2000',
		defaultDate: new Date(1990, 0, 1, 0, 0, 0),
		dateFormat: 'dd.mm.yy',
		monthNamesShort: ['J&auml;n','Feb','M&auml;r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNamesMin: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']
	});
	
	$("#datepicker_workpermit").datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '2010:2100',
		dateFormat: 'dd.mm.yy',
		monthNamesShort: ['J&auml;n','Feb','M&auml;r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNamesMin: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']
	});

	$("#datepicker_send").datepicker({
		dateFormat: 'dd.mm.yy',
		monthNamesShort: ['J&auml;n','Feb','M&auml;r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		dayNamesMin: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So']	
	});
	
	//add new Validators
	jQuery.validator.addMethod("phone", function(value, element) {
        return this.optional(element) || /^[0-9\+\/\-\–\ \(\)( x| ext)]+$/.test(value);
	});
	
	jQuery.validator.addMethod("checkdatefield", function(value, element) {
		if($(element).closest("tbody").find("select[value = '']").size() == 0) {
			if(value == '') return false;
			else return true;
		}
		return true;
	});
	
	jQuery.validator.addMethod("realisticDateDE", function(value, elem){
		var match = value.match(/\./g);
		if (match == null) return false;
		if (match.length != 2) return false;
		var split = value.split(/\./);
		if(split[0].length <= 1 || split[0].length >= 3) return false;
		var day = parseInt(split[0],10);
		if(day <= 0 || day >= 32)return false;
		if(split[1].length <= 1 || split[1].length >= 3) return false;
		var month = parseInt(split[1],10);
		if(month <= 0 || month >= 13)return false;
		if(split[2].length <= 3 || split[1].length >= 5) return false;
		var year = parseInt(split[2],10);
		var date = new Date();
		var currentYear = date.getFullYear();
		if(year < ( currentYear - 100 ) || year > ( currentYear + 100 ))return false;
		return true;
		});

	
	//Override default error message
	jQuery.validator.messages = {
		required: "Dieses Feld ist verpflichtend!",
		email: "Bitte geben Sie eine g&uuml;ltige E-Mail Adresse an!",
		phone: "Bitte geben Sie eine g&uuml;ltige Telefonnumer an!",
		checkdatefield: "&nbsp; &nbsp; &nbsp; Diese Feld darf nicht leer sein!"
	};

	
	$("#cvform").formToWizard({ submitButton: 'generateCV' });
	
	monthOptions = { 
			"02":"Februar", 
			"03":"M&auml;rz", 
			"04":"April", 
			"05":"Mai", 
			"06":"Juni", 
			"07":"Juli", 
			"08":"August", 
			"09":"September", 
			"10":"Oktober", 
			"11":"November", 
			"12":"Dezember"
			};
		$.each(monthOptions, function(val, text) {
		    $("select.month").append(
		        $('<option></option>').val(val).html(text)
		    );
		});
		
	var date = new Date();
	var year2 = date.getFullYear();
	for(var i = 1970; i<=year2; i++) {
	    $("select.year2").append(
		        $('<option></option>').val(i).html(i)
		);		
	};
	
	$("input[name='nolicense']").click(function() {
		$("#skills input:checkbox").attr('checked', false);
	});
	
	//followed two function are that complicated because just with one toggle or click event 
	//there will be no hook shown on the clicked checkbox, though its checked! However....
	$("input.workexp_tillnow").live("click",
		function() {
			$(this).siblings("select").hide();
			$(this).before('<select class="month" name="fakemonth" style="margin-right:4px;">'+
                '<option value="" selected="selected">Monat</option>'+
                '<option value="">September</option>'+
            '</select>'+
            '<select class="year2" name="fakeyear" style="margin-right:4px;">'+
                '<option value="" selected="selected">Jahr</option>'+
                '<option value="2100">2100</option>'+
            '</select>')
			$(this).siblings("select[name=fakemonth], select[name=fakeyear]").attr('disabled', 'disabled');
			$(this).hide();
			$(this).after('<input type="checkbox" name="workexp_tillnow_checked" checked="true"/>');
		}
	);
	
	$("input[name=workexp_tillnow_checked]").live("click", function() {
		$(this).siblings("select[name=fakeyear], select[name=fakemonth]").remove();
		$(this).siblings("select").show();
		$(this).siblings("input.workexp_tillnow").show();
		$(this).siblings("input.workexp_tillnow").attr('checked', false);
		$(this).remove();
	});
	
	$("span.addWorkExp").click(function(){
		var boxdesc = "workexp";
		var labelname = "Name der Firma";
		var labeldesc = "Beschreibung der T&auml;tigkeit";
	    $("#workexperience p").before(workexperienceBox(boxdesc, labelname, labeldesc));
		});
	
	$("span.addEducation").click(function(){
		var boxdesc = "education";
		var labelname = "Name der Schule/Ausbildungsst&auml;tte";
		var labeldesc = "Beschreibung, Abschl&uuml;sse";
	    $("#education p").before(workexperienceBox(boxdesc, labelname, labeldesc));
		});
	
	$("span.addTraining").click(function(){
		var boxdesc = "training";
		var labelname = "Name der Weiterbildung";
		var labeldesc = "Beschreibung der Weiterbildung";
	    $("#training p").before(workexperienceBox(boxdesc, labelname, labeldesc));
		});
	
	//with the event live its possible to manipulate elements which are dynamically added
	//even after the initializing of the DOM-Tree
	$("span.deleteBox").live("click", function(event){
	    $(this).parents("table").remove();
		});
	
	//show and hide the comment divs
	$("div.help").click(function(){
		var options = {};
		var suffix = $(this).siblings("div.field").children().attr("name");
		if($.support.opacity) {
			$("#comment_"+suffix).children("div.comment").toggle("blind",options,500);
		}
		else {
			$("#comment_"+suffix).children("div.comment").toggle();	
		}
		});	
	
	//upload image
	var btnUpload=$('#upload');  
	var status=$('#status'); 
	new AjaxUpload(btnUpload, {  
		        action: 'fileadmin/scripts/cv-generator/upload-file.php',  
		        //Name of the file input box  
		        name: 'uploadfile',
		        onSubmit: function(file, ext){  
		            if (! (ext && /^(jpg|jpeg|gif)$/.test(ext))){  
		                  // check for valid file extension  
		            	$("#image").siblings("div.error").remove();
		                status.text('Es sind nur JPG oder GIF Dateien erlaubt!');  
		                return false;  
		            }
		            status.text('Uploading...').css("color", "#5A4C6F");
		        },  
		        onComplete: function(file, response){  
		            //On completion clear the status  
		            status.text('').css("color", "red");; 
		            $('div.error').remove();
		            $('#image').html('');
		            //Add uploaded file to list
		            var res = response.split(".");
		            if(res[0]==="success"){  
		                $('#image').html('<img src="http://lehrerweb.at/fileadmin/scripts/cv-generator/uploads/'+res[1]+'/'+file+'" alt="" width="113" height="151"/><div id="deleteImg"><img src="http://lehrerweb.at/fileadmin/scripts/cv-generator/pics/cancel.png" alt="Bild l&ouml;schen" title = "Bild l&ouml;schen" width="18" height="18"/></div><div id="imagetitle">'+file+'</div>').addClass('success'); 
		            } else if(response==="error2"){  
		                $('#image').after('<div class="error">Die Größe des Bildes darf 450 x 450 Pixel/450 kB nicht überschreiten!</div>'); 
		            }
				else {
					$('#image').after('<div class="error">Fehler beim Upload der Datei!</div>');
				}  
		        }  
		    }); 
	//set data for image upload
	$("#deleteImg").live("click", function(){
		$('#image').html('');
	});
});

function workexperienceBox(boxdesc, labelname, labeldesc) {
	var date = new Date();
	var year = date.getFullYear();
	var yearopt;
	var monthop;
	var tillnow = "";
    for(var i = 1970; i<=year; i++) {
    	yearopt += '<option value="'+i+'">'+i+'</option>';
    }
    
	$.each(monthOptions, function(val, text) {
		monthop += '<option value="'+val+'">'+text+'</option>';
	});
	//only activate if there are more than one till now work required
	//if(boxdesc == "workexp") {
	//	tillnow = '<input type="checkbox" class="workexp_tillnow" name="workexp_tillnow[]"></input>'+
    //    '<label for="workexp_tillnow">laufend</label>';
	//}
	var newBox = 	    		
	'<table class="draggable" cellspacing="1" cellpadding="5" border="0" width=550px>'+
    '<tbody>'+
    '<tr>'+
        '<td><label for="from">Von:</label></td>'+
        '<td>'+
            '<select class="month" name="'+boxdesc+'_frommonth[]">'+
                '<option value="" selected="selected">Monat</option>'+
                '<option value="01" >J&auml;nner</option>'+
                monthop +
            '</select>'+
            '<select class="year2" name="'+boxdesc+'_fromyear[]">'+
                '<option value="" selected="selected">Jahr</option>'+
                yearopt +
            '</select>'+
            '<span class="deleteBox">l&ouml;schen</span>'+
        '</td>'+
    '</tr>'+
    '<tr>'+
        '<td><label for="to">Bis:</label></td>'+
        '<td>'+
            '<select class="month" name="'+boxdesc+'_tomonth[]">'+
                '<option value="" selected="selected">Monat</option>'+
                '<option value="01" >J&auml;nner</option>'+
                monthop +
            '</select>'+
            '<select class="year2" name="'+boxdesc+'_toyear[]">'+
                '<option value="" selected="selected">Jahr</option>'+
                yearopt +
            '</select>'+
            tillnow+
        '</td>'+
    '</tr>'+
    '<tr>'+
        '<td><label for="'+boxdesc+'_name">'+labelname+':</label></td>'+
        '<td><input class="checkdatefield" type="text" size="51" name="'+boxdesc+'_name[]"/></td>'+
    '</tr>'+
    '<tr>'+
        '<td><label for="'+boxdesc+'_description">'+labeldesc+':</label></td>'+
        '<td><textarea title="" rows="2" cols="40" name="'+boxdesc+'_description[]"></textarea></td>'+
    '</tr>'+
    '</tbody>'+
    '</table>';
	
	return newBox;
}
