/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

function CookieFavourites(dir, callback) {
  this.dir = dir;
  this.callback = callback;
  this.cookie = null;
  this.global = null;
  if (window.globalStorage) {
    try {
      this.global = globalStorage[location.hostname];
    }
    catch (e) {
      //Fall back to Cookies
    }  
  }
  if (this.global == null) {
    this.cookie = new Cookie("Favourites");
  }  
  var _self = this;

  this.loaded = function(list) {
    _self.setAll(list);
    if (_self.callback) {
      _self.callback(list);
    }  
  }  
  
  this.reload(this.loaded);
}

CookieFavourites.prototype = new Favourites();

CookieFavourites.prototype.saveAll = function() {
  var result = this.saveArray(this.getAll(), 2);
  if (this.global) {
    this.global.widgetopFavourites = result;
  }
  else {
    this.cookie.store(result);
  }  
}

CookieFavourites.prototype.saveArray = function(array) {
  var result = "["
  for (var i = 0; i < array.length; i++) {
  	if (i > 0) {
  	  result += ",";
  	}
  	result += "['" + array[i].title + "','" + array[i].path + "']";
  }
  result += "]";
  return result;
}

CookieFavourites.prototype.reload = function(callback) {
  try {
    var value = null;
    if (this.global) {
      value = this.global.widgetopFavourites;
      if (value != null) {
        value = "" + value;
      }
    }
    else {
      value = this.cookie.get();
    }      
    if (value == null) {
      callback(defaultFavourites);
      return;
      if (value == null) {
        callback(new Array());
        return;
      }      
    }
    var array = eval(value);
    var result = new Array(array.length);
    for (var i = 0; i < array.length; i++) {
    	var obj = new Object();
    	obj.title = array[i][0];
    	obj.path = array[i][1];
    	result[i] = obj;
    }
    callback(result);
  }
  catch (e) {
    callback(new Array());
    //addError("Reloading from Cookie failed: " + e);
  }  
}

CookieFavourites.prototype.clear = function() {
  CookieFavourites.prototype.setAll.call(this, new Array());
}

