$(function() {
    $("#datepicker").datepicker({              
      buttonImage: 'images/calendar.png', 
      showOn: 'both',
      buttonImageOnly: true,
      buttonText: 'Select date',
      beforeShow: function() {
        window.setTimeout(hideWeekends, 10);
      }, 
    	onChangeMonthYear: function() { 
      	window.setTimeout(hideWeekends, 10);
      }      
    });          

    //form validation 
    $('form[name=cart_quantity]').submit(function() {
      date = $('#datepicker').val();                      
      if (!date) {
                alert('Please enter arrival date');
                $('#datepicker').focus();
                return false;
      }    
      comments = $('textarea[name=comments]').val();
      if (!comments) {
          alert('Please enter your gift message');
          $('textarea[name=comments]').focus();
                return false;
      }                      
    });    
});

function hideWeekends() {
  $('.ui-datepicker-week-end:first-child').each(function() {
    //disable Sundays
    text = $(this).text();    
    $(this)
    .removeAttr('onclick')
    .empty()
    .html(text)
    .css('text-align', 'right');

    //disable mondays
    monday = $(this).next();
    text = monday.text();
    monday
    .removeAttr('onclick')
    .empty()                  
    .html(text)
    .css('text-align', 'right');    
  });                    
  
  //disable invalid dates
  month = $('.ui-datepicker-month').text();
  months = new Array('January', 'February', 'March', 'April', 'May', 
  'June', 'July', 'August', 'September', 'October', 'November', 'December');
  for (x in months) {
  	if (months[x] == month) {
  		month_num = x;
  		break;
  	}	
  }  
  year = $('.ui-datepicker-year').text();  
  $('.ui-datepicker td[onclick]').each(function() {
  	day = $(this).text();
  	date_str = month_num + '/' + day + '/' + year;
  	if (!isValidDate(date_str) || date_str == '8/8/2009' || date_str =='6/4/2009' || date_str == '10/27/2009' || date_str == '10/27/2009' || date_str == '11/25/2009' || date_str == '11/26/2009' || date_str == '0/1/2010' || date_str == '0/2/2010' || date_str == '6/6/2010' || date_str == '8/7/2010') {
  		text = $(this).text();    
      $(this)
      .removeAttr('onclick')
      .empty()
      .html(text)
      .css('text-align', 'right');
  	}
  });
}

function isValidDate(date_str) {

	myArray = date_str.split('/');
	myDate = new Date();
	time_now = myDate.getTime() / 1000;	
	arrival_time = Date.UTC(myArray[2],myArray[0],myArray[1]) / 1000 + 8 * 3600; //correction for PDT	
	//if (arrival_time - time_now < 43200) { //arrival required in less than 12hrs  
	if (arrival_time - time_now < 48600) { //arrival required in less than 13hrs  
		return false;
	}
	else
		return true;	
}
