var lasturl="";  //here we store the current URL hash
var loading = {};

function changeTab(tabName) {
  var tab = $('#tab-' + tabName);
  var content = $('#desc-' + tabName);
  
  if (tab.hasClass('navitab')) {
    $('.active-tab').removeClass('active-tab');
    $('.activenavitab').removeClass('activenavitab').addClass('navitab');
    content.addClass('active-tab');
    tab.addClass('activenavitab').removeClass('navitab');
  }
}

function loadPage(url)  //the function that loads pages via AJAX
{
  var regex = new RegExp('#\/(.*)\/');
  var res = regex.exec(url);
  
  url = res[1];
  
  if (loading[url]) {
    return;
  }
  loading[url] = true;
  
  $('#loading').css('visibility','visible');  //show the rotating gif animatio

  $.get(
    window.location.protocol + '//' + window.location.hostname + '/load/'+url,
    {},
    function(page){
      $('#main').html(page.content);  //load the returned html into pageContet
      $('#loading').css('visibility','hidden');  //and hide the rotating gif
      changeTab(page.tab);
      $('a').blur();
      delete (loading[page.slug]);
    },
    'json'
  );
}

function checkURL(hash)
{ 
  if(!hash) {hash=window.location.hash;}  //if no parameter is provided, use the hash value from the current address

  if(hash != lasturl)  // if the hash value has changed
  {
    lasturl=hash;  //update the current hash
    loadPage(hash);  // and load the new page
  }
}

$().ready(function() {  //executed after the page has loaded
  $('body').ajaxComplete(function () {
    $('#main a.zoom').colorbox({'onClosed': function(){ $(this).blur(); }});
    $('#main a[rel=colorbox]').colorbox({'onClosed': function(){ $(this).blur(); }});
    $('div.gallery a').colorbox({'onClosed': function(){ $(this).blur(); }, 'current':'Image {current} of {total}'});
  });
      
  checkURL();  //check if the URL has a reference to a page and load it

  $('a.nav').click(function (e){  //traverse through all our navigation links..
      checkURL(this.hash);  //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
      this.blur();
  });
  $('#sidebar a').click(function (e){  //traverse through all our navigation links..
      checkURL(this.hash);  //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
      this.blur();
  });

  setInterval(function() {checkURL();},250);  //check for a change in the URL every 250 ms to detect if the history buttons have been used

  $('#navitabs a').mouseover(function(){
    var regex = new RegExp('tab-(.*)');
    var res = regex.exec($(this).attr('id'));
    var tab = res[1];
    changeTab(tab);
  });

  var pages = ['home','townhouse','beaches','in-the-area','getting-there','bookings','contact-us','golf','bookings/new'];
  var location, hash;
  
  if (window.location.hash) {
    var regex = new RegExp('#\/(.*)\/');
    var res = regex.exec(window.location.hash);
    hash = res[1];
  }
  if (-1 != $.inArray(hash, pages)) {
    location = hash;
  }
  else {
    location = 'home';
  }
  loadPage('#/'+location+'/');
  
  $('#checkPrice').live('click',function(){
    var dateFrom, dateTo;
    
    $(this).val('Checking').attr('disabled','disabled');
    
    dateFrom = $('#booking_date_from_year').val() + '-' + $('#booking_date_from_month').val() + '-' + $('#booking_date_from_day').val();
    dateTo = $('#booking_date_to_year').val() + '-' + $('#booking_date_to_month').val() + '-' + $('#booking_date_to_day').val();
    
    $.get('/load/bookings/check', { 'startDate': dateFrom, 'endDate': dateTo },function (data) {
      var statusField = $('#status');
      
      if (data.valid) {
        statusField.css('color','green');
        $('#book_submit').removeAttr('disabled');
      } else {
        statusField.css('color','red');
        $('#book_submit').attr('disabled','disabled');
      }
      
      statusField.html(data.message);
      
      $('#checkPrice').removeAttr('disabled').val('Check price and availability');
    },'json');
  });
  
  $('#booking-form select').live('focusout', function () {
    var bookingform, date;
    
    bookingform = $('#booking-form');
    date = $('#booking_date_from_year').val() + '-' + $('#booking_date_from_month').val() + '-' + $('#booking_date_from_day').val() + '-' + $('#booking_date_to_year').val() + '-' + $('#booking_date_to_month').val() + '-' + $('#booking_date_to_day').val();
    
    if (bookingform.data('date') !== date) {
      bookingform.data('date',date);
      $('#book_submit').attr('disabled','disabled');
      $('#status').html('');
    }
  });
  
  $('#book_submit').live('click',function(){
    var bookingform = $('#booking-form');
    
    $(this).val('Submitting...').attr('disabled','disabled');
    $.post('/load/bookings/book',bookingform.serializeArray(),function(data){
      $('#main').html(data.content);
      $('#checkPrice').click();
    },'json');
    return false;
  });

  /*$('form#booking-form').live('submit',function(){alert('hello there');
      $(this).find('input[type=submit]').val('Submitting...').attr('disabled','disabled');
      $.post('/load/bookings/book',$(this).serialize(),function(data){
        $('#main').html(data.content);
        $('#checkPrice').click();
      },'json');
//      return false;
    });*/
});

