// 
//  admin.js
//  
//  Copyright 2011 Osborne Brook Partnership Limited. All rights reserved.
// 


$(document).ready(function(){
  
  // Delete links
  OB.initDeleteLink();

  // Clickable table rows
  $('tr.selectable').live('click', function() {
    var link = $(this).closest('tr').attr('rel');
    window.location = location.protocol + '//' + location.host + link;
  });
  
  $('tr.selectable td a').live('click', function(e) {
    e.stopPropagation();
  });
  
  // Messages
  OB.hideMessages(false);
  OB.showMessages();
  
  // Logout link
  $('.logout_link').click(function(e) {
    if ( !confirm('Are you sure you want to log out?') ) { e.preventDefault(); }
  });
  
});

OB.initDeleteLink = function() {
  $('.delete_link').live('click', function(){
    var path = $(this).attr('href');
    var prompt = $(this).attr('rel');
    var redirect = $(this).attr('rev');

    if (confirm(prompt)) {
      $.post(path, {'_method' : 'delete'}, function(ret){
        if (ret == "OK") {
          if (redirect.match(/^#eval__/)) {  
            var run = redirect.replace(/^#eval__/,'');
            eval(run);
          } else if (redirect) {
            window.location = redirect;
          } else {
            window.location.reload();
          }
        } else if (ret.match('CONFIRM')) {
          message = ret.replace('CONFIRM', '').trim();
          if (confirm("Please confirm delete action again: " + message)) {
            $.post(path, {'_method' : 'delete', 'confirm' : 1 }, function(ret){
              if (redirect.match(/^#eval__/)) {  
                var run = redirect.replace(/^#eval__/,'');
                eval(run);
              } else if (redirect) {
                window.location = redirect;
              } else {
                window.location.reload();
              }
            });
          }
        } else {
          error_message = ret.replace('ERROR', '').trim();
          alert("Sorry, but I can't delete this object. " + error_message);
        }
      });
    }
    return false;
  });
};

// Toggles a div by a clickable element (button). You must specify the
// foldable element in the buttons "ref" attribute, and the button texts
// in the "rel" and "ref" attributes.
OB.toggleByButton = function(button, no_animate) {
  no_animate = no_animate || false;
  var basic_wrapper = $(button).attr('ref');
  
  if ( $(basic_wrapper).is(':hidden') ) {
    no_animate ? $(basic_wrapper).show() : $(basic_wrapper).slideDown('slow');
    $(button).text( $(button).attr('rev') ).addClass('open');
  } else {
    no_animate ? $(basic_wrapper).hide() : $(basic_wrapper).slideUp('slow');
    $(button).text( $(button).attr('rel') ).removeClass('open');
  }
};

OB.toggleByCheckbox = function(checkbox, no_animate) {
  no_animate = no_animate || false;
  var wrapper = $(checkbox).attr('ref');
  
  if ( $(checkbox).is(':checked') ) {
    no_animate ? $(wrapper).show() : $(wrapper).slideDown();
  } else {
    no_animate ? $(wrapper).hide() : $(wrapper).slideUp();
  }
};

OB.getURLParameter = function(name) {
  return decodeURI(
    (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
  );
};

// SerializeObject

(function($) {
  $.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
      o[this.name] = this.value || '';
    });
    return o;
  };
})(jQuery);

// obForm jQuery plugin

(function($) {
  $.fn.obForm = function(options) {

    if (!options) options = {};
    var options = $.extend({
      prefix: ''
    }, options);

    return this.each(function() {
        
      $(this).ajaxForm({
        dataType: 'json',
        beforeSerialize: options.beforeSerialize,
        success: function(data, status, xhr, $form) {

          $('input, select, textarea', $form).removeClass('error');
          $('.errormessage', $form).remove();
          $('.field').removeClass('error');
          
          // Redirect?
          if (data.redirect) {
            window.location.href = data.redirect;
          
          // Success message?
          } else if (data.success_message) {
            $('#messages').remove();
            $('body').prepend('<div id="messages"><ul>' + data.success_message + '</ul></div>');
            OB.showMessages();
          
          // Showing errors
          } else {
            var generrors = '';
            $.each(data, function(f, m) {

              // Appending error message to the field's label
              if ($('#' + options.prefix + f + '_field').length > 0) {
                $('#' + options.prefix + f + '_field').addClass('error').find('label').first().append(' <span class="errormessage" id="' + f + '_err">' + m + '</span>');
              
              // ... or preparing the message panel to show the error message
              } else {
                generrors += '<li class="error">' + f + ' ' + m + '</li>';
              }
            });
            
            // Scrolling to the error
            var error_position = $('.field.error').length > 0 ? $('.field.error').first().position().top : 0;
            $('html,body').animate({ scrollTop: error_position }, { duration: 'slow', easing: 'swing'});
            
            // Showing the message panel
            if (generrors != '') {
              $('#messages').remove();
              $('body').prepend('<div id="messages"><ul>' + generrors + '</ul></div>');
              OB.showMessages();
            }
            
            // Focus on the first field with errors
            $('input.error, select.error, textarea.error', $form).eq(0).focus();
          }
          
          if (data.status == "OK" && options.onSuccess) {
            options.onSuccess();
          }
        }
      });
      
    });
  }
})(jQuery);

