$(document).ready(function(){

  var $booking_container = $('#bookingCover');

  var weekday_names = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
  var month_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
                           //0, 1,  2,   3,   4,   5,   6,   7,   8,   9,   10,  11,  12,  13,  14,  15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31
  var day_suffix = new Array("","st","nd","rd","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","st","nd","rd","th","th","th","th","th","th","th","st");
  //if($('input#selected_days_input').length > 0)
  //  $('input#selected_days_input').val('');
    
  //InitializeBooking();
  //var result = $booking_container.html;
  var params = typeof(params) != 'undefined' ? params : '';
  //$booking_container.html(result);
  InitializeBookingCalendarEvents();
/*  
  function InitializeBooking(params){
    var params = typeof(params) != 'undefined' ? params : '';
    $booking_container.fadeOut("fast", function(){
      var result = '';
      $.ajax({
        type: "GET",
        url: "site/ajax/booking.php",
        data: params,
        async: false,
        dataType: "text",
        success: function(response){
          result = response;
        },
        error: function(xhr, desc, exception){ result = 'An error occurred while getting the calendar.'; }
      });
      $booking_container.html(result).fadeIn("fast", function(){
        InitializeBookingCalendarEvents();
      });
    });
  }
*/   
  function InitializeBookingCalendarEvents(){
    refresh_selected_days_info();
    suggest_other_days();

    $('.calendar td').not('.before_current_day, .empty_day, .current_day, .month, .week, .booked').add('.selected')
      .unbind('mouseover')
      .unbind('mouseout')
      .unbind('click');
    $('.calendar .previous_month, .calendar .next_month')
      .unbind('click')
      .css('display', 'none');

    if($booking_container.attr('class') != 'step_3'){
      $('.calendar td').not('.before_current_day, .empty_day, .current_day, .month, .week, .booked').add('.selected').mouseover(function(){
        $(this).addClass('hover');
      }).mouseout(function(){
        $(this).removeClass('hover');
      }).click(function(){
        if($(this).hasClass('booked') && !$(this).hasClass('selected')){
          return '';
        }
        
        $('.calendar td').removeClass('suggested');
        $(this).toggleClass('selected');
        if(check_selected_days_validity($(this)) === false){
          $(this).toggleClass('selected');
        }
        if(!$(this).hasClass('selected')){
          month_number = parseInt($('.calendar .month_number').html(), 10);
          year_number = parseInt($('.calendar .year_number').html(), 10);
          $('input#selected_days_input').val($('input#selected_days_input').val().replace(year_number+'-'+month_number+'-'+$(this).html(), ''));
        }
        save_selected_days();
        refresh_selected_days_info();
        suggest_other_days();
        
        if($('input#selected_days_input').val().split('|').length > 1){
          $('#booking_next').slideDown("fast");
        }else{
          $('#booking_next').slideUp("fast");
        }
      });
  
      $('.calendar .previous_month, .calendar .next_month')
        .css('display', 'block');
  
      $('.calendar .previous_month, .calendar .next_month').click(function(){
        calendar_move_months_click($(this));
        return false;
      });
    }
    if($('input#selected_days_input').length > 0){
      if($('input#selected_days_input').val().split('|').length > 1){
        $('#booking_next').slideDown("fast");
      }else{
        $('#booking_next').slideUp("fast");
      }
    }


    $('#booking_next, #booking_prev').unbind('click');
    $('#booking_next, #booking_prev').click(function(){
      if($(this).is('#booking_next'))
        if(check_selected_days_validity_before_next() == false)
          return false;

      var params = '';
  		$('form#booking_form').find("input:hidden, :text, :checked, :password, :selected, textarea")
  		.each(function() {
  		  if($(this).attr('name'))
  		    params += $(this).attr('name')+'='+$(this).val()+'&';
  		  else if($(this).parent().attr('name'))
  		    params += $(this).parent().attr('name')+'='+$(this).val()+'&';
  		});
  		// !!! UPDATE when next step is added
  		if($(this).attr('id') == 'booking_prev'){
  		  params = params.replace(/step=2/g, 'step=1');
  		  if(params.indexOf('step=3') >= 0){
  		    params = params.replace(/step=3/g, 'step=2');
  		    params = params.replace(/form_sent=yes/g, '');
  		  }
      }
      if($(this).attr('id') == 'booking_next'){
  		  params = params.replace(/step=3/g, 'step=4');
  		  params = params.replace(/step=1/g, 'step=2');
      }
      find_step = 'step=';
      step_pos = params.indexOf(find_step);
      step = params.substr(step_pos + find_step.length, 1);
      $booking_container.attr('class', 'step_'+step);
  		InitializeBooking(params);
      return false;
    });
    $('.booking_go_to').unbind('click');
    $('.booking_go_to').click(function(){
      step = $(this).attr('rel');
      if(step.indexOf('step_') >= 0){
        step = step.replace('step_', '');
        params = 'step='+step;
        $booking_container.attr('class', 'step_'+step);
  		  InitializeBooking(params);
  		}
      return false;
    });
    
    calculate_price();
  }
  
  $("#bookingRooms input").click(refresh_calendar);

  function calendar_move_months_click(elm){
    var result_container = $('#calendarCover');

    move_months = elm.attr('href');
    find_move_months = "?move_months=";
    pos = move_months.indexOf(find_move_months);
    move_months = move_months.substr(pos + find_move_months.length, move_months.length);
    var params = 'calendar_params[move_months]='+move_months;
    selected_days = $('input#selected_days_input').val();
    params += '&calendar_params[selected_days]='+selected_days;
    params += '&room_id='+$('#bookingRooms :checked').attr('value');

    ajax_load_calendar(result_container, params);
  }
  function refresh_calendar(){
    var result_container = $('#calendarCover');
    
    elm = $(".previous_month");
    move_months = elm.attr('href');
    find_move_months = "?move_months=";
    pos = move_months.indexOf(find_move_months);
    move_months = move_months.substr(pos + find_move_months.length, move_months.length);
    var params = 'calendar_params[move_months]='+(parseInt(move_months)+1);
    selected_days = $('input#selected_days_input').val();
    params += '&calendar_params[selected_days]='+selected_days;
    params += '&room_id='+$('#bookingRooms :checked').attr('value');

    ajax_load_calendar(result_container, params);
  }
  
  function ajax_load_calendar(result_container, params){
    var result = '';
    $.ajax({
      type: "GET",
      url: "/site/ajax/calendar.php",
      data: params,
      async: false,
      dataType: "text",
      success: function(response){
        result = response;
      },
      error: function(xhr, desc, exception){ result = 'An error occurred while getting the calendar2.'; }
    });
    //console.log(result);
    //alert(result);
    $('#calendarCover').html(result);
    //result_container.html(result);
    
    InitializeBookingCalendarEvents();
    
    return false;
  }

  function check_selected_days_validity(elm){
    if(elm.hasClass('empty_day') || elm.hasClass('current_day') || elm.hasClass('month') || elm.hasClass('week')){
      return false;
    }
    if(elm.hasClass('before_current_day')){
      alert("You can't book days in history.");
      return false;
    }
    previous_elm = elm.prev();
    if(previous_elm.length == 0){
      previous_elm = elm.parent().prev().find('td:last');
    }
    next_elm = elm.next();
    if(next_elm.length == 0){
      next_elm = elm.parent().next().find('td:first');
    }
    if($('.calendar td.selected').length > 1){
      if($('input#selected_days_input').val().length > 1){
        if(!previous_elm.hasClass('selected') && !next_elm.hasClass('selected')){
          alert("Selected days must be in row.");
          return false;
        }else if(previous_elm.hasClass('selected') && next_elm.hasClass('selected')){
          alert("Selected days must be in row.");
          return false;
        }
      }
    }else if(($('input#selected_days_input').val().length > 1)){
      month_number = parseInt($('.calendar .month_number').html(), 10);
      year_number = parseInt($('.calendar .year_number').html(), 10);
      if($('input#selected_days_input').val() != year_number+'-'+month_number+'-'+elm.html()){
        if(!previous_elm.hasClass('selected') && !next_elm.hasClass('selected')){
          alert("Selected days must be in row.");
          return false;
        }else if(previous_elm.hasClass('selected') && next_elm.hasClass('selected')){
          alert("Selected days must be in row.");
          return false;
        }
      }
    }

    return true;
  }
  
  function check_selected_days_validity_before_next(){
    type_of_break = $('select#type_of_break').val();
    if(typeof(type_of_break) == 'undefined')
      type_of_break = $('input[name="type_of_break"]').val();
    if(typeof(type_of_break) != 'undefined'){
      selected_days = $('input#selected_days_input').val().split('|');
      var date_obj = new Date();
      
      if(type_of_break == '2'){//two days, mid week
        if(selected_days.length != 2){
          if(selected_days.length < 2)
            alert('Please pick two days you want to book. You have selected only one day.');
          else  
            alert('Please pick only two days you want to book or change your type of break.');
          return false;
        }
        for(x in selected_days){
          if(parseInt(x) >= 0){
            date_arr = selected_days[x].split('-');
            date_obj.setFullYear(date_arr[0], date_arr[1]-1, date_arr[2]);
            if(bank_holidays_array.indexOf(date_arr[0]+'-'+date_arr[1]+'-'+date_arr[2]) >= 0){
              alert('You are not allowed to pick a bank holiday with your chosen type of break.');
              return false;
            }
            weekday = date_obj.getDay();
            if((weekday == 0) || (weekday == 5) || (weekday == 6)){
              alert('You are not allowed to pick '+weekday_names[weekday]+' with your chosen type of break.');
              return false;
            }
          }
        }
      }else if(type_of_break == '3'){//three days, mid week
        if(selected_days.length != 3){
          if(selected_days.length < 3)
            alert('Please pick three days you want to book or change your type of break.');
          else  
            alert('Please pick only three days you want to book or change your type of break.');
          return false;
        }
        for(x in selected_days){
          if(parseInt(x) >= 0){
            date_arr = selected_days[x].split('-');
            date_obj.setFullYear(date_arr[0], date_arr[1]-1, date_arr[2]);
            if(bank_holidays_array.indexOf(date_arr[0]+'-'+date_arr[1]+'-'+date_arr[2]) >= 0){
              alert('You are not allowed to pick a bank holiday with your chosen type of break.');
              return false;
            }
            weekday = date_obj.getDay();
            if((weekday == 0) || (weekday == 5) || (weekday == 6)){
              alert('You are not allowed to pick '+weekday_names[weekday]+' with your chosen type of break.');
              return false;
            }
          }
        }
      }else if(type_of_break == 'week'){//7 days
        if(selected_days.length != 7){
          if(selected_days.length < 7)
            alert('Please pick seven days you want to book or change your type of break.');
          else  
            alert('Please pick only seven days you want to book.');
          return false;
        }
      }else if(type_of_break == 'weekend'){//weekend
        if(selected_days.length != 3){
          if(selected_days.length < 3)
            alert('Please pick three weekend days you want to book or change your type of break.');
          else  
            alert('Please pick only three days you want to book or change your type of break.');
          return false;
        }
        for(x in selected_days){
          if(parseInt(x) >= 0){
            date_arr = selected_days[x].split('-');
            date_obj.setFullYear(date_arr[0], date_arr[1]-1, date_arr[2]);
            if(bank_holidays_array.indexOf(date_arr[0]+'-'+date_arr[1]+'-'+date_arr[2]) >= 0){
              alert('You are not allowed to pick a bank holiday with your chosen type of break.');
              return false;
            }
            weekday = date_obj.getDay();
            if((weekday != 0) && (weekday != 5) && (weekday != 6)){
              alert('You are not allowed to pick '+weekday_names[weekday]+' with your chosen type of break.');
              return false;
            }
          }
        }
      }else if(type_of_break == 'holiday_weekend'){//weekend + bank holiday
        if(selected_days.length != 4){
          if(selected_days.length < 4)
            alert('Please pick three weekend days and a bank holiday you want to book or change your type of break.');
          else  
            alert('Please pick only three weekend days and a bank holiday you want to book or change your type of break.');
          return false;
        }
        is_there_bank_holiday = false;
        for(x in selected_days){
          if(parseInt(x) >= 0){
            date_arr = selected_days[x].split('-');
            date_obj.setFullYear(date_arr[0], date_arr[1]-1, date_arr[2]);
            if(bank_holidays_array.indexOf(date_arr[0]+'-'+date_arr[1]+'-'+date_arr[2]) >= 0){
              is_there_bank_holiday = true;
            }
            weekday = date_obj.getDay();
            if((weekday != 0) && (weekday != 5) && (weekday != 6)){
              if(bank_holidays_array.indexOf(date_arr[0]+'-'+date_arr[1]+'-'+date_arr[2]) < 0){
                alert('You are not allowed to pick '+weekday_names[weekday]+' with your chosen type of break.');
                return false;
              }
            }
          }
        }
      }
    }
    
    return true;
  }

  function suggest_other_days(){
    var suggestClasses = new Array('work_day','weekend');
    var cantHaveClasses = new Array('current_day', 'before_current_day', 'booked');
    $('.calendar td.empty_day').removeAttr('title');

    $('.calendar td.selected').each(function(){
      selected_cell = $(this);
      previous_elm = selected_cell.prev();
      if(previous_elm.length == 0){
        previous_elm = selected_cell.parent().prev().find('td:last');
      }
      next_elm = selected_cell.next();
      if(next_elm.length == 0){
        next_elm = selected_cell.parent().next().find('td:first');
      }
      for(x in suggestClasses){
        if(isInt(x)){
          if(selected_cell.hasClass(suggestClasses[x])){
            while(previous_elm.hasClass(suggestClasses[x]) && !previous_elm.hasClass('.'+cantHaveClasses.join(', .'))){
              previous_elm.addClass('suggested');
              previous_elm = previous_elm.prev();
              if(previous_elm.length == 0){
                previous_elm = selected_cell.parent().prev().find('td:last');
              }
            }
            while(next_elm.hasClass(suggestClasses[x]) && !next_elm.hasClass('.'+cantHaveClasses.join(', .'))){
              next_elm.addClass('suggested');
              next_elm = next_elm.next();
              if(next_elm.length == 0){
                next_elm = selected_cell.parent().next().find('td:first');
              }
            }
          }
        }
      }
    });
    $('.calendar td.empty_day.suggested, .calendar td.empty_day.selected').attr('title','To book or unbook this day: use arrows to move month selection.');
  }

  function refresh_selected_days_info(){
    var $info_box = $('#selected_days_info');
    if($info_box.length == 0)
      return false;
    info_html = '';
    var first_day = '';
    var last_day = '';
    var first_day_month_name = '';
    var last_day_month_name = '';
    month_number = parseInt($('.calendar .month_number').html(), 10);
    month_name_long = $('.calendar .month_name_long').html();
    year_number = parseInt($('.calendar .year_number').html(), 10);
    var date_obj = new Date();

    if($('input#selected_days_input').length > 0)
      var selected_days = $('input#selected_days_input').val().split('|');
    else
      var selected_days = new Array();
    if(selected_days.length > 0){
      date_arr = selected_days[0].split('-');
      if(date_arr.length == 3){
        date_obj.setFullYear(date_arr[0], date_arr[1]-1, date_arr[2]);
        first_day = weekday_names[date_obj.getDay()]+" "+date_arr[2]+day_suffix[date_arr[2]];
        first_day_month_name = month_names[date_arr[1]-1]+" "+date_arr[0];
      }
    }
    if(selected_days.length > 1){
      date_arr = selected_days[selected_days.length-1].split('-');
      if(date_arr.length == 3){
        date_obj.setFullYear(date_arr[0], date_arr[1]-1, date_arr[2]);
        last_day = weekday_names[date_obj.getDay()]+" "+date_arr[2]+day_suffix[date_arr[2]];
        last_day_month_name = month_names[date_arr[1]-1]+" "+date_arr[0];
      }
    }    

    if((first_day.length > 0) && (last_day.length > 0)){
      info_html = "<p>You have selected the following days:<br />From "+first_day;
      if(first_day_month_name != last_day_month_name)
        info_html += " "+first_day_month_name;
      info_html += " to "+last_day+" "+last_day_month_name;
    } else if((first_day.length > 0) && (last_day.length == 0)){
      info_html = "<p>You have selected the following day:<br />"+first_day+" "+first_day_month_name;
    } else {
      info_html = "<p>Please select your preferred dates.</p>";
    }
    $info_box.html(info_html);
  }

  function save_selected_days(){
    month_number = parseInt($('.calendar .month_number').html(), 10);
    year_number = parseInt($('.calendar .year_number').html(), 10);
    var selected_days = $('input#selected_days_input').val().split('|');

    $(".calendar td.selected:not('.empty_day')").each(function(){
      selected_days.push(year_number+'-'+month_number+'-'+$(this).html());
    });

    selected_days = selected_days.unique();

    index_of_empty = selected_days.indexOf('', 0, false);
    if(index_of_empty >= 0)
      selected_days.splice(index_of_empty, 1);
    index_of_empty = selected_days.indexOf('0', 0, false);
    if(index_of_empty >= 0)
      selected_days.splice(index_of_empty, 1);

    selected_days.sort(sort_by_date);
    selected_days.reverse();

    $('input#selected_days_input').val(selected_days.join('|'));
  }
  
  function sort_by_date(a, b){
    arr1 = a.split('-');
    arr2 = b.split('-');
    if(arr1[0] != arr2[0])
      return arr2[0] - arr1[0];
    if(arr1[1] != arr2[1])
      return arr2[1] - arr1[1];
    if(arr1[2] != arr2[2])
      return arr2[2] - arr1[2];
  }
});

  
function calculate_price(){
  type_of_break = $('select#type_of_break').val();
  if(typeof(type_of_break) == 'undefined')
    type_of_break = $('input[name="type_of_break"]').val();
  if(typeof(type_of_break) != 'undefined'){
    if(type_of_break == '2')
      price = 420;
    if(type_of_break == '3')
      price = 1000;
    if(type_of_break == 'week')
      price = 1150;
    if(type_of_break == 'weekend')
      price = 799;
    if(type_of_break == 'holiday_weekend')
      price = 975;
    $('#price_info').html('<h2>Final price: &euro;'+price+'.00</h2>');
    $('input[name="price"]').val(price);
  }
}

// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
Array.prototype.indexOf = function( v, b, s ) {
 for( var i = +b || 0, l = this.length; i < l; i++ ) {
  if( this[i]===v || s && this[i]==v ) { return i; }
 }
 return -1;
};
// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

function isInt(i) {
  return (i % 1) == 0;
}
