var persCount = 2;
var accCount = 2;
var autoCount = 2;


$(document).ready(function() {
		$('#land_link').menu({
			content: $('#bes_landen').html(),
			callerOnState: '',
			flyOut: true,
			linkHover: 'highlight_topmenu',
			linkHoverSecondary: 'highlight_topmenu',
			showSpeed: 100
		});
		$('#backup_bestemmingen').menu({
			content: $('#bes_landen').html(),
			callerOnState: '',
			flyOut: true,
			linkHover: 'highlight_topmenu',
			linkHoverSecondary: 'highlight_topmenu',
			showSpeed: 100
		});
	$('#zone_link').menu({
			content: $('#bes_content').html(),
			callerOnState: '',
			flyOut: true,
			linkHover: 'highlight_topmenu',
			linkHoverSecondary: 'highlight_topmenu',
			showSpeed: 100
		});
			$('#bestemmingen_link').menu({
			content: $('#bes_zones').html(),
			callerOnState: '',
			flyOut: true,
			linkHover: 'highlight_topmenu',
			linkHoverSecondary: 'highlight_topmenu',
			showSpeed: 100
		});
});

$(function(){
	$(".rounded").corner("top");	
/*
	$(".lightbox").lightBox({
		txtImage: 'Foto',
		txtOf: 'van'
		
	});*/
	
	$('#extracontent a.extra-photos').colorbox(
		{current: "Foto {current} van {total}",
			title: "&nbsp;"}
	);
	

});


function initDatepicker(){
	$(".datepicker").datepicker(
	{ dateFormat: 'dd-mm-yy', minDate: '0' }
	);
}

function printPage(divName, throughSubmit){
	
	if(throughSubmit == "undefined")
		throughSubmit = false;
	
	window.open('/printPage.php?div=' + divName + '&throughSubmit=' + throughSubmit);
	
}


/* Function used to solve the anti-aliasing/cleartype problem with IE after jQuery show() */
function filterFunction(obj){
	if(jQuery.browser.msie)
		obj.style.removeAttribute("filter");
}

/* Function used to change imagemaps */
function changeImagemap(newImg){
	document.getElementById("image-map").src = newImg.src;
}

/* Function used to switch images */
function changePic(newUrl, newSub){
	if(newSub == undefined){
		newSub = " ";
	}
	
	var adres = newUrl;
	document.getElementById("mainpic").src = "" + adres;
	$("#sub").html('<em>' + newSub + '</em>');
	
}

/* Function used to Ajax requesting the points on the map */
function reqPoints(id){
	 var obj = document.getElementById("map").getBoundingClientRect();
	 offsetX = obj.left;
	 offsetY = obj.top;
	
	 offsetX = 0;
	 offsetY = 0;
	
	
	$.post("ajax/fetchPoints.php", {
		
		id: id,
		offsetX: offsetX,
		offsetY: offsetY}, function(data){
		var rawString = data;
  	$("#map").append(rawString);
  	
		
	});
	 	

}


var oPlattegronden = Array();

function getSizes(){
	setTimeout("fetchSizes()", 500);
	
}

function fetchSizes(){
		org = $(".plattegrond");
			for(var i = 0; i < org.length; i++){
				oPlattegronden[i] = org[i].width;
				$(org[i]).attr("width", "100");
				//alert(oPlattegronden[i]);
				
				
			}
}

function resizeP(nr, o){	
		if(o.width != 100){
			
			o.width = 100;
		}
		else{		
			o.width = oPlattegronden[nr];
			
		}
}
/* Function to check if the option is NVT, we add 0 to certain input fields. Reserveringsformulier only */
function noAccCheck(value){
	
	if(value == 'N.V.T.'){
		$('.aankomst').val('0');
		$('.vertrek').val('0');
		$('.aantalnacht').val('0');
		
	}
}

function noAutoCheck(value){
	
	if(value == 'nvt'){
		
		
		$('.r_i_ah_datum').val('0');
		$('.r_i_ah_aantaldagen').val('0');
		$('.r_s_ah_waarafhalen').val('NVT');
		$('.ah_kinderzitje').val('nee');
		$('.r_i_ah_retour').val('0');
		
		$('.ah_stoelverhoging').val('nee');
		$('.ah_kinderzitje').attr('checked', 'checked');
		$('.ah_stoelverhoging').attr('checked', 'checked');
		
	}
}

