/**
 * Function to update the venue-select list
 */

function updateVenueSelect(city){		
		$("#foundEvents").remove();
		$("#venue").removeAttr("disabled");		
		$.getJSON("/validation/VenuesInCity/",{cityId: city}, function(data){
			$("select[name='venue']").empty();
				if(data){															
					$.each(data, function(i,item){
						$("select[name='venue']")
						.append("<option value=" + item.id + ">" + item.venue_name + "</option>");
					});	
				}
		});			
	
}

/**
 * Function to get events in the given venue/city/date
 */ 

function getSelectedEvents(){
	var cityToCheck = $("select[name='city']").val();
	var venueToCheck = $("select[name='venue']").val();
	var day = $("select[name='starttime_day']").val();
	var month = $("select[name='starttime_month']").val();
	var year = $("select[name='starttime_year']").val();							
						
	$("#foundEvents").remove();
			
	// random number to avoid caching
	var randomnumber=Math.floor(Math.random()*110);
								
	$.post("/validation/eventsCityVenue/" + 
	randomnumber,{cityId: cityToCheck, venueId: venueToCheck,day:day,month:month,year:year}, function(data){
			if(data){								
				//		
				$("select[name='venue']").parent()
				.after("<li id='foundEvents'><strong>Reeds bestaande evenement(en) in de gekozen stad/locatie op de gekozen datum:</strong><div id='eventError' class='formFeedback formFeedbackNegative'></div><br /><br /></li>");
				$("#foundEvents").append(data);
				// fold the found events			
				$("ul.items").accordion({alwaysOpen:false,event:"click",header:".overviewHeader",animated:false,selectedClass:"active"});					
				// add the checkbox
				$("#foundEvents").append("<input name='newEvent' type='checkbox' class='checkBoxInline' /><span class='smallText'> Dit is een nieuw evenement</span>");
				// add the function to the checkbox
				$("input[name='newEvent']").click(function(){					
					$("#eventError").remove();
				});
				// resize the overlay to fit the new content
				var overlayNewHeight = $("#stap1").height();					
				$("#overlaystap1").css({height:overlayNewHeight + "px"});
				$("#overlaystap1").css({display:"none"});				
			}
		})	
	}


/**
 * Function to check if the venue is in the given city
 */

function venueInCityCheck(city, venue){				
	$("#formFeedbackvenue").addClass("formFeedbackPositive").removeClass("formFeedbackNegative");
	$("#cityVenueError").remove();
		$.post("/validation/venueInCity/",{city: city, venue: venue}, function(data){			
				if(data == "found"){					
					$("#formFeedbackvenue").removeClass("formFeedbackPositive");
					return true;
				}
				if($("#endtimeError").length < 1){ // only add the error if it's not shown
					$("#formFeedbackvenue").addClass("formFeedbackNegative");
					$("#venue").parent()
					.after("<li id='cityVenueError'><span class='errorMessage'>Het gekozen podium bevindt zich niet in de gekozen stad.</span></li>");
					var overlayNewHeight = $("#stap1").height();					
					$("#overlaystap1").css({height:overlayNewHeight + "px"});
		}
		});			
	
}

/**
 * Validation for step 1
 */

function stap1validation(){
	
	// check for events on the given date/venue/city
	if(	
	// item has been confirmed as a new event
	$("input[name='newEvent']:checked").length != 1 && $("input[name='newEvent']").length == 1 
	// item has not been checked yet
	|| $("input[name='newEvent']").length == 0
	){ 
		// editing mode, do not check
		if($("input[name='refid']").length != 1){
			getSelectedEvents();	
		}
	}	

	$("#endtimeError").remove();

	// check if the chosen venue is in the chosen city
	var cityToCheck = $("#city").val();
	var venueToCheck = $("#venue").val();
	var venueCheck = venueInCityCheck(cityToCheck,venueToCheck);
		
	// get the values of the select-boxes for the starttime
	var startDay = $("select[name='starttime_day']").val();
	var startMonth = $("select[name='starttime_month']").val();
	var startYear = $("select[name='starttime_year']").val();
	var startHour = $("select[name='starttime_hour']").val();
	var startMinutes = $("select[name='starttime_minutes']").val();
	var startTime = new Date(startYear,startMonth-1,startDay,startHour,startMinutes);	
	// get the values of the select-boxes for the endtime
	var endDay = $("select[name='endtime_day']").val();
	var endMonth = $("select[name='endtime_month']").val();
	var endYear = $("select[name='endtime_year']").val();
	var endHour = $("select[name='endtime_hour']").val();
	var endMinutes = $("select[name='endtime_minutes']").val();
	var endTime = new Date(endYear,endMonth-1,endDay,endHour,endMinutes);
	
	// compare the times
	if(endTime < startTime){
		if($("#endtimeError").length < 1){ // only add the error if it's not shown
				$("#endtime_minutes").parent().after("<li id='endtimeError'><span class='errorMessage'>De eindtijd van het evenement is eerder dan de begintijd.</span><div id='starttimeError' class='formFeedback formFeedbackNegative'></div></li>");
				$("#formFeedbackendtime_minutes").addClass("formFeedbackNegative");
				$("#formFeedbackstarttime_minutes").addClass("formFeedbackNegative");
				// resize the overlay to fit the new content
				var overlayNewHeight = $("#stap1").height();					
				$("#overlaystap1").css({height:overlayNewHeight + "px"});
		} 
	}
}

/**
 * Validation for step 4
 */

function stap4validation(){
	$("#vvktimeError").remove();
	$("#formFeedbackvvktime_minutes").addClass("formFeedbackPositive").removeClass("formFeedbackNegative");
	// get the values of the select-boxes for the starttime
	var startDay = $("select[name='starttime_day']").val();
	var startMonth = $("select[name='starttime_month']").val();
	var startYear = $("select[name='starttime_year']").val();
	var startHour = $("select[name='starttime_hour']").val();
	var startMinutes = $("select[name='starttime_minutes']").val();
	var startTime = new Date(startYear,startMonth-1,startDay,startHour,startMinutes);	
	// get the values of the select-boxes for the endtime
	var endDay = $("select[name='endtime_day']").val();
	var endMonth = $("select[name='endtime_month']").val();
	var endYear = $("select[name='endtime_year']").val();
	var endHour = $("select[name='endtime_hour']").val();
	var endMinutes = $("select[name='endtime_minutes']").val();
	var endTime = new Date(endYear,endMonth-1,endDay,endHour,endMinutes);
	// get the values of the select-boxes for the vvktime
	var vvkDay = $("select[name='vvktime_day']").val();
	var vvkMonth = $("select[name='vvktime_month']").val();
	var vvkYear = $("select[name='vvktime_year']").val();
	var vvkHour = $("select[name='vvktime_hour']").val();
	var vvkMinutes = $("select[name='vvktime_minutes']").val();
	var vvkTime = new Date(vvkYear,vvkMonth-1,vvkDay,vvkHour,vvkMinutes);
	// compare the times
	if(endTime < vvkTime || startTime < vvkTime){
		if($("#vvktimeError").length < 1){ // only add the error if it's not shown
			$("#formFeedbackvvktime_minutes").addClass("formFeedbackNegative");			
			$("#vvktime_minutes").parent().after("<li id='vvktimeError'><span class='errorMessage'>De voorverkooptijd is later dan de begin- of eindtijd van het evenement.</span><div id='vvkError' class='formFeedback formFeedbackNegative'></div></li>");
			var overlayNewHeight = $("#stap4").height();
			$("#overlaystap4").css({height:overlayNewHeight + "px"});
		}
		return false;
	} else {
		return true;
	}
}

 /* Functions to initialize document ready
 */

$(document).ready(function(){
	
	if($("#venue").attr("disabled") == false){
		$("#venue").attr("disabled",true); 
	}
	
	var venueLatitude = $("#mapVenue #latitude").html();
	var venueLongitude = $("#mapVenue #longitude").html();	
		
	// Google Map activation 
	$("#locationTab").click(function(){
		setTimeout(function(){ 
			mapVenue.checkResize()
			var point = new GLatLng(venueLatitude*1.0018,venueLongitude*1.001);
			mapVenue.setCenter(point);
		},100);
	});			
	
	// make the artist-field an autocomplete box
	$("input[title='artists']").autocomplete("/validation/artist/",
	{minChars:2,inputClass:'formAutocomplete',resultsClass:'formAutocompleteResults'});

	// init the datepicker
	$(".datepickerField").datepicker().mouseover(function(){
			$(this).children(".datepicker_inline").css({display:"block"}).bind("mouseout click",function(){
				$(this).css({display:"none"});				
			});			
		});
		
	// function to add extra artistfields
	$(".extraFieldArtist").click(function(){
		var countFields = $(this).parent().parent().children("li").length-1;
		$(this).parent().before("<li><label for='artists" + countFields + "'>Extra artiest " + countFields + ":</label><input type='text' name='artists[]' id='artists" + countFields + "' title='artists' size='25' /></li>");
		// make the new inputfield also autocomplete
		$("input[title='artists']").autocomplete("/validation/artist/",
		{minChars:2,inputClass:'formAutocomplete',resultsClass:'formAutocompleteResults'});
		// recalculate the overlay height
		var overlayNewHeight = $("#stap3").height();
		$("#overlaystap3").css({height:overlayNewHeight + "px"});
		return false;
	});
		
	// update the venue-list after selecting a city
	$("select[name='city']").change(
	function(){
		var cityToCheck = $(this).val();		
		updateVenueSelect(cityToCheck, null);
	});
	
	// update the endtime after selecting a starttime
	$("select[name='starttime_day']").change(
	function(){	
		$("select[name='endtime_day'] option[value='" + $(this).val() + "']").attr("selected","selected");		
	});
	
	$("select[name='starttime_month']").change(
	function(){	
		$("select[name='endtime_month'] option[value='" + $(this).val() + "']").attr("selected","selected");		
	});
	
	$("select[name='starttime_year']").change(
	function(){	
		$("select[name='endtime_year'] option[value='" + $(this).val() + "']").attr("selected","selected");		
	});
	
	$("select[name='starttime_hour']").change(
	function(){	
		$("select[name='endtime_hour'] option[value='" + $(this).val() + "']").attr("selected","selected");		
	});
	
	$("select[name='starttime_minutes']").change(
	function(){	
		$("select[name='endtime_minutes'] option[value='" + $(this).val() + "']").attr("selected","selected");		
	});
	
	// check the presaletime on a change
	$("select[name='vvktime_day']").change(
	function(){	
		stap4validation();
	});
	
	$("select[name='vvktime_month']").change(
	function(){	
		stap4validation();
	});
	
	$("select[name='vvktime_year']").change(
	function(){	
		stap4validation();
	});
	
	$("select[name='vvktime_hour']").change(
	function(){	
		stap4validation();
	});
	
	$("select[name='vvktime_minutes']").change(
	function(){	
		stap4validation();	
	});

	// get the events already entered in the selected venue/city
	$("select[name='venue']").change(function(){						
		getSelectedEvents();
		});	
});