$(function(){
	$('.view.datepicker .picker').each(function(){
		var uniqid = $(this).closest('.datepicker').attr('data-uniqid');
		var options = eval('vs_datepicker_options_'+uniqid);
		options.beforeShow = function(input, inst){
			$('#datepicker_container').removeClass('arrival').removeClass('departure').addClass($(input).closest('.datepicker').hasClass('arrival') ? 'arrival' : 'departure');
			if($.support.opacity){
    			$('#datepicker_container').stop().css('display', 'block').animate({
    				'opacity' : 1,
    				'queue' : false
    			}, options.duration);
    		} else {
    		    $('#datepicker_container').css('display', 'block');
    		}
			
		};
		options.onClose = function(dateText, inst){
		    if($.support.opacity){
		        $('#datepicker_container').stop().animate({
    				'opacity' : 0,
    				'queue' : false
    			}, options.duration, function(){
    				$(this).css('display', 'none');
    			});
		    } else {
		        $('#datepicker_container').css('display', 'none');
		    }
			
		}
		if($(this).closest('.datepicker').hasClass('arrival')){
			options.onSelect = function(dateText, inst){
				inst.input.trigger('change');
				_set_min_date_to_departure(dateText, $(this));
			};
			var theval = $(this).find('input[type=text]').val();
			if(theval !== ""){
				_set_min_date_to_departure(theval, $(this));
			}
		}
		
		$(this).find('input[type=text]').datepicker(options);
	});
	
	setTimeout(function(){
		var $datepicker_container = $('<div id="datepicker_container"><div class="header"></div><div class="content"><div class="block_0"></div></div><div class="footer"></div></div>');
		$('#content .datepicker').parent().append($datepicker_container);
		$datepicker_container.children('.content').append($('#ui-datepicker-div'));
		if($.support.opacity){
		    $datepicker_container.css('display', 'none').css('opacity', 0);
		} else {
		    $datepicker_container.css('display', 'none');
		}
		
	},1);
});

function _set_min_date_to_departure(dateText, $picker)
{
	var nday = dateText.substr(0, 2);
	var nmonth = parseInt(dateText.substr(3, 2), 10) -1;
	var nyear = dateText.substr(6, 4);
	var ndate = new Date(nyear, nmonth , nday);
	ndate.setDate(ndate.getDate()+1);
	
	var $inp = $picker.closest('.datepicker').parent().find('.datepicker.departure .picker input[type=text]');
	setTimeout(function(){
		var oldDate = $inp.val();
		$inp.datepicker("option", "minDate", ndate);
		var newDate = $inp.val();
		
		var hasChanged = false;
		if(oldDate != newDate) hasChanged = true;
		if($inp.val() == ""){
			var wdate = new Date(ndate.getTime() + 518400000);
			var wday = parseInt(wdate.getDate());
			if(wday < 10){
				wday = "0"+wday;
			}
			var wmonth = parseInt(wdate.getMonth(), 10)+1;
			if(wmonth < 10){
				wmonth = "0"+wmonth;
			}
			$inp.val(wday+"/"+wmonth+"/"+wdate.getFullYear());
			hasChanged = true;
		}
		if(hasChanged) $inp.trigger('change');
	}, 400);
}
