// Hooks for SPS login
setMyAccountCloseHook(function() {
  location.reload();
})

setOnSignOutHook(function() {
  location.reload();
})


// TODO use class name like "tabs" instead of "section_lesson" id
$(document).ready(function() {
  $('#section-lesson').tabs();
  $('#searchForm').searchForm();
  // Displays modal popup for not logged in user
  $('#modal-no-access').jqm({trigger: '.modal-no-access', modal: false});
});

// TODO move to separate file
// On Resource New page
function removeSubjects() {
  $('#categoryTable select').val('');
  $('.subsubject').html('');
  $('#categoryTable tbody:gt(1)').hide();
}

// On Resource New page
function addSubjects() {
  $('#categoryTable tbody:hidden:first').show();
}

// On Resource New page
function toggleEditorArea(textArea){
  textArea = $(textArea);
  textArea.is(':hidden') ? textArea.show('slow') : textArea.hide('slow');
}

// On Resource New page
function saveAsDraft() {
  button = $('#resource_draft')
  button.val(1);
  button.parents('form').submit();
}

(function($) {
  $.fn.togglePreview = function() {
    this.live("click", function() {
      var button = $(this);
      var parent = button.parents('li');

      if(parent.hasClass('preview')) {
        parent.removeClass('preview');
        button.removeClass('accordion_toggle_active');
      } else {
        parent.addClass('preview');
        button.addClass('accordion_toggle_active');
      }
    });
  };
})(jQuery);

(function($) {
  $.fn.rating = function() {
    var container = $(this);
    var ratings   = container.children('li');
    var form      = container.next('form');
    var input     = form.children('input:first').disable();

    var init = function() {
      // Activate rating based on current score
      var score = form.children('input[name*=[score]]').val();
      var active_ratings = container.children('li:lt(' + score + ')').addClass('rating-active');

      ratings.hover(
        function() {
          active_ratings.removeClass('rating-active');

          $(this).prevAll().andSelf().addClass('rating-hover');
          $(this).nextAll().removeClass('rating-hover');
        },
        function() {
          $(this).siblings().andSelf().removeClass('rating-hover');

          active_ratings.addClass('rating-active');
        }
      );

      var clickHandler = function() {
        var parent = $(this).parent();

        active_ratings = parent.prevAll().andSelf().addClass('rating-active');
        parent.nextAll().removeClass('rating-active');

        var rating = $(this).text();
        input.enable().val(rating);

        $.post(
          form.attr('action'),
          form.serialize(),
          function(data, textStatus) {},
          'json'
        );

        // Unbind onclick handler, so it's not possible to click more than once
        ratings.children('span').unbind("click", clickHandler);

        return false;
      };

      ratings.children('span').click(clickHandler);
    };

    init();
    return this;
  };
})(jQuery);

// TODO allow to provide function instead of id
// (so it's possible to fetch element relative to 'this')
(function($) {
  $.fn.updateCharCount = function(limit, notifyId) {
    var update = function(self) {
      self = $(self);
      var limitLeft = limit - self.val().length;
      if(limitLeft < 1) {
        self.val(self.val().substr(0, limit));
      }
      $(notifyId).text(limitLeft.toString());
    };

    update(this);

    return this.keyup(function() {
      update(this);
    });
  };
})(jQuery);


(function($) {
  $.fn.searchForm = function() {
    var form = $(this);
    var advancedForm = form.find('.box-modify');
    var buttons = form.find('input[name=search_type]');
    var defaultButton = form.find('input[name=search_type]:checked');

    // Submit the form whenever select or radio button is changed
    // Using click for IE7 compatibility
    advancedForm.find('input[type=radio]').click(function() {
      this.form.submit();
    });

    advancedForm.find('select').change(function() {
      this.form.submit();
    });

    buttons.click(function() {
      var button = $(this);

      // Update form action
      var action = button.attr('rel');
      form.attr('action', action);

      // Toggle advanced search form
      if (advancedForm.length) {
        var advancedFields = advancedForm.find('input, select');

        if (button.val() != defaultButton.val()) {
          advancedFields.disable();
          advancedForm.hide();
        } else {
          advancedFields.enable();
          advancedForm.show();
        }
      }
    });

    return this;
  };
})(jQuery);

(function($) {
  $.fn.cycle = function(options) {
    if (!this.length) return this;

    options = $.extend({
      delay: 5000,
      random: false
    }, options);
    var elements   = this;
    var cycle      = function() {
      var nextElement;
      if (options.random) {
        nextElement = $(elements[Math.floor(Math.random() * elements.length)]);
      } else {
        var currentElement = elements.filter(':visible');
        nextElement = $(currentElement.next()[0] ? currentElement.next()[0] : elements[0]);
      }

      elements.hide();
      nextElement.show();
    };

    cycle();
    setInterval(cycle, options.delay);

    return this;
  }
})(jQuery);

// Form namespace
var Form = {};

// Tinymce with character limit
Form.TinymceHammer = {
  init : function() {
    var init = {
      width: 517,
      height: 150,
      theme: "advanced",
      theme_advanced_toolbar_align: "left",
      theme_advanced_toolbar_location: "top",
      theme_advanced_buttons1: "undo,redo,cut,copy,paste,pastetext,|,bold,italic,strikethrough,blockquote,charmap,bullist,numlist,removeformat,|,link,unlink,image,|,cleanup,code",
      theme_advanced_buttons2 : "",
      theme_advanced_buttons3 : "",
      valid_elements : "a[href|title],blockquote[cite],br,caption,cite,code,dl,dt,dd,em,i,img[src|alt|title|width|height|align],li,ol,p,pre,q[cite],small,strike,strong/b,sub,sup,u,ul",
      setup: function(ed) {
        ed.onKeyUp.add(function(ed, o) {
          var editor = tinyMCE.activeEditor;
          var charsLeft = Number($('#'+editor.id).attr('data-chars_limit')) - editor.getContent().length;
          var text = "You have " + charsLeft.toString() + " characters remaining";
          $('#' + editor.id + "_chars_remaining").text(text);
        });
      }
    };
    init.mode = 'specific_textareas';
    init.editor_selector = 'tinymce';
    init.plugins = 'paste';
    init.language = 'en';

    tinyMCE.init(init);
  }
};

// Callbacks for MultiFile plugin to create/remove description for each file input
Form.MultiFile = {
  addDescription: function(fileInput, descriptionId) {
    fileInput       = $(fileInput);
    var description = $('#' + descriptionId).val();
    var name        = fileInput.attr('name').replace(/\[file\]$/, '[description]');
    var id          = name.replace(/\]\[|\[|\]/g, '_').slice(0, -1);

    var descriptionInput = $('<input />').attr({
      value: description,
      name:  name,
      id:    id,
      type:  'hidden'
    });

    $(fileInput).after(descriptionInput);
    $('#' + descriptionId).val('');
    if (description.length > 0) {
      $('.MultiFile-label :last').append(' - ' + description);
    }
  },
  removeDescription: function(fileInput) {
    fileInput = $(fileInput);
    var name  = fileInput.attr('name').replace(/\[file\]$/, '[description]');
    var id    = name.replace(/\]\[|\[|\]/g, '_').slice(0, -1);

    $('#' + id).remove();
  }
};

// TODO refactor it into something more meaningful
function setModalUrl(fieldName, url, value) {
    $('#' + fieldName).attr('href', url);
    $('#' + fieldName + 'Name').html(value);    // Delete contact
    $('#' + fieldName + 'Title1').html(value);  //
    $('#' + fieldName + 'Title2').html(value);  //
    return true;
}
