var test = ['anesteziolog','chirurg','dentální hygienista','dermatolog', 'dětský psycholog', 'diabetolog', 'diagnostika', 'domácí ošetřovatel', 'endokrinolog', 'gastroenterolog', 'genetik', 'gynekolog', 'hematolog', 'imunolog', 'internista', 'kardiolog', 'kožní' , 'logoped', 'neurolog', 'oční', 'onkolog', 'ortodontista', 'ortoped'];  // delete
var navDuration = 200;

function clear_form_elements(ele) {
	$(ele).find(':input').each(function() {
		switch(this.type) {
			case 'password':
			case 'select-multiple':
			case 'select-one':
			case 'text':
			case 'textarea':
				$(this).val('');
				break;
			case 'checkbox':
			case 'radio':
				this.checked = false;
		}
	});
}

function ContactFormSubmit() {
	// remove any previous errors and reset error count
	$("#reportFormMessage").empty();
	var errorCount = 0;
	
	// check firstname has been entered
	if ($("#contactFormFirstName").val().length === 0) {
		$("#contactFormFirstNameLabel").addClass("error"); 
		errorCount++;
	}
	else { $("#contactFormFirstNameLabel").removeClass("error"); }
	
	// check surname has been entered
	if ($("#contactFormSurname").val().length === 0) {
		$("#contactFormSurnameLabel").addClass("error"); 
		errorCount++;
	}
	else { $("#contactFormSurnameLabel").removeClass("error"); }
	
	// check email has been entered
	if ($("#contactFormEmail").val().length === 0) {
		$("#contactFormEmailLabel").addClass("error"); 
		errorCount++;
	}
	else { $("#contactFormEmailLabel").removeClass("error"); }
	
	// check message has been entered
	if ($("#contactFormMessage").val().length === 0) {
		$("#contactFormMessageLabel").addClass("error"); 
		errorCount++;
	}
	else { $("#contactFormMessageLabel").removeClass("error"); }
	
	// do we submit???
	if (errorCount === 0) {
		// submit form
		//$("#contactForm").submit();
		$.get("/contact/sendEmail.php", { contactFormFirstName: $("#contactFormFirstName").val(), contactFormSurname: $("#contactFormSurname").val(), contactFormEmail: $("#contactFormEmail").val(), contactFormPhone: $("contactFormPhone").val(), contactFormMessage: $("#contactFormMessage").val() } );
		
		// wipe all the data
		clear_form_elements("#contactForm");
		
		// display success
		$("#reportFormMessage").append("<li class='correct'>Contact form was sent successfully</li>");
	}
	else {
		// display error message
		$("#reportFormMessage").append("<li class='error'>An error occurred. Please complete the highlighted fields.</li>");
	}
	
	return false;
}

window.onload = function()
{
  /*
  $("#search_type").autocomplete(test,
	  {
		  minChars: 0
		}
	); //nahradit "test" url zdroje
*/
	//inicializace filtru
	if ($('#slider1').length)
	{
	  $('#slider1').slider({
		  range: 'min',
		  step:  "5",
		  slide: function(event, ui) {$('#slider1 .ui-slider-handle').text(ui.value+'km');}
		});
		$('#slider1 .ui-slider-handle').text('0km');
		
		$('#slider2').slider({
		  range: 'min',
		  slide: function(event, ui) {$('#slider2 .ui-slider-handle').text(ui.value+'%');}
		});
		$('#slider2 .ui-slider-handle').text('0%');
		
		$('#slider3').slider({
		  range: 'min',
		  slide: function(event, ui) {$('#slider3 .ui-slider-handle').text(ui.value+'%');}
		});
		$('#slider3 .ui-slider-handle').text('0%');
	}
	
	if ($('#slider4').length)
	{
		$('#slider4').slider({
			range: "min",
			value: 5,
			min: 5,
			max: 50,
		  slide: function(event, ui) {$('#slider4 .ui-slider-handle').text(ui.value);}
		});
		$('#slider4 .ui-slider-handle').text('5');
	}

	if ($('#slider-rate').length)
	{	
		$('#slider-rate').slider({
			range: "min",
			value: 50,
			min: 0,
			max: 100,
		  slide: function(event, ui) {$('#slider-rate .ui-slider-handle').text(ui.value+'%');}
		});
		$('#slider-rate .ui-slider-handle').text('50%');
	}

	//inicializace listu
	if ($('#resultsList').length)
	{
	  var rows = $('#resultsList .row');
	  for (i = 0, l = rows.length; i < l; i++)
		{
		  $(rows[i]).hover(
		    function() {$(this).addClass('hover');},
		    function() {$(this).removeClass('hover');}
			);
		}
	}
	
	if ($('.paging').length)
	{
	  var el = $('.paging');
	  el.css('width', 'auto');
	  var child = el.children();
	  child = $(child[child.length - 2]);
	  el.css('width', (child.position().left+child.outerWidth()+20)+'px');
	}
};

function updateMatched()
{
  $('#search_matched').load('results.php', {type: $('#search_type').val(), place: $('#search_place').val()}); //nahradit adresou skriptu
}

function filterCatClick(el)
{
  el = $(el);
  el.next().toggleClass('hidden');
	el.toggleClass('opened');
}


function dialogBody(title, msg, mode){
dialogHTML = '<div id="dialog" title="'+title+'"><div class="clear"></div><div class="form-box contact-form"><div class="col fl"><div id="nameLabel" style="text-align:left;" class="lab"><label>Name <span>*</span></label></div><div class="con"><input type="text" id="name" name="name" class="input" tabindex="1"></div><div id="phoneLabel" style="text-align:left;" class="lab"><label>Phone</label></div><div class="con"><input id="phone" type="text" name="phone" class="input" tabindex="3"></div></div><div class="col fr" style="margin-right:20px;"><div id="emailLabel" style="text-align:left;" class="lab"><label>E-mail <span>*</span></label></div><div class="con"><input id="email" type="text" name="email" class="input" tabindex="2"></div> <div id="placesLabel" style="text-align:left;" class="lab"><label>Required Places on Course ';

if (mode == 2) { dialogHTML += '<span>*</span>'; }

dialogHTML += '</label></div><div class="con"><input id="places" type="text" name="places" class="input" tabindex="5"></div></div><div class="clear"></div><div id="messageLabel" style="text-align:left;" class="lab"><label>Message</label></div><div class="con-textarea-medium"><textarea id="message" name="message" class="textarea-medium" cols="" rows="" tabindex="5">'+msg+'</textarea></div><div class="clear"></div></div></div>';
return dialogHTML;
}


$(document).ready(function() {  

    // SLIDER PAGE -------------------------------------------------------------------------------------------
	$(".slide-right").pageSlide({ width: "300px", direction: "right"});

	var selected = null;
	
	$(".enquire").click(function(){
		selected = $(this);
		var coursename = $('#coursename').html();
		var date = $(this).parent().parent().children(0).html();
		$('body').append(dialogBody("Make Enquiry", "I would like to enquire about the "+coursename+" course on "+date+".", 1));
		
		$('#dialog').dialog({
		 autoOpen: true,
		 width: 550,
		 modal: true,
		 resizable: false,
		 buttons: {
				"Make Enquiry": function() {
					
					// get data from form
					var cid = $('#cid').val();
					var name = $('#name').val();
					var email = $('#email').val();
					var phone = $('#phone').val();
					var reqPlaces = $('#places').val();
					var msg = $('#message').val();
					var ok = true;
					
					// check valid email entered
					if ((email.length === 0) || (email.indexOf('@') == -1)){
						alert("Please enter a valid email address.");
						ok = false;
					}
					
					// all OK, then submit and update db					
					if (ok) {					
						// update db
						$.post("/courses/details/updateDB.php", 
							  { 'm': 2, 'cn': $('#coursename').html(), 'cid': cid, 'name': name, 'email': email, 'phone': phone, 'reqPlaces': reqPlaces, 'msg': msg });
																
						// close dialog
						$( this ).dialog( "close" );
					}
										
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
		 beforeclose: function () { $(this).remove(); }
		});
		
		return false;
		
	});
	
	$(".book").click(function(){
		selected = $(this);
		var coursename = $('#coursename').html();
		var date = $(this).parent().parent().children(0).html();
		$('body').append(dialogBody("Make Booking", "I would like to book the "+coursename+" course on "+date+".", 2));
		
		$('#dialog').dialog({
		 autoOpen: true,
		 width: 550,
		 modal: true,
		 resizable: false,
		 buttons: {
				"Make Booking": function() {
					
					// get data from form
					var cid = $('#cid').val();
					var name = $('#name').val();
					var email = $('#email').val();
					var phone = $('#phone').val();
					var reqPlaces = $('#places').val();
					var msg = $('#message').val();
					var ok = true;
					var ctitle = selected.parent().parent().children(0).html();
					var maxPlaces = selected.parent().parent().next().children(0).next().html().replace("spaces left: ", "");
					
					// check valid email entered
					if ((email.length === 0) || (email.indexOf('@') == -1)){
						alert("Please enter a valid email address.");
						ok = false;
					}
					
					// check places is a number
					if ((ok) && (isNaN(parseInt(reqPlaces)) || ((!isNaN(parseInt(reqPlaces))) && (parseInt(reqPlaces) <= 0)))) { 
						alert("Please enter a valid number of places you require on the course.");
						ok = false;
					}
				
					// check places is not over our max left
					if ((ok) && (parseInt(reqPlaces) > parseInt(maxPlaces))){
						alert("There are not enough spaces available on the course. Please use the Enquiry link to send us an email if you are just a few places short as we may be able to accommodate this. Alternatively, please select another date.");
						ok = false;
					}
					
					// all OK, then submit and update db					
					if (ok) {
						// update percentage
						var oldPercentage = selected.parent().parent().next().children(0).children().html().replace('<span style="width: ', '');
						oldPercentage = parseInt(oldPercentage.replace('%;">&nbsp;</span>').replace("undefined", ""));
						maxPlaces = parseInt(maxPlaces);
						reqPlaces = parseInt(reqPlaces);
						var origPlaces = ((maxPlaces * 100) / oldPercentage);
						var percent = (((maxPlaces - reqPlaces) / origPlaces) * 100);
						selected.parent().parent().next().children(0).children().html('<span style="width: '+ percent+'%;">&nbsp;</span>');
						
						// update places left text
						selected.parent().parent().next().children(0).next().html("spaces left: " + (maxPlaces - reqPlaces));
						
						// update db
						$.post("/courses/details/updateDB.php", 
							  { 'm': 1, 'ctitle': ctitle, 'cn': $('#coursename').html(), 'cid': cid, 'name': name, 'email': email, 'phone': phone, 'reqPlaces': reqPlaces, 'msg': msg });
																
					// close dialog
					$( this ).dialog( "close" );
					}
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
		 beforeclose: function () { $(this).remove(); }
		});
		
		return false;
		
	});


    // #feat links ---------------------------------------------------------------------------------------------------
  	$("#feat-link").click(function(){    
  	  $(this).animate({ left : '300px', duration : 'normal' }); 
  	  $(this).addClass("active");
  	  $(this).addClass("pageslide-close");
  	  //$(this).hasClass("active").removeClass("active");
  	});       

  	// #feat links ---------------------------------------------------------------------------------------------------
  	$("#pageslide-body-wrap").click(function(){    
  	  $("#feat-link.active").animate({ left : '0', duration : 'normal' }); 
  	  //$(this).toggleClass("active");
  	  $("#feat-link.active").removeClass("active");
  	  $("#feat-link.active").removeClass("pageslide-close");
  	}); 

  	// FAQ ---------------------------------------------------------------------------------------------------
  	$("#faq li").click(function(){    
  	  $(this).find("div").slideToggle("slow");
  	  $(this).toggleClass("active");
  	  try {$(this).hasClass("active").removeClass("active"); }
	  catch (exception){}
  	});       

	// DROPDOWN MENU  ---------------------------------------------------------------------------------------------------
	$("#mainMenu ul li a").hover(function() { //When trigger is clicked...
	
	$(this).parent().find("li:first").addClass('first'); // add class first
		$(this).parent().find("li:last").addClass('last'); // add class last
		
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul").slideDown('normal').show(); //Drop down the subnav on click
	
		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul").slideUp('normal'); //When the mouse hovers out of the subnav, move it back up
		});
	
		//Following events are applied to the trigger (Hover events for the trigger)
		});
			
	// CLEAR INPUT VALUE  ---------------------------------------------------------------------------------------------------
	$('input, textarea').each(function () {
		if ($(this).val() === '') {
			$(this).val($(this).attr('Title'));
		}
	}).focus(function () {
		$(this).removeClass('inputerror');
		if ($(this).val() == $(this).attr('Title')) {
			$(this).val('');
		}
	}).blur(function () {
		if ($(this).val() === '') {
			$(this).val($(this).attr('Title'));
		}
	});
		
	$("a.fancybox").fancybox({
		'titleShow'		: false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic'
	});

	$(".fancybox-html").fancybox({
		'autoScale'			: false,	
		'height'        : 475,
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'type'				  : 'iframe'
	});

	$(".fancybox-html-small").fancybox({
    'autoDimensions'	: false,
		'width'         	: 530,
		'height'        	: 170,	
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
						
});

// HEADER PAGE SLIDER ---------------------------------------------------------------------------------------------------
jQuery('#slider-box').cycle({
  fx: 'fade', // transition fx
  speed: 700, // transitions speed
	pause: 1000, // pause between slides
	pager:  '#slide-pager'
});	
