// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var p360 = {
  init: function(){
    jQuery.ajaxSetup({
      'beforeSend': function(xhr) {
        xhr.setRequestHeader("Accept", "text/javascript")
        }
    });
    this.add_child_id('.add_child_id');
    this.add_child_string('.add_child_string');
    this.editor('.markitup');
    this.datepicker('.datepicker');
    this.datetimepicker('.datetimepicker');
    this.autocomplete('.autocomplete');
    this.tooltip('span[title]');
    this.addFromAutoComplete('.add_child');
    this.removeChild('.remove_child');
    this.simpleAutocomplete('.simple-autocomplete');
    this.auto_select('.autoselect');
    this.delete_parent('.delete_parent');
    this.delete_parent_bar('.delete_parent_bar');
  },

  add_child_id: function(selector){
    $(selector).click(function() {
      name = $(this).prev().val()
      id = $(this).prev().prev().val()
      list = $(this).prev().prev().prev()
      list_count = list.children().length
      if (id != "" && id != undefined && name != "")
      {
        list.append("<li class='nice_item'>" + name + "<input type='hidden' name='recipient[" + list_count + "]' value='" + id + "' /><a href='javascript:void(0)' class='delete_parent'>X</a></li>")
        $(this).prev().val("")
      }
    });
  },

  add_child_string: function(selector){
    $(selector).click(function() {
      name = $(this).prev().val()
      list = $(this).prev().prev()
      list_count = list.children().length
      if (name != undefined && name != "")
      {
        list.append("<li class='nice_item'>" + name + "<input type='hidden' name='recipient[" + list_count + "]' value='" + name + "' /><a href='javascript:void(0)' class='delete_parent'>X</a></li>")
        $(this).prev().val("")
      }
    });
  },

  auto_select: function(selector){
    auto_select(selector)
  },

  delete_parent: function(selector){
    $(selector).live('click', function(){
      $(this).parent().fadeOut('fast', function() {
	    $(this).remove();
	  })
    })
  },
  
  delete_parent_bar: function(selector){
    $(selector).live('click', function(){
      $(this).parent().parent().fadeOut('fast', function() {
	    $(this).remove();
	  })
    })
  },

  editor: function(selector){
    $(selector).markItUp(mySettings);
  },

  datepicker: function(selector, options){
    var defaults = {
      duration: 1,
      changeMonth: true,
      changeYear: true,
      yearRange: '1900:2020',
      showAnim: 'fadeIn',
      constrainInput: true
    }
    options = jQuery.extend(defaults, options);
    $(selector).datepicker(options);
  },

  datetimepicker: function(selector, options){
    var defaults = {
      showTime: true,
      stepMinutes: 1,
      stepHours: 1,
      altTimeField: '',
      time24h: false
    }
    options = jQuery.extend(defaults, options);
    this.datepicker(selector, options);
  },

  tooltip: function(selector){
    $(selector).tooltip({
      tip: '.tooltip',
      effect: 'fade',
      fadeOutTime: 1000
    }).dynamic({
      bottom: {
        direction: 'down',
        bounce: true
      }
    });
  },

  addChild: function(selector) {
    var link = $(selector);
    link.click(function(){
      var association = $(this).data('association');
      var template = $('#' + association + '_fields_template').html();
      var regexp = new RegExp('new_' + association, 'g');
      var new_id = new Date().getTime();
      link.parent().before(template.replace(regexp, new_id));
      p360.autocomplete('.autocomplete');
      return false;
    });
  },

  removeChild: function(selector) {
    $(selector).live('click', function(){
      $(this).parent().hide();
      $(this).prev("input[type=hidden]").val('1');
      return false;
    });
  },

  addFromAutoComplete: function(selector) {
    var link = $(selector);
    link.click(function(){
      var association = $(this).attr('data-association');
      
      //IE doesn't seem to like .html(), so I replaced the line below with the line after. It's a dirty hack, but it works in IE.
      //var template = $('#' + association + '_fields_template').html();
      var template = '<li> <strong>RESULT</strong> <input id="seminar_appointments_attributes_new_appointments_patient_id" name="seminar[appointments_attributes][new_appointments][patient_id]" type="hidden" value="VALUE" /> <input id="seminar_appointments_attributes_new_appointments__destroy" name="seminar[appointments_attributes][new_appointments][_destroy]" type="hidden" value="false" /> <a href="#" class="remove_child">Delete</a> </li>'
      
      var input = link.prev();
      
      if (input.val() == ''){
        return false;
      }
      
      if (input.data('id') == undefined)
      {
        return false;
      }
      
      var regex = {}
      regex.assoc = new RegExp('new_' + association, 'g');
      regex.result = new RegExp('RESULT', 'g');
      regex.value = new RegExp('VALUE', 'g');
      
      template = template.replace(regex.assoc, new Date().getTime());
      template = template.replace(regex.result, input.data('label'));
      template = template.replace(regex.value, input.data('id'));
      input.parent().before(template);
      input.val('');
      input.removeData('id');
      input.removeData('label');
      return false;
    });
  },

  autocomplete: function(selector) {
    var inputs = $(selector);
    inputs.each(function(){
      var self = $(this);
      var url = self.attr('data-remote');
      self.autocomplete({
        source: function(request, response) {
          $.ajax({
            url: url,
            dataType: "json",
            data: {
              search: request.term
            },
            success: function(data) {
              response($.map(data, function(item) {
                return {
                  label: item.result,
                  value: item.result,
                  id: item.value
                }
              }));
            }
          });
        },
        select: function(event, ui) {
          self.data('id', ui.item.id);
          self.data('label', ui.item.label);
        }
      });
    });
  },
  
  simpleAutocomplete: function(selector) {
    var inputs = $(selector);
    inputs.each(function(){
      var self = $(this);
      var url = self.attr('data-remote');
      self.autocomplete({
        source: function(request, response) {
          $.ajax({
            url: url,
            dataType: "json",
            data: {
              search: request.term
            },
            success: function(data) {
              response($.map(data, function(item) {
                return {
                  label: item.result,
                  value: item.result,
                  id: item.value
                }
              }));
            }
          });
        },
        select: function(event, ui) {
          self.prev("input[type=hidden]").val(ui.item.id);
          if ($(this).attr('callback') != undefined)
          {
            eval($(this).attr('callback'))
          }
        }
      });
    });
  }
};