/* Function to add a person to the form. Reserveringsformulier only */
function addPers(){
	var ingevuld = $(".i_aantal_deelnemers").attr("value");
	if(ingevuld < persCount){
		if(ingevuld == "")
			ingevuld = 0;
		
		alert('Totaal aantal deelnemers ('+ingevuld+') wordt overschreden');
		return;
	}
	
	
	$.get("ajax/fetchPers.php?amount=" + persCount, function(data){
		var rawString = data;
		$("#pers_div").append(data);
		persCount++;
	})	
}

/* Reserveringformulier function, fills in the input field from the select. */
function fillTransferTo(){
		var acc = $(".j_a_sacc").attr("value");
		$(".r_i_taxinaar").attr("value", acc);
		
}
var accCount = 2;


function addAcc(landId, bHide){
	
	$.post("ajax/fetchAccommodaties.php", {
			landId: landId,
			amount: accCount,
			b: bHide
			}
		, function(data){
		
		var rawString = data;
		accCount++;
		
		
		$("#acc_div").append(data);
		//document.getElementById("acc_div").innerHTML += data;
		initDatepicker();

	})

		
}

var autoCount = 1;

function addAuto(landId){
	$.get("ajax/fetchAuto.php?amount=" + autoCount + "&landId=" + landId, function(data){
		var rawString = data;
		$("#auto_div").append(data);
		initDatepicker();
	
	})
	
	autoCount++;
	
	
	
}

function setPersAmount(persCount){
	this.persCount = persCount;
	
}

function openAutogroep(id) {
	$("#auto_" + id).show("slow");
}

function closeAutogroep(id){
	$("#auto_" + id).hide("slow");
	
}



/* Used to check forms. Simple function, checks if class is obligatory and then checks the content. Not rocket science */
function checkForm(isReservering, isBlocked){
	/* Set the boolean to true */
	var correct = true;
	/* Get all objects with the class */
	var ob = $(".obligatory");
	/* Let's check all the objects in the array. */
	for(var i = 0; i < ob.length; i++){
		/* Oh, in case someone went wrong the first time, set the default state back to white */
		ob[i].style.backgroundColor = '#ffffff';
		/* Ohnoes, it's empty... */
		if(ob[i].value == ""){
			/* If it's hidden, don't check it */
			if($(ob[i]).is(':hidden')){
				continue;
			}
			
			/* Fix the background color */
			ob[i].style.backgroundColor = '#FF00FF';
			/* Set the focus to that input */
			ob[i].focus();
			/* And there goes the neighbourhood */
			correct = false;
		}	
	}
	
	
	var rob = $(".r_obligatory");
	
	for(var j = 0; j < rob.length; j++){
		var name = $(rob[j]).attr("name");	
		var test = $("[name=" + name + "]");	
		var status = $(test).is(":checked");
		
		name = name.replace("[", "");
		name = name.replace("]", "");
		
		
		$("#" + name).css("background-color", "#ffffff");
	
		if($(test).is(':hidden')){
			
			continue;
		}
		
		
		if(status == false){
			$("#" + name).css("background-color", "#ff00ff");
			correct = false;
			
		}
		
	}
	
	var identicals = $(".identical");
	
	if(identicals.length != 0){
		var valueToCheck = identicals[0].value;
		if(identicals[1].value != valueToCheck){
			correct = false;
			$(identicals[0]).css("background-color", "#ff00ff");
			$(identicals[1]).css("background-color", "#ff00ff");
			
		}
		
	}
	
	var mails = $(".obligatory_mail");
	
	for(var k = 0; k < mails.length; k++){
		var currentMail = mails[k];
		currentMail.style.backgroundColor = '#ffffff';
		/*if(currentMail.value.indexOf(".") > 2)
			if(currentMail.value.indexOf("@") > 0)
				continue;
		*/
		
		if (currentMail.value.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1){
			continue;
		}	
		
	
		currentMail.style.backgroundColor = '#ff00ff';
		currentMail.focus();
		
		correct = false;
		
		
		
	}
	

	if(isReservering){
		var deelnemers = $(".i_aantal_deelnemers").attr("value");
		var in_deelnemers = $(".j_p_iachternaam");
		var aant_deelnemers = in_deelnemers.length;
		if(deelnemers > aant_deelnemers){
			alert("Onvoldoende aantal deelnemers ingevuld");
			correct = false;
			
		}
		
		
		
	}

	
	
	if(isBlocked)
		correct = false;
	
	/* It's not correct? Prompt to the user that it's wrong */
	if(!correct)
		alert("Velden niet goed ingevuld");
	
	//correct = true;
	
		
	if(correct){
		if(!isReservering){
			$("form").submit();
			return;
		}
		else{
			
			var confirm = $("#confirm_hidden").attr("value");
			
			//if(confirm == 'true'){
				$("input[type='text']").removeAttr("disabled"); 
				$("input[type='radio']").removeAttr("disabled");
				$("input[type='checkbox']").removeAttr("disabled");
				$("select").removeAttr("disabled");
				
				
			//}
			//else{
				var printOn = false;
			
				if(window.confirm("Wilt u deze opdracht printen?")){
					printOn = true;
					printPage('forms', true);
					
				}
				
				if(printOn){
				}
					
				else
					$("form").submit();
						
				
				
				
				/*alert("Wilt u deze opdracht bevestigen aub.");
				$("input[type='text']").attr("disabled", "true");
				$("input[type='radio']").attr("disabled", "true");
				$("input[type='checkbox']").attr("disabled", "true");
				$("select").attr("disabled", "true");
				
				
				
				$("#confirm_hidden").attr("value", "true");
				$("#verzend_button").attr("value", "Bevestigen");
				$("#verzend_button").css("background-color", "#FF00FF");*/
				
				
				
			//}
				
		}
			
		
	}
	
		
}

/*$(".lightbox").lightBox();*/
function forceSubmit(){
	$("form").submit();
}


function isIdentical(a, b){
	var aVal = $(a).attr('value');
	var bVal = $(b).attr('value');
	
	if(aVal == bVal)
		return true;
	else
		return false;
}

/*	Possibly the most annoying thing about making 'valid' XHTML: target="_blank" isn't allowed anymore.
		So now we're forced to make a function for it which actually implements targets in your a-tags. Hmmm.

*/
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
}


function toggleStatus() {
		
    if ($('.toggleElement').is(':checked')) {
				
        $('.toggableElement').removeAttr('disabled');

    } else {
    	        $('.toggableElement :input').attr('disabled', true);

    }   
}

function addVervolgLink(type, id){
	alert("reroute?");
	
	addVervolgLink(type, 0, 0, 0, id);
	
}

/* Uglies function in the book */
function addVervolgLink(type, id, landId, zoneId, regioId){
	
	var paragraphs = $("#index p");
	var lastParagraph = paragraphs[paragraphs.length - 1];
	if(type == 'accommodatie')
		var URL = '<a href="/vervolgInfo.php?id=' + landId + '&zid=' + zoneId + '&rid=' + regioId + '&aid=' + id + '">Klik hier voor vervolg</a>';
	else
		var URL = '<a href="/	achtergrondInfo.php?type=' + type + '&id=' + id + '&landId=' + landId + '&zid=' + zoneId + '&rid=' + regioId + '">Klik hier voor vervolg</a>';
		
	
	$(lastParagraph).append(' ' + URL);
	
	
	
}

function handleFoldSelect(value, aValues, aDivs){
	for(i = 0; i < aDivs.length; i++){
		var curVal = aValues[i];
		var curDiv = aDivs[i];
		if(value == curVal){				
			 $('.' + curDiv).show('slow', function() {filterFunction(this)});	
		}
		else{
			$('.' + curDiv).hide();
		}
	}	
}


/* function for checking if any brochure is checked */
function brochureHandle(){
	var isCorrect = false;
	if($("#brochure-check-Griekenland").is(":checked"))	
		isCorrect = true;
	if($("#brochure-check-Canarische").is(":checked"))
		isCorrect = true;
	
	if(!isCorrect){
		alert("Geen brochure geselecteerd");
		return true;
	}
	
	
}

/* Function used to calculate the end-date */
function calcRetour(obj, jsId){
	var startDate = new Date(Date.parse($("#auto_datum_" + jsId).datepicker('getDate')));
	var oneDay = 1000*60*60*24;
	var amount = $(obj).attr("value");
	amount = amount / 1;
	
	var endDate = new Date();
	endDate = startDate;

	
	endDate.setDate(startDate.getDate() + amount);

	var parsedDate = endDate.getDate() + "-" + (endDate.getMonth()+1)  + "-" + endDate.getFullYear();
	
	$("#auto_retour_calc_" + jsId).attr("value", parsedDate);
	
	
		
}



window.onload = externalLinks; 
