function selectScopeIcon(elt)
{
  var imgs = elt.parentNode.parentNode.getElementsByTagName('img');
  for (var i = 0; i < imgs.length; i++) {
    imgs[i].className = "new_scope_icon";	
  }
  elt.className = "new_selected_scope_icon";

  document.getElementById('image_url').value = jQuery(elt).attr('src');
}

function selectAll(chk,elt)
{
  var chks = document.getElementById(elt).getElementsByTagName('input');

  for (var i = 0; i < chks.length; i++) {
    if (chk.checked) {
      chks[i].checked = true;
    } else {
      chks[i].checked = false;
    }
  }
}

function doChecks(divId,parentChk)
{
  var chks = document.getElementById(divId).getElementsByTagName('input');
  var allChecked = true;
  for (var i = 0; i < chks.length; i++) {
    if (!chks[i].checked) {
      document.getElementById(parentChk).checked = false;
      allChecked = false;
      break;
    }
  }
  if (allChecked) document.getElementById(parentChk).checked = true;
}

function scopeAdd()
{
  var scopes = document.getElementById('current_scopes').options;

  for (var i = 0; i < scopes.length; i++) {
    if (scopes[i].selected) 
    {
      var selectedScopes = document.getElementById('scopes[]').options;
      var notThere = true;
      for (var j = 0; j < selectedScopes.length; j++) {
        if (selectedScopes[j].value == scopes[i].value)
        {
          notThere = false;
        }
      }

      if (notThere) {
        var newOpt = document.createElement('option');
        newOpt.innerHTML = scopes[i].text;
        newOpt.value = scopes[i].value;
        document.getElementById('scopes[]').appendChild(newOpt);
        jQuery(scopes[i]).remove();
      }
    }
  }
}

function scopeRemove()
{
  var scopes = document.getElementById('scopes[]').options;

  for (var i = 0; i < scopes.length; i++) {
    if (scopes[i].selected) 
    {
      var optionClone = jQuery(scopes[i]).clone();
      document.getElementById('scopes[]').removeChild(scopes[i]);
      jQuery('#current_scopes').append(optionClone);
    }
  }
}

function selectScopes()
{
  var scopes = document.getElementById('scopes[]').options;

  for (var i = 0; i < scopes.length; i++) {
    scopes[i].selected = true;
  }
}

function makeDefault()
{
  var scopes = document.getElementById('scopes[]').options;
  var gotselected = false;

  for (var i = 0; i < scopes.length; i++) {
    if (scopes[i].selected) {

      var newOpt = document.createElement('option');
      newOpt.innerHTML = scopes[i].text;
      newOpt.value = scopes[i].value;

      document.getElementById('scopes[]').removeChild(scopes[i]);

      document.getElementById('scopes[]').insertBefore(newOpt,scopes[0]);

      gotselected = true;

      break;
    }
  }
  if (!gotselected) alert("Please select a scope to use as the default.");
}