function countdown(c)
{
  if (c == 0)
  {
    $("#flash_failure").text("You may now attempt to log in again.")
  }
  else
  {
    $("#flash_failure").text(("Due to repeatedly entering incorrect credentials, you must wait " + c + " second(s) before you may attempt to log in again."))
    c--
    setTimeout(("countdown(" + c + ")"), 1000)
  }
};


c = parseInt($("body").attr("countdown"));
if (c > 0)
{
  countdown(c)
}

$(document).ready(function(){
  p360.init();
  
  $('.history_header').click(function() {
    $('.history_box').slideToggle('slow')
  })
  
  $('.toggle_header').click(function() {
    $(this).next().slideToggle('slow')
  })
  
  $('.toggle_header_blend').click(function() {
    $(this).parent().parent().next().slideToggle('slow')
  })
  
  $(':radio').addClass("real_radio")
  $(':checkbox').addClass("real_checkbox")
  
  if ($('#flash_success').text() != "")
  {
    $('#flash_success').addClass("hidden")
    $.gritter.add({
      title: "Success",
      text: $('#flash_success').text()
    })
  }
  
  if ($('#flash_error').text() != "")
  {
    $('#flash_error').addClass("hidden")
    $.gritter.add({
      title: "Error",
      text: $('#flash_error').text()
    })
  }
  
  if ($('#flash_notice').text() != "")
  {
    $('#flash_notice').addClass("hidden")
    $.gritter.add({
      title: "Notice",
      text: $('#flash_notice').text()
    })
  }
  
});