// Thickbox need to initialize on pageload. So need to processing to make it work on ajax load. See http://www.djcnet.co.uk/jquery-thickbox-on-ajax-generated-pages.html

function removeThickBoxEvents() {
        $('.thickbox').each(function(i) {
            $(this).unbind('click');
        });
    }

function bindThickBoxEvents() {
        removeThickBoxEvents();
        tb_init('a.thickbox, area.thickbox, input.thickbox');
    }

// Adds the .js mime to URLs, so that Rails fires the correct respond_to response.
var mimeifyUrl = function(url){
  if (/\.js/.test(url)){
    return url
  } else if (/\?/.test(url)) {
    return url.replace('?', '.js?')
  } else {
    return url + '.js'
  }
}

$.ajaxSetup({
  complete: function(response, status){
    tb_init('a.thickbox, area.thickbox, input.thickbox');
  //  $('#loading_indicator').hide(); //TODO improve this
  },
  error: function(){
    alert('An error occured!') // TODO: replace this with your own awesome error handler
  },
  beforeSend: function(request, params){
  //  $('#loading_indicator').show()
  }
});

// Similar to the built in 'load' function in jQuery, extended so that it adds the .js mime to
// the url.
$.fn.railsLoad = function(location){
  var self = this;
  $.ajax({
    url: mimeifyUrl(location),
    success: function(response, status){
      $(self).html(response);
    }
  });
}

// initial on load
$(function() {
})


// make a textbox a datepicker
$.fn.standardDateSelect = function() {
  this.datepicker({
    dateFormat: 'yy-mm-dd',
    changeYear: true,
    changeMonth: true,
    duration: '',
    yearRange: '1900:2020'
  }); 
}