(function ($) {
  function isEmpty(checkBox) {
    return checkBox.attr('rel') !== 'partial' && !checkBox.attr('checked');
  }
  
  $.fn.scopeDesign = function (options) {
    return $(this).addClass('scopeDesign').find('li').each(function () {
      var config = $.extend({}, {
        withChecked: false,
        scopeId: null
      }, options);
        
      var self = $(this);
      
      var topicId = this.id.substring('topic_'.length);
      var checkBox = self.find('input[type=checkbox]');
      var lnk = self.find('a');
      
      checkBox.threeStateCheckBox({isOnGray: true});
      checkBox.scopeDesignComputedState();
      
      lnk.click(function (evt) {
        if (initialTarget(evt).tagName !== 'INPUT' && initialTarget(evt).tagName !== 'SPAN') {
          self.find('.topic_ajax_load').removeClass('hidden');
          var targetContainer = self.find('ul');
          targetContainer.load('/scopes/subtopics' + (config.withChecked ? '_with_checked' : '') + '/' + topicId + '?all=' + checkBox.attr('checked') + (config.withChecked ? ('&scope_id=' + config.scopeId) : '') + (isEmpty(checkBox) ? '&empty=true' : ''), function () {
            self.find('.topic_ajax_load').addClass('hidden');
            self.find('.subtopics_wpr').removeClass('hidden');
            self.addClass('expanded');
            lnk.unbind('click');
            lnk.click(function (e) {
              if (initialTarget(e).tagName !== 'INPUT' && initialTarget(e).tagName !== 'SPAN') {
                self.find('.subtopics_wpr').toggleClass('hidden');
                self.toggleClass('expanded');
              }
            });
            targetContainer.find('.subtopic').each(function () {
              var subtopicSelf = $(this);
              var subtopicId = this.id.substring('subtopic_'.length);
              var subtopicCheckBox = subtopicSelf.find('input[type=checkbox]');
              var subtopicLink = subtopicSelf.find('a');
              
              subtopicCheckBox.threeStateCheckBox();
              subtopicCheckBox.scopeDesignComputedState();
              
              subtopicLink.click(function (ee) {
                var lessonsTargetContainer = subtopicSelf.find('ul');
                subtopicSelf.find('.subtopic_ajax_load').removeClass('hidden');
                lessonsTargetContainer.load('/scopes/lessons' + (config.withChecked ? '_with_checked' : '') + '/' + topicId + '?sub_topic_id=' + subtopicId + '&all=' + subtopicCheckBox.attr('checked') + (config.withChecked ? ('&scope_id=' + config.scopeId) : '') + (isEmpty(subtopicCheckBox) ? '&empty=true' : ''), function () {
                  subtopicSelf.find('.lessons_wpr').removeClass('hidden');
                  subtopicSelf.find('.subtopic_ajax_load').addClass('hidden');
                  subtopicLink.unbind('click');
                  
                  subtopicLink.click(function (e) {
                    if (initialTarget(e).tagName !== 'INPUT' && initialTarget(e).tagName !== 'IMG') {
                      subtopicSelf.find('.lessons_wpr').toggleClass('hidden');
                    }
                  });
                  
                  lessonsTargetContainer.find('.lesson').each(function () {
                    var lessonSelf = $(this);
                    var lessonId = this.id.substring('lesson_'.length);
                    var lessonCheckBox = lessonSelf.find('input[type=checkbox]');
                    var lessonLink = lessonSelf.find('a');
                    
                    lessonCheckBox.threeStateCheckBox();
                    lessonCheckBox.scopeDesignComputedState();
                  });
                });
              });
            });
          });
        }
      });
    });
  };

  $.fn.threeStateCheckBox = function (options) {
    function getState(el) {
      return el.attr('checked') ? 'checked' : (el.attr('rel') === 'partial' ? 'partial' : 'unchecked');
    }
    
    return $(this).each(function () {
      var el = $(this), state = getState($(this));
      var img = $('<span alt="" class="three_state_checkbox_img"></span>').insertAfter(el);
      
      var config = $.extend({}, {
        isOnGray: false
      }, options);
      
      if (config.isOnGray) {
        img.addClass('gray');
      }
      
      el.hide();
      
      function updateImages(imgState) {
        img.setClass('checked', imgState === 'checked');
        img.setClass('unchecked', imgState === 'unchecked');
        img.setClass('partial', imgState === 'partial');
      }
      
      function check(evt, stopPropagation) {
        el.attr('checked', 'checked');
        el.removeAttr('rel');
        updateImages('checked');
        updateState(!stopPropagation);
        el.trigger('checked');
      }
      
      function uncheck(evt, stopPropagation) {
        el.removeAttr('checked');
        el.removeAttr('rel');
        updateImages('unchecked');
        updateState(!stopPropagation);
        if (!stopPropagation) {
          el.trigger('unchecked');
        }
      }
      
      function makePartial(evt, stopPropagation) {
        el.removeAttr('checked');
        el.attr('rel', 'partial');
        updateImages('partial');
        updateState(!stopPropagation);
        if (!stopPropagation) {
          el.trigger('partial');
        }
      }
      
      function updateState(fireEvent) {
        state = getState(el);
        if (fireEvent) {
          el.trigger('statechange', [state]);
        }
      }
      
      img.click(function () {
        switch(state) {
          case 'checked': 
            uncheck();
            break;
          default:
            check();
            break;
        }
      });
      
      el.bind('makepartial', makePartial);
      el.bind('check', check);
      el.bind('uncheck', uncheck);
      
      if (state === 'checked') { check(); }
      if (state === 'unchecked') { uncheck(); }
      if (state === 'partial') { makePartial(); }
    });
  };
    
  $.fn.scopeDesignComputedState = function () {
    
    function handleStateChange(parentEl) {
      var nChecked = parentEl.find('input[checked]').length;
      var nTotal = parentEl.find('input[type=checkbox]').length;
      if (nChecked === nTotal) {
        $(parentEl.closest('li').find('input[type=checkbox]')[0]).trigger('check');
      } else if (nChecked > 0) {
        $(parentEl.closest('li').find('input[type=checkbox]')[0]).trigger('makepartial');
      } else {
        $(parentEl.closest('li').find('input[type=checkbox]')[0]).trigger('uncheck');
      }
    }
    
    return $(this).each(function () {
      var el = $(this);
      el.bind('statechange', function (evt, state) {
        if (state ==='checked') {
          el.closest('li').find('ul input[type=checkbox]').trigger('check', [true]);
          handleStateChange(el.closest('ul'));
        } else if (state === 'unchecked') {
          el.closest('li').find('ul input[type=checkbox]').trigger('uncheck', [true]);
          handleStateChange(el.closest('ul'));
        } else {
          handleStateChange(el.closest('ul'));
        }
      });
    });
  };

  $(document).ready(function () {
    // $('.sub_item').live('click', function (evt) {
    //   $(this).closest('.subtopics_wpr').prev('li').find('.topic_checkbox').removeAttr('checked').trigger('statechange');
    //   $(this).closest('.lessons_wpr').prev('li').find('.subtopic_selected').removeAttr('checked').trigger('statechange');
    //   $(this).closest('.videos_wpr').prev('li').find('.lesson_selected').removeAttr('checked').trigger('statechange');
    // });
    // 
    // $('.topic_checkbox').live('click', function (evt) {
    //   $(this).closest('li').next('.subtopics_wpr').find('.sub_item').attr("checked", "checked").trigger('statechange');
    // });
    // 
    // $('.subtopic_selected').live('click', function (evt) {
    //   $(this).closest('li').next('.lessons_wpr').find('.sub_item').attr("checked", "checked").trigger('statechange');
    // });
    // 
    // $('.lesson_selected').live('click', function (evt) {
    //   $(this).closest('li').next('.videos_wpr').find('.sub_item').attr("checked", "checked").trigger('statechange');
    // });
  });
})(jQuery);
