/* Utilities */ 


function nextHighestIndex(draggable) {
  var dragboxes = document.getElementsByClassName('win');
  var highest = 0;
  
  for(var i = 0, length = dragboxes.length; i < length; i++) {
    var thisValue = parseInt(dragboxes[i].style.zIndex);
    if(dragboxes[i] != draggable.element && thisValue > highest) {
      highest = thisValue;
    }
  }
  return highest+1;
}

/* Cookie */

var Cookie = {
  
  get: function(name) {
    var nameEQ = name + "=";
  	var ca = document.cookie.split(';');
  	for(var i=0;i < ca.length;i++) {
  		var c = ca[i];
  		while (c.charAt(0)==' ') c = c.substring(1,c.length);
  		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  	}
  	return null;  	
  },
  
  set: function(name, value) {
    var exp = new Date();
    var nowPlusOneWeek = exp.getTime() + (7*24*60*60*1000);
    exp.setTime(nowPlusOneWeek);
    
    document.cookie = name+"=" + value + "; path=/; expires=" + exp.toGMTString();
  }
    
}


/* Stage */

var Stage = {
  
  COOKIE_NAME : 'positions',
  
  cleanUp: function(level) {
    // Loop through open windows
    $$('div.win').each(function(win){ 
      // Loop through classnames and destroy all on the same level
      Element.classNames(win).select(function(classname){return classname.match(/level_\d+/);}).each(function(classname) {
        if(parseInt(classname.split('_').last()) == level) 
          Element.remove(win);
      })
    });
  },
  
  close: function(id) {
    Element.remove(id);
  },
  
  cachePosition: function(id) {
    var element = $(id);
    if (element) {
      var left = parseInt(element.getStyle('left'));
      var top = parseInt(element.getStyle('top'));
      var level = Element.classNames(element).select(function(classname){return classname.match(/level_\d+/);});
      
      var cookie_value = Stage.formatCookieValue(level, left, top);
          
      Cookie.set(Stage.COOKIE_NAME, cookie_value);
    }    
  },
  
  formatCookieValue: function(level, left, top) {
    var positions = $H();  
    
    // Get the stored positions from the cookie
    var current_positions = Cookie.get(Stage.COOKIE_NAME);
    if (current_positions) {
      current_positions.split(',').each(function(value){
        var pair = value.split(':');
        positions[pair[0]] = pair[1];
      })
    }
    // Add OR overwrite the current level with the new position
    positions[level] = left + 'x' + top;
    
    // Format the output level_n:leftxtop,...
    var result = new Array();
    positions.each(function(pair){
      result.push(pair.key + ':' + pair.value);
    })
    
    return result.join(',');
  }
  
}