$(document).ready(function() {

	$('.two-col-left #parc-descr .parc-text *:not(p:first)').hide();
	setup_lightbox();
	setup_tooltip();
	
	/* Trigger Change Event on Click - IE Fix*/
	if ($.browser.msie) {	
		$(':checkbox').click(function(){
			$(this).trigger('change');
		});
		$(':radio').click(function(){
			$(this).trigger('blur');
			$(this).trigger('focus');
			$(this).trigger('change');
		});
	}

	

/* 
 * 
 * FAQ
 * 
 */	

	$('.toggle-me').hide();
	
	$('.faqtoggle > a').toggle(
		function(){
			$(this).next().show();
		},
		function(){
			$(this).next().hide();
		}
	);
		
	
/* 
 * 
 * BOOKING
 * 
 */

	//popup with bungalow info
	$('.bungalowinfo').each(function() {
		var $link = $(this);
		var $dialog = $('<div></div>')
			.load($link.attr('href') + ' #content')
			.dialog({
				autoOpen: false,
				title: $link.attr('title'),
				width: 500,
				height: 400,
				modal: true,
				bgiframe: true
			});

		$link.click(function() {
			$dialog.dialog('open');

			return false;
		});
	});

	$('.bookingPricetable :input').change(function(){

		var id = $(this).parent().parent();
		
		if($(this).attr('type') == 'checkbox'){
			if ($(this).is(':checked')){
				var amount = 1;
			} else {
				var amount = 0;
			}
		} else {
			var amount = Number($(this).val());
		}
		//alert('test');
		var price = castPrice($(id).find('.price').html());
			
		var totalNr = amount * price;

		var total = '&euro; '+ totalNr.toFixed(2).replace(".",",");
		$(id).find('.total').html(total);

		updatePrice();
	});
	
	// Update the total price
	function updatePrice(){
        var totalPrice = 0;
        $('.bookingPricetable .total').each(function(){
                totalPrice += castPrice($(this).html());

        });
        totalPrice = totalPrice.toFixed(2).replace(".",",");
        $('#total_price').html('&euro; ' + totalPrice);
    }
    
	// Cast the price to a number for calculation
    function castPrice(price){
    	return parseFloat(price.replace("&euro; ","").replace(/\u20ac /g,"").replace(",","."));
    }
    	
/* 
 * 
 * SEARCH
 * 
 */	
    
    function changeParcs(Land, RegionProvince, Keten)
    {
    	// get ketenId...
    	var Parc = $('#search-hotelId').val();
    	var Keten = $('#search-ketenId').val();

		$.get("/?go=bungalow&action=ajax&type=parcs",{parc:Parc, country:Land, regionProvince:RegionProvince, keten:Keten},function(options){
			$('#search-hotelId').each(function(){
				if (this.tagName == 'SELECT') this.options.length = 0;
			});
			//fill select;
			$('#search-hotelId').html(options);
		});
		
    }
    
    function changeKeten(Land, RegionProvince)
    {
    	var Keten = $('#search-ketenId').val();
    	
    	if (Keten === undefined)
    	{
    		changeParcs(Land, RegionProvince, 0);
    	}
    	else
    	{
    		$.get("/?go=bungalow&action=ajax&type=ketens",{country:Land, regionProvince:RegionProvince, keten:Keten},function(options){
    			$('#search-ketenId').each(function(){
    				if (this.tagName == 'SELECT') this.options.length = 0;
    			});
    			//fill select;
    			$('#search-ketenId').html(options);
    			changeParcs(Land, RegionProvince, Keten);
    		});    		
    	}
    }
    
    // change the select dates
	$('#search-land').change(function(){
		var Land = $(this).val();
		var Province = $('#search-province').val;

		//remove existing options for periodId
		// load select options
		
		$.get("/?go=bungalow&action=ajax&type=regions",{country:Land, regionProvince:Province},function(options){
			$('#search-province').each(function(){
				if (this.tagName == 'SELECT') this.options.length = 0;
			});
			//fill select;
			$('#search-province').html(options);
			changeKeten(Land, 0);
		});
	});

	$('#search-ketenId').change(function(){
    	var Land = $('#search-land').val();
    	var RegionProvince = $('#search-province').val();
    	var Keten = $(this).val();
    	
		//remove existing options for periodId
    	changeParcs(Land, RegionProvince, Keten);
	});
	
	$('#search-province').change(function(){
    	var Land = $('#search-land').val();
    	var RegionProvince = $(this).val();
    	
		//remove existing options for periodId
    	changeKeten(Land, RegionProvince);
	});

    // change the select dates
	$('#search-periodType').change(function(){
		var periodType = $(this).val();

		//set all periodType selectlist to this.val
//		$('#search-periodType').val(periodType);
		//remove existing options for periodId
		$('#search-periodId').each(function(){
			if (this.tagName == 'SELECT') this.options.length = 0;
		});
		// load select options
		
		$.get("/?go=bungalow&action=ajax&type=periods",{periodTypeId:periodType},function(options){
			//fill select;
			$('#search-periodId').html(options);
		});
		
	});	
	
/*	// if the periodselect is changed change it for all forms
	$('.parksearch .periodSelect').change(function(){
		var selected = $(this).val();
		$('.periodSelect').val(selected);
	});
*/

	$('.two-col-left #parc-descr .expand').removeClass('hidden').click(function(){
		$(this).addClass('hidden');
		$('.two-col-left #parc-descr .parc-text *').show();
		$('.two-col-left #parc-descr .collapse').removeClass('hidden');
	});
	$('.two-col-left #parc-descr .collapse').click(function(){
		$(this).addClass('hidden');
		$('.two-col-left #parc-descr .parc-text *:not(p:first)').hide();
		$('.two-col-left #parc-descr .expand').removeClass('hidden');
	});
	
	//$('.two-col-left #parc-descr .parc-text p:first').show();
	
	
	
/* 
 * 
 * PARKSEARCH
 * 
 */		

	// MouseOver for parksearch
	$('#parc-results .result').live('mouseover',function(){
			$(this).children('td').css({'background-color':'#FCF0E2', 'cursor': 'pointer'});
	});
	
	// MouseOut for parksearch
	$('#parc-results .result').live('mouseout',function(){
		$(this).children('td').css({'background-color':'', 'cursor': 'default'});
	});
	
	//$('.searchresults .result.active img').hide();
	
	// Click to toggle bungalow info on parksearch
	$('#parc-results .result').live('click', function(){
		// get the bungalow id
		var bung = $(this).find('.open_acco img').attr('bung');
		
		// if active than remove class active and hide bungalow info
		if($(this).hasClass('active') == true){
			$(this).removeClass('active');
			$('#parc-results tr.'+bung).hide();
			$(this).find('.close_acco').hide();
			$(this).find('.open_acco').show();
		} else {
		//else hide others and show current
			//$('.searchresults tr.active').removeClass('active').next('tr').hide();
			$(this).addClass('active');
			$('#parc-results tr.'+bung).show();
			$(this).find('.open_acco').hide();
			$(this).find('.close_acco').css('display','block');
		}
		
		return false;
	});
		
	// Search on park page
	$('.parksearch').submit(function() {
		$('#parc-results').hide();
		$('.spinner').show();

		var params = {
				periodTypeId: $('#search-periodType').val(),
				periodId: $('#search-periodId').val(),
				adults: $('#search-adults').val(),
				children: $('#search-children').val(),
				babies: $('#search-babies').val(),
				hotelId: $('.submit').attr('name'), 
				search: 1
		};
		
		$.get("/?go=bungalow&action=ajax&type=parksearch", params, function(results){
			$('.spinner').hide();
			$('#parc-results').html(results).slideDown('slow');
			setup_lightbox();
			setup_tooltip();
		});
		
		return false;
    });
	
	$('#advancedSearchLink').click(function(){
			$(this).toggleClass('active')
			$('#advancedSearch').toggleClass('active');
			return false;
	});
	
/* 
 * 
 * LIGHTBOX
 * 
 */
	
	function setup_lightbox() {
		$('a.lightbox').each(function(){
			$('a.lightbox[name="' + $(this).attr('name') + '"]').lightBox({fixedNavigation:true});
		});
	}
	
	function setup_tooltip(){
		$('.discount-junior').tooltip({
			tip: '#youngdiscount',
			offset: [10, 2]
			//effect: 'slide'
		}).dynamic({
		    bottom: { 
		        // slide downwards 
		        direction: 'down',
		        // bounce back when closed 
		        bounce: true
		    }
		});
		$('.discount-senior').tooltip({
			tip: '#olddiscount',
			offset: [10, 2]
			//effect: 'slide'
		}).dynamic({
			bottom: { 
			// slide downwards 
				direction: 'down',
				// bounce back when closed 
				bounce: true
			}
		});
	}

/* 
 * 
 * POPUPS
 * 
 */

	$('#discount_youngest').datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '1910:2010',
		regional: 'nl',
		dateFormat: 'dd-mm-yy',
		onClose: function(){calculate_discount()}
	});
	$('#discount_oldest').datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '1910:2010',
		regional: 'nl',
		dateFormat: 'dd-mm-yy',
		onClose: function(){calculate_discount()}
	});

	
	function calculate_discount(){

		var params = {
				//youngest_day: $('#discount_youngest_day').val(),
				//youngest_month: $('#discount_youngest_month').val(),
				//youngest_year: $('#discount_youngest_year').val(),
				//oldest_day: $('#discount_oldest_day').val(),
				//oldest_month: $('#discount_oldest_month').val(),
				//oldest_year: $('#discount_oldest_year').val(),
				discount_youngest: $('#discount_youngest').val(),
				discount_oldest: $('#discount_oldest').val(),
				
				bungalow_id: $('.acco_id').attr('id').replace('bungalow_id_',''),
				start: $('.start_time').attr('id').replace('start_',''),
				originalPrice: castPrice($('#originalPrice').html()),
				nrOfBungalows: $('#numberOfBungalows').html()
		};

	/*	var type = $(this).parent.attr('id');
		
		if((params.youngest_day!= null && params.youngest_month!= null && params.youngest_year!= null)){
			alert(test);
		}
		*/
		
		//console.debug($('#acco_price_table').attr('class').replace('original', ''));
		//remove existing discount text
		$('.discount').remove();
		//show spinner
		$('.spinner').fadeIn();
		
		//get new discount information
		$.get("/?go=bungalow&action=ajax&type=discount", params, function(result){
			//hide spinner
			$('.spinner').fadeOut();
			//Show result
			$('#acco_price_table').after(result);
			//change total price
			updatePrice();
//			$('.searchresults').html(results).slideDown('slow');
//			setup_lightbox();
		});
	};
	
	
	
	$('a.info').each(function() {
		var $link = $(this);
		var $dialog = $('<div></div>')
			.load($link.attr('href'))
			.dialog({
				autoOpen: false,
				title: $link.attr('title'),
				width: 500,
				height: 400,
				modal: true,
				bgiframe: true
			});

		$link.click(function() {
			$dialog.dialog('open');

			return false;
		});
	});	
	
	$('input[name=pc_cijfers]').autotab({ target: 'pc_letters', format: 'numeric'});
	$('input[name=pc_letters]').autotab({ target: 'plaats', format: 'text'});
	$('input[name=birthday]').autotab({ target: 'birthmonth', format: 'numeric'});
	$('input[name=birthmonth]').autotab({ target: 'birthyear', format: 'numeric'});

});