msAdminList = Class.create();
msAdminList.prototype =
{
  initialize: function (DivId, Url, Options) {

    this.Options = {
      Views: [
        { Id: 'basic', 		Title: 'Lijstweergave',     Img: '/shared/img/mslist/application_view_list.gif', Class: 'msadminlist-modifiers-table'    },
        { Id: 'detail',  	Title: 'Detail weergave', 	Img: '/shared/img/mslist/application_view_detail.gif',  Class: 'msadminlist-modifiers-details'  },
        { Id: 'explorer', 	Title: 'Verkenner',         Img: '/shared/img/mslist/application_view_tile.gif', Class: 'msadminlist-modifiers-icons'    }
        
      ],
      RefreshImg:         '/shared/img/mslist/refresh.gif',
      LoaderImg:          '/shared/img/mslist/loader.gif',
      AltLoaderImg:       '/shared/img/mslist/loader-simple.gif',
      ClearFilterImg:     '/shared/img/mslist/filter-less-options.gif',
      ClassModifiers:     'msadminlist-modifiers',
      ClassContent:       'msadminlist-content',
      AddControls:        false,
      ObjectsPerView:     25,             // How many objects to show
      CurrentPage:        1,
      ViewType:           'basic',        // What was the last view type
      ViewTypeClass:      'active',       // What was the last view type
      SortCol:            '',             // What is the column we're now sorting
      SortDir:            'asc',          // What is the direction we're now sorting
      Root:				        '',             // The root we are exploring in nested lists
      Parent:             '',             // The parent we are dropping children into
      ParentRoot:         '',
      Selected:           [],             // The selected children
      GeneralCallBack:    null,           // Callback on the div where the result of the request was inserted. 
      ReloadEverySeconds: 0,              // Do a refresh every number of seconds; The length of request and response is not included
      AutoPrepare:        false,
      Multiple:           true,           // Allow multiple selects
      ReceptionFailure:   'Het ophalen van de pagina is niet gelukt. Neem contact op met de beheerder.',
      Propagate:          true,           // Propagate events on draggable to underlying elements
      Mutate:			  '',                   // Server side callback function to perform
      MutateParameters:   [],             // Parameter holder for the callback
      Listitems: 		      [],
      ActionURL:          null,
      DeleteURL:          null,
      WithFavorite:       true,
      Delete:             Array(),
      Position:           {},
      Selector: {
        Enabled: false,
      	X: 0,
      	Y: 0,
      	W: 0,
      	H: 0
      	}
      };
    
    Object.extend(this.Options, Options || {});
    
    // disabled explorer view until further notice
    if (this.Options.ViewType == 'explorer') {
      this.Options.ViewType = 'basic';
    }
    
    this.DivId = DivId;
    this.Url = Url;
    
    this.AjaxRequest = null;
    this.ReloadTimeout = null;
    
    if (this.Options.AutoPrepare) {
      this.Prepare();
    }
    else {
      Event.observe(window, 'load', this.Prepare.bindAsEventListener(this));
    }
    
    Event.observe(window, 'scroll', this.getElementCoords.bindAsEventListener(this));
  },
  
  Prepare: function()
  {
    
    this.MainDiv = $(this.DivId);
    
    if (this.Options.AddControls) {

      this.Modifiers = new Element('div').addClassName(this.Options.ClassModifiers).setStyle({'float': 'left', 'cursor': 'pointer'});
      for (var v = 0, st = this.Options.Views.length; v < st; v++)
      {
        var m = new Element('img');
        m.src = this.Options.Views[v].Img;
        m.setAttribute('id',    this.Options.Views[v].Id);
        m.setAttribute('alt',   this.Options.Views[v].Title);
        m.setAttribute('title', this.Options.Views[v].Title);
        
        if (this.Options.Views[v].Id == 'explorer') {
          m.addClassName('modifier-button-disabled');
        }
        Event.observe(m, 'click', this.ChangeView.bindAsEventListener(this, this.Options.Views[v].Id));
        
        this.Modifiers.appendChild(m);
  
        m = null;
      }
      this.MainDiv.appendChild(this.Modifiers);

    }
    
    
    this.RefreshDiv = new Element('div').setStyle({'float': 'right', 'cursor': 'pointer'});
   /*var r = new Element('img');
    r.src = this.Options.RefreshImg;
    r.setAttribute('alt', 'Verversen');
    r.setAttribute('title', 'Verversen');
    Event.observe(r, 'click', this.Refresh.bindAsEventListener(this));
    this.RefreshDiv.appendChild(r);*/
    this.MainDiv.appendChild(this.RefreshDiv);
    /*
    if (this.Options.WithFavorite) {
      this.FavoriteDiv = new Element('div').setStyle({'float': 'right', 'cursor': 'pointer'});
      var r = new Image();
      r.src = this.Options.FavoriteImg;
      r.setAttribute('alt', 'Toevoegen aan favorieten');
      r.setAttribute('title', 'Toevoegen aan favorieten');
      Event.observe(r, 'click', this.addFavorite.bindAsEventListener(this));
      this.FavoriteDiv.appendChild(r);
      this.MainDiv.appendChild(this.FavoriteDiv);
    }
    */
    
    if(typeof(msCMSObjects) != 'undefined') {
      if (this.Options.WithFavorite && msCMSObjects && typeof(msCMSObjects.getById('favoritefilterbtn') != 'undefined')) {
        
        if (typeof(msCMSObjects.getById('favoritefilterbtn').enable) == 'function') {
          msCMSObjects.getById('favoritefilterbtn').enable();
        }
      }
    }
        
    this.PaginatorDiv = new Element('div').setStyle({'float': 'left', 'cursor': 'pointer'});
    this.PaginatorDiv.id = this.DivId + '-paginator';
    this.PaginatorDiv.className = 'mslist-paginator';
    
    this.MainDiv.appendChild(this.PaginatorDiv);
    

    this.RemoteContent = new Element('div').addClassName(this.Options.ClassContent);
    this.RemoteContent.setStyle({'clear': 'both'});
    
    this.MainDiv.appendChild(this.RemoteContent);

    this.MainDiv.onselectstart = function() {
        return false;
    };
    this.MainDiv.unselectable = "on";
    this.MainDiv.style.MozUserSelect = "none";
    this.MainDiv.style.cursor = "default";
    
    this.Refresh(true);
  },

  ChangeView: function(event, NewView)
  {
	  //this.Options.Root = '';
	
	  // disabled explorer view until further notice
    if (NewView == 'explorer') {
      NewView = 'basic';
    }
    
    this.Options.ViewType = NewView;
    this.Refresh();
    
    set_cookie('view for ' + this.Url, NewView, 30);
  },
  
  ChangeSort: function(Col, Dir)
  {
    this.Options.SortCol = Col;
    this.Options.SortDir = Dir;

    this.Refresh();
  },

  ChangeRoot: function(Root)
  {
    this.Options.Root = Root;

    this.Refresh();
  },
  
  ChangeObjectsPerView: function(items)
  {
    this.Options.ObjectsPerView = items;
    
    this.Refresh();
    
    set_cookie('items per page for ' + this.Url, items, 30);
    
    if ($('Perpagina_select')) {
      $('Perpagina_select').value = items;
    }
  },
  
  InsertChildren: function(Parent)
  {

    Selected = [];
    
    this.Options.Listitems.each(function(s) {
      if(s.element.hasClassName('mslist-selected-item')) {
        Selected.push( s.element.id );
      }
    });
    					
    	
    this.Options.Selected = Selected.uniq();				
    
    this.Options.Parent = Parent;

    this.Refresh();
  },
  
  Refresh: function(firsttime)
  {
    // see if we have an information block
    // if so, don't display them
    if (!firsttime) {
      $$('.form-information').each(function(s) { s.style.display = 'none'; });
    }
    else {
      // the view is stored in a cookie, so check if we have it
      view = get_cookie('view for ' + this.Url);

      if (view) {
        
        if (view == 'explorer') view = 'basic';
        
        this.Options.ViewType = view;
          
        if(typeof(msCMSObjects) != 'undefined' ) {
        
          [ 'viewbasicbtn', 'viewdetailbtn', 'viewexplorerbtn' ].each(function(btnId) {
            
            button = msCMSObjects.getById(btnId);
            
            if (button) {
              if (btnId == 'view' + view + 'btn') {
                button.activate();
              }
              else {
                msCMSObjects.getById(btnId).deactivate();
              }
            }
          });
        }
      }
      
      items_per_page = get_cookie('items per page for ' + this.Url);
      
      if (items_per_page)
      {
        this.ChangeObjectsPerView(items_per_page);
      }
    }
    
    this.Options.Listitems = [];
    
    this.showLoader();
    
    window.clearTimeout(this.ReloadTimeout);
    this.AjaxRequest = null;

    this.AjaxRequest = new Ajax.Request(this.Url,  {
      method: 'post',
      parameters: {
        rows: 		this.Options.ObjectsPerView,
        page: 		this.Options.CurrentPage,
        col:  		this.Options.SortCol,
        dir:  		this.Options.SortDir,
        view: 		this.Options.ViewType,
        root: 		this.Options.Root,
        selected: 	this.Options.Selected.toJSON(),
        parent: 	this.Options.Parent,
        mutate: 	this.Options.Mutate,
        mutateparams: this.Options.MutateParameters.toJSON()
      },
      onSuccess: this.AjaxSuccess.bindAsEventListener(this),
      onFailure: this.AjaxFailure.bindAsEventListener(this)
    });
    
    
  },

  AjaxSuccess: function(r)
  {
    this.RemoteContent.update(r.responseText);
    
    if(this.ReloadDiv) {
      this.MainDiv.removeChild(this.ReloadDiv);
      this.ReloadDiv = null;
    }
    
    this.checkButtons();
    
    this.Options.Selected = [];		
    
    this.Options.Parent = '';
    this.Options.Mutate = '';
    this.Options.MutateParameters = [];

    Event.observe(this.DivId  + '-list', 'mousedown', this.handleMousedown.bindAsEventListener(this));
    Event.observe(this.DivId  + '-list', 'mousemove', this.handleMousemove.bindAsEventListener(this));
    Event.observe(this.DivId  + '-list', 'mouseup', this.handleMouseup.bindAsEventListener(this));
    Event.observe(this.DivId  + '-list', 'click', this.handleClick.bindAsEventListener(this));
    Event.observe(this.DivId  + '-selected', 'click', this.propagateClick.bindAsEventListener(this));
    Event.observe(this.DivId  + '-selected', 'mousedown', this.propagateMousedown.bindAsEventListener(this));

    Event.observe(window, 'resize', this.ResizeDetailPane.bindAsEventListener(this));
    
    this.ResizeDetailPane();
    
    this.MainDiv.fire('msAdminList:loaded');
    
    this.AutoReloader();
    
  },

  AjaxFailure: function(r)
  {
    this.MainDiv.removeChild(this.ReloadDiv);
    this.ReloadDiv = null;
    
    this.RemoteContent.update(this.Options.ReceptionFailure);
    this.AutoReloader();
  },
  
  ResizeDetailPane: function(ev)
  {
    
    if (this.Options.ViewType != 'explorer') {
      var what = 'resize' + this.Options.ViewType + 'List()';

      // we cant check for typeof because is always a string :(
      try {
        eval(what);	
      }
      catch(e) {};
    }
    
    if ($('mslist-detail-pane')) {
      $('mslist-detail-pane').style.height = (document.documentElement.clientHeight - Position.cumulativeOffset($('mslist-detail-pane')).top) + 'px';
    }
      
  },
  
  AutoReloader: function()
  {
    if (parseInt(this.Options.ReloadEverySeconds) > 0)
    {
      window.setTimeout(this.Refresh.bindAsEventListener(this), this.Options.ReloadEverySeconds * 1000);
    }
  },
  
  GetSelector: function()
  {
	  return this.Options.Selector;
  },
  
  SetSelector: function(sel)
  {
	 this.Options.Selector = sel;
  },
  
  GetMouseXY: function(ev)
  {
  	ev = ev || window.event;
  	if(ev.pageX || ev.pageY){
  	  this.Options.Position = {
    		x:ev.pageX, 
    		y:ev.pageY
  	  };
  	  
  	  return this.Options.Position;
  		
  	}
	
    this.Options.Position = {
  	  x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
  	  y:ev.clientY + document.body.scrollTop  - document.body.clientTop
  	}
  	
  	return this.Options.Position;
  },
  
  StopPropagation: function(ev)
  {
    this.Options.Propagate = false;
  },

  propagateClick: function(ev)
  {
    if (this.Options.Propagate) {

      selected = $(Obj.DivId+'-selected').style;
  	  selected.display = 'none';
  	    
  	  if (ev.ctrlKey) {
  	    // we can only come here with ctrl pressed
          this.handleClick(ev);
  	  }
    }
    
    this.Options.Propagate = true;
    
  },
  
  propagateMousedown: function(ev)
  {
    if (this.Options.Propagate) {
      
      mousepos = this.GetMouseXY(ev);
  	  Obj = this;
  		  
  	  this.Options.Listitems.each(function(s) {
  		  
    		if (Obj.doIntersect(mousepos.x, mousepos.y, 1, 1, s.x, s.y, s.w, s.h)) {
    		  
    		  if (!s.element.hasClassName('mslist-selected-item')) {
    		    // this item is not selected, so we start a new drag;

    		    Obj.Options.Propagate = false;
    		    
    		    Obj.handleClick(ev);
    		  }
    		  
    		}
    		
        
  	  });
    }
    
    this.Options.Propagate = true;
  },
  
  
  getElementCoords: function(ev)
  {
    this.Options.Listitems = [];
    
  	myOptions = this.Options;
  	
  	if (this.Options != 'undefined') {
     $$('#' + this.DivId + '-list li').each(function(s, index) {
    	   
    	    
    	    
    	lw = $('ListDiv-list').getWidth();
    	
    	rx = Position.cumulativeOffset(s).left;
    	ry = Position.cumulativeOffset(s).top;
    	 
    	if (rx >= (lw - 50)) {
    	  // we have a position problem in IE7
    	  rx = rx - (lw - 50);
    	  
    	  // $('ListDiv-list').cumulativeOffset().top - 
    	  ry = 130 + ry;
    	}
    	// 239
    	
    	
    		myOptions.Listitems.push({ 
    		  x: rx,
    		  y: ry,
    		  w: Element.getDimensions(s).width,
    		  h: Element.getDimensions(s).height,
    		  element: s
    	    });
    	  });
  	}
  },
  
  getScrollTop: function () {
    
    if ($('ListScrollDiv')) {
      return $('ListScrollDiv').scrollTop;
    }
    
    return 0; 

  },
  
  handleClick: function(ev)
  {
	 // if ctrl is pressed, multiselect is possible

	  mousepos = this.GetMouseXY(ev);
	  
	  Obj = this;
	  
	  selectedItem = false;
	  
	  this.Options.Listitems.each(function(s) {
		  
	    if (s.element.hasClassName('mslist-root-folder') || s.element.hasClassName('list-heading')) {
	      return;
	    }
	    
	    //console.log(mousepos.x + ' ' + mousepos.y + ' x:' + s.x + ' m' +s.y  );
	     
	    px = mousepos.x;
	    py = mousepos.y;
	    
	    // please use getElementById because $ always returns 'object'
	    if (document.getElementById('ListScrollDiv')) {
	      py += $('ListScrollDiv').scrollTop;
	    }
	    
	    
  		if (Obj.doIntersect(px, py, 1, 1, s.x, s.y, s.w, s.h)) {
  		  
  		  selectedItem = s;
  		  
  		  if (s.element.hasClassName('mslist-selected-item')) {
    		  s.element.addClassName('mslist-item-draggable');
    		  s.element.removeClassName('mslist-selected-item');
  		  }
  		  else {
  		    s.element.addClassName('mslist-selected-item');
    		  s.element.removeClassName('mslist-item-draggable');
    		  
  		    if (s.element.hasClassName('mslist-folder')) {
  		      if(typeof(selectFolderWrapper) != 'undefined') {
  		        
  		        selectFolderWrapper(Obj.Options.Root + '/' + s.element.id.substr(14), s.element);
  		      }
  		    }
  		    else if (!s.element.hasClassName('mslist-root-folder')) {
  		      if(typeof(selectFileWrapper) != 'undefined') {
  		        selectFileWrapper(Obj.Options.Root + '/' + s.element.id.substr(14), s.element);
  		      }
  		      
  		      
  		      if (Obj.Options.ActionURL && Obj.Options.ActionURL.length > 0) {
  		        // todo: also handle non-url actions, like js functions etc
  		        
  		        if ((navigator.appName.indexOf("Microsoft")!=-1)) {
  		          if($(ev.srcElement).hasClassName('mslist-cell-data')) {
  		            Obj.showLoader('Het object wordt geopend');
    		          window.location.href = Obj.Options.ActionURL + '/id/' + s.element.id.substr(14);
    		        }
  		        }
  		        else {
  		          if(ev.target.hasClassName('mslist-cell-data')) {
  		            Obj.showLoader('Het object wordt geopend');
    		          window.location.href = Obj.Options.ActionURL + '/id/' + s.element.id.substr(14);
    		        }
  		        }
        	  }
  		    }
  		  }
  		}
  		else {
  		  // does not intersect
  		  
  		  // disable multi select
  		  //if (!ev.ctrlKey || !Obj.Options.Multiple) {
  			  s.element.removeClassName('mslist-selected-item');
  			  //s.element.addClassName('mslist-item-draggable');
  		  //}
  		}
  		
	  });
	  
	  
	  // execute custom click handler if it exists
    what = 'click' + this.Options.ViewType + 'List(this, selectedItem)';
      
    // we cant check for typeof because is always a string :(
    try {
      eval(what);	
    }
    catch(e) {};	
      
	  this.updateDragcontainer();
	  
  },
  
  showLoader: function (msg)
  {
    if (!this.ReloadDiv) {
      
      if(typeof($$('#' + this.DivId + ' .list-heading').first()) != 'undefined') {
        test = new Element('span');
        test.style.display = 'block';
        test.style.position = 'absolute';
        test.style.background = "url('" + this.Options.AltLoaderImg + "')";
        test.style.width = '16px';
        test.style.height = '16px';
        test.style.left = '2px';
        test.style.top = '2px';
      
        $$('#' + this.DivId + ' .list-heading').first().appendChild(test);
      }
      else {
        this.ReloadDiv = new Element('div').setStyle({'float': 'left', 'cursor': 'pointer', 'height' : '14px', 'line-height' : '14px' });
        var r = new Image();
        r.src = this.Options.LoaderImg;
        
        if (!msg) {
          msg = translate('Bezig met ophalen van gegevens');
        }
        r.setAttribute('alt', msg);
        r.setAttribute('title', msg);
        r.setAttribute('style', 'margin: 0 5px 0 0');
        var p = new Element('span');
        p.addClassName('ajax-loader-info');
        p.innerHTML = msg;
        this.ReloadDiv.appendChild(r);
        this.ReloadDiv.appendChild(p);
        this.MainDiv.insertBefore(this.ReloadDiv, this.RefreshDiv);
      }
    }
  },
  
  handleMousedown: function(ev)
  {
    if (this.Options.Multiple) {
    
      this.getElementCoords();
      
      sel = this.GetSelector();
      mousepos = this.GetMouseXY(ev);
      
      sel.X = mousepos.x;
      sel.Y = mousepos.y;
      sel.W = 0;
      sel.H = 0;
      sel.Enabled = true;
      
      this.SetSelector(sel);
      
      if ($(this.DivId+'-overlay')) {
        overlay = $(this.DivId+'-overlay').style;
        overlay.position = 'absolute';
        
        overlay.top = '10px';
        overlay.left = '0px';
        overlay.width = '0px';	
        overlay.height = '0px';
        
        overlay.display = 'block';
      }
    }
    
    // execute custom mousedown handler if it exists
    what = 'mousedown' + this.Options.ViewType + 'List(this)';
      
    // we cant check for typeof because is always a string :(
    try {
      eval(what);	
    }
    catch(e) {};	
  }, 
  
  handleMouseup: function(ev)
  {  
    this.getElementCoords();
    
  	sel = this.GetSelector();
  	sel.Enabled = false;
  	this.SetSelector(sel);
  	
  	overlay = $(this.DivId+'-overlay').style;
  	//overlay.display = 'none';
  	//overlay.top = '50px';
  	
  	// execute custom mouseup handler if it exists
    what = 'mouseup' + this.Options.ViewType + 'List(ev)';
      
    // we cant check for typeof because is always a string :(
    try {
      eval(what);	
    }
    catch(e) {};	
    
  	this.updateDragcontainer();
  	
  },

  handleMousemove: function(ev)
  {
    
    // multiple select is disabled
    return;
    
    
    mousepos = this.GetMouseXY(ev);
    
    if (!this.Options.Multiple) {
      return;
    }
    
  	sel = this.GetSelector();
  
  	dx = mousepos.x - sel.X;
  	dy = mousepos.y - sel.Y;
  
  	
  	if (dx < 0) {
      // right is before left, so swap coords to keep it simple
  	  dx *= -1;
  	}
  
  	if (dy < 0) {
  	  dy *= -1;
  	}
  		
  	sel.W = dx;
  	sel.H = dy;
  
  	this.SetSelector(sel);
  	
  	if (!$(this.DivId+'-overlay')) {
  	  return false;
  	}
  	
  	overlay = $(this.DivId+'-overlay').style;

  	if (sel.Enabled) {
  	  overlay.top = (((Math.min(sel.Y, mousepos.y) + 4) - Position.cumulativeOffset($(this.DivId)).top) - 50 ) + 'px';
  	  overlay.left = ((Math.min(sel.X, mousepos.x) + 4) - Position.cumulativeOffset($(this.DivId)).left)+ 'px';
  	  overlay.width = sel.W + 'px';
  	  overlay.height = sel.H + 'px';
      
  	  Obj = this;
  	  
  	  // in Windows Explorer, pressing CTRL inverts the result
  	  
  	  this.Options.Listitems.each(function(s) {
  		  
  	    
  	    //console.log('%s %s %s %s', Math.min(sel.X - Position.cumulativeOffset(Obj.DivId).left, mousepos.x), Math.min(sel.Y - Position.cumulativeOffset(Obj.DivId).top, mousepos.y), sel.W, sel.H);
  	    
    		if (Obj.doIntersect(Math.min(sel.X - Position.cumulativeOffset(Obj.DivId).left, mousepos.x), Math.min(sel.Y - Position.cumulativeOffset(Obj.DivId).top, mousepos.y), sel.W, sel.H, s.x, s.y, s.w, s.h)) {
    			
    			if (ev.ctrlKey) {
    				if (s.element.hasClassName('mslist-inverted-selected-item')) {
    					s.element.addClassName('mslist-selected-item');
    					s.element.removeClassName('mslist-item-draggable');
    					s.element.removeClassName('mslist-inverted-selected-item');
    				}
    				else {
    					s.element.addClassName('mslist-selected-item');
    					s.element.addClassName('mslist-inverted-selected-item');
    					s.element.removeClassName('mslist-item-draggable');
    				}
    				
    			}
    			else {
    				s.element.addClassName('mslist-selected-item');
    				s.element.removeClassName('mslist-item-draggable');
    			}
    		}
    		else {
    				s.element.removeClassName('mslist-selected-item');
    				s.element.addClassName('mslist-item-draggable');
    		}
    		
  	  });
  	  
  	}
  },
  
  updateDragcontainer: function()
  {
    if (!this.Options.Multiple) {
      return;
    }
    
	  s =  $(this.DivId);
	  
	  selContainer = {
	    x: Position.cumulativeOffset(s).left,
  	  y: Position.cumulativeOffset(s).top,
  	  w: Element.getDimensions(s).width,
  	  h: Element.getDimensions(s).height
	  };
  
    selected = $(this.DivId+'-selected').style;
    
    t = (Prototype.Browser.IE) ? 2 : 0;
    
	  selected.top = t + 'px';
	  selected.left = 0 + 'px';
	  
	  selected.width = selContainer.w + 'px';
	  selected.height = selContainer.h + 'px';
	  selected.position = 'absolute';
	  selected.display = 'block';
	  
	  $(this.DivId+'-selected').update();
	  
    $(this.DivId+'-selected').insert($(this.DivId+'-content').innerHTML);
	  
    Obj = this;
	  
    $$('#' + this.DivId + '-selected ul').each(function(s) {
      s.style.background = 'transparent';
      
      // please leave this as is: Internet Explorer does not get innerHTML in any other way
      tags = s.getElementsByTagName('li');
      
      for (i in tags) {
        
        if(typeof(tags[i].style) != 'undefined') {
          tags[i].style.background = 'transparent';
          
          Element.extend(tags[i]);
          
          if(!tags[i].hasClassName('mslist-selected-item')) {
            tags[i].innerHTML = '';
          }
        }
      }
	  });
	  
    this.checkButtons();
  },
  
  checkButtons: function()
  {
	  has_files = false;
	  has_folders = false;
	  has_selected_files = false;
	    
		selected = 0;

		$$('#' + this.DivId + '-list li').each(function(s) {
		  
		  if(s.hasClassName('mslist-root-folder')) {
		    return;
		  }
		  
      if(s.hasClassName('mslist-selected-item')) {
        
        selected++;
        
        if (current_vfs_name != 'undefined') {
	        s.getElementsBySelector('span').each(function(s) {
	          current_vfs_name = s.innerHTML;
	        });
        }
        
    	  if(s.hasClassName('mslist-folder')) {
    		  has_folders = true;
    	  }
    	  else {
    		  has_selected_files = true;
    	  }
      }
      
      if(s.hasClassName('mslist-folder') || s.hasClassName('mslist-item')) {
    	  has_files = true;
    	  
    	  
      }
    });
	    
	  // if only files are selected, enable the delete files button
	  // if the folder is empty, enable the delete folder button
	  // console.log('has files %s has folders %s', has_files, has_folders);
	    
	  if (!this.Options.AddControls) {
	    // controls are in the ribbon
	    
	    var deleteitemsbtn = msCMSObjects.getById('deleteitemsbtn');
	    if (deleteitemsbtn != false) {
        if (has_selected_files && !has_folders) {
        	deleteitemsbtn.enable();
        }
        else {
        	deleteitemsbtn.disable();
        }
	    }
	    
	    var deletefolderbtn = msCMSObjects.getById('deletefolderbtn');
	    if (deletefolderbtn != false) {
        if (!has_files && !has_folders) {
        	deletefolderbtn.enable();
        }
        else {
        	deletefolderbtn.disable();
        }
	    }
    
	    var renamebtn = msCMSObjects.getById('renamebtn');
	    
	    if (typeof(renamebtn) == 'object') {
        if (selected > 1) {
          renamebtn.enable();
        }
        else {
          renamebtn.disable();
        }
	    }
	  }
  },
  
  addFolder: function(foldername)
  {
	  //console.log('adding folder %s', foldername);
	  
	  this.Options.Mutate = 'add_folder';
	  this.Options.MutateParameters.push({f: foldername});
	  
	  this.Refresh();
	  
  },
  
  sortOn: function(column, index)
  {
	  this.Options.SortCol = column;
	  this.Options.SortDir = ( this.Options.SortDir == 'asc') ? 'desc' : 'asc';
	  
	  Obj = this;
	  
	  $$('.list-heading a').each(function(s) {

	    if (s.id == 'sort-handle-'+index) {
	      s.addClassName('sort-'+Obj.Options.SortDir);
	      s.removeClassName('sort-'+ ( Obj.Options.SortDir == 'asc' ? 'desc' : 'asc' ));
	    }
	    else {
	      s.removeClassName('sort-asc');
	      s.removeClassName('sort-desc');
	    }
	    
	  });

	  this.Refresh();
	  
  },
  
  setPage: function (page)
  {
    this.Options.CurrentPage = page;
    this.Refresh();
  },
  
  deleteFolder: function()
  {
	  
	  this.Options.Mutate = 'delete_folder';
	  this.Options.Root = this.Options.Root;
	  
	  this.Refresh();
  },
  
  deleteSelectedItems: function()
  {
	  
	  Params = [];
	  
	  $$('#' + this.DivId + ' li').each(function(s) {

		  if(s.hasClassName('mslist-selected-item')) {
		    if(s.hasClassName('mslist-item')) {
		    	Params.push( s.id );
		    }
		  } 
	  });
	  
	  Params = Params.uniq();	
	  
	  
	  this.Options.Mutate = 'delete_items';
	  this.Options.MutateParameters.push({f: Params});
	  
	  this.Refresh();
	  
	  
  },
  
  renameItem: function(name)
  {
    Params = [];
	  
	  $$('#' + this.DivId + ' li').each(function(s) {

		  if(s.hasClassName('mslist-selected-item')) {
		    if(s.hasClassName('mslist-item')) {
		    	Params.push( s.id );
		    }
		  } 
	  });
	  
	  Params = Params.uniq();	
	  
	  
	  this.Options.Mutate = 'rename_item';
	  this.Options.MutateParameters.push({f: Params, n: name});
	  
	  this.Refresh();
  },
  
  SetParentRoot: function(root)
  {
	  this.Options.ParentRoot = root;
  },
  
  doIntersect: function (x1, y1, w1, h1, x2, y2, w2, h2)
  {
  	var ix1, iy2, iw, ih, intersect = true;
    var e1x1 = x1;
    var e1x2 = x1 + w1;
    var e1y1 = y1;
    var e1y2 = y1 + h1;
    var e2x1 = x2
    var e2x2 = x2 + w2;
    var e2y1 = y2
    var e2y2 = y2 + h2;
    // horizontal
    if (e1x1 <= e2x1) {
      ix1 = e2x1;
      if (e1x2 < e2x1) intersect = false;
      else iw = Math.min(e1x2, e2x2) - e2x1;
    }
    else {
      ix1 = e1x1;
      if (e2x2 < e1x1) intersect = false;
      else iw = Math.min(e1x2, e2x2) - e1x1;
    }
    // vertical
    if (e1y2 >= e2y2) {
      iy2 = e2y2;
      if (e1y1 > e2y2) intersect = false;
      else ih = e2y2 - Math.max(e1y1, e2y1);
    }
    else {
      iy2 = e1y2;
      if (e2y1 > e1y2) intersect = false;
      else ih = e1y2 - Math.max(e1y1, e2y1);
    }

    return intersect;

  },
  
  disable: function ()
  {
  },
  
  listHandlerSwitchView: function (event, params)
  {

    if (msCMSObjects != 'undefined') {
      btns = [ 'viewbasicbtn', 'viewdetailbtn', 'viewexplorerbtn' ];
      
      btns.each(function(btnId) {
        if (btnId == 'view' + params + 'btn') {
          msCMSObjects.getById(btnId).activate();
        }
        else {
          msCMSObjects.getById(btnId).deactivate();
        }
      });
    }
    
    ListObj.ChangeView(event, params);
  },
  
  SetPaginator: function (paginator)
  {
    $(this.DivId + '-paginator').innerHTML = paginator;
  },

  markForDeletion: function (id, del)
  {
    this.Options.Delete[id] = !del;
    
    can_delete = false;
    
    for (i in this.Options.Delete) {
      if (typeof(this.Options.Delete[i]) == 'function') continue;
      
      if (this.Options.Delete[i]) {
        can_delete = true;
      }
    }
    
    if (can_delete) {
      msCMSObjects.getById('deleteitemsbtn').enable();
    }
    else {
      msCMSObjects.getById('deleteitemsbtn').disable();
    }
    
  },
  
  deleteItems: function (ev)
  {
    Params = [];
    
    t = 0;
    
    for (i in this.Options.Delete) {
      if (typeof(this.Options.Delete[i]) == 'function') continue;
      
      if (this.Options.Delete[i]) {
        Params.push(i);
        t++;
      }
    }
	  
	  Params = Params.uniq();	
	  
	  msg = (t == 1) ? 'Weet je zeker dat je dit item wilt verwijderen?' : 'Weet je zeker dat je deze items wilt verwijderen?';
	  
	  if(confirm(translate(msg))) {
	  
  	  this.Options.Mutate = 'delete_items';
  	  
  	  this.Options.MutateParameters.length = 0;
  	  
  	  this.Options.MutateParameters.push({f: Params});
  	  
  	  this.Options.Delete.length = 0;
  	   
  	  this.Refresh();
	  }
  },
  
  saveOrder: function (ev)
  {
    var ret = [];
    
    this.recurseList('#ListDiv-list > .mslist-item', ret, this.Options.Root);
  
    this.Options.Mutate = 'save_order';
    this.Options.MutateParameters.push({o: ret});
    
    this.Refresh();
    
    saveorderbtn = msCMSObjects.getById('saveorderbtn');
    if (saveorderbtn) {
      saveorderbtn.disable();
    }
  },
  
  recurseList: function (list, ret, pad)
  {
    Obj = this;
    
    $$(list).each(function(s) {
      
      if (s.id.substr(0, 14) == 'listitem-list_') {
        cur = s.id.substr(14);
        ret.push( pad + '_' + cur);
            
        Obj.recurseList('#' + s.id + ' > ul > li', ret, pad + '_' + cur);
      }
    });
  },
  
  advancedFilter: function ()
  {
    popup = new msWindowMaker(env + '/listhandler/advancedfilter/url' + this.Url);
    popup.Prepare();
    popup.Show();
  },
  
  hasFilters: function(yes) 
  {
    msCMSObjects.getById('removefilterbtn').enable();
  },
  
  ClearFilters: function()
  {
    el = this;
     new Ajax.Request(env + '/listhandler/advancedfilter/clear/filters', {
       onSuccess: function()
       {
         msCMSObjects.getById('removefilterbtn').disable();
         el.Refresh();
       }
     });
  },
  
  addFavorite: function()
  {
    if (name = prompt('Voeg deze pagina aan uw favorieten toe.', 'Lijstweergave')) {
      
      new Ajax.Request(env + '/favorites/add', {
        parameters: {
          name: name,
          options: Object.toJSON(this.Options),
          url: window.location.href,
          ftype: 'list'
        }
      });
      
    }
  }
}

list_tools_widths = Array();

