/* Functions used for creating and manipulating cookies via cookie objects.
 *
 * 16-Aug-2005 [Mike Ford] Extract into separate file 
 */

function leedsMetCookie(name, hours, path, domain) {

  this.$name = name;
  this.$expiry = hours ? new Date((new Date()).getTime() + hours*60*60*1000) : null;
  this.$path = path ? path : "/";
  this.$domain = domain ? domain : ".leedsmet.ac.uk";

  var cookies = document.cookie;
  if (cookies=="") {
	return;
  }

  var wantedCookie = cookies.match("(^|;\\s?)" + name + "=([^;]*)(;|$)");
  if (wantedCookie===null) {
    return;
  }

  // if the cookie exists, decode its sub-cookies

  var settings = wantedCookie[2].split("||");
  for (var i=0, n=settings.length; i<n; i++)
  {
	subCookie = settings[i].split("::");
    this[subCookie[0]] = unescape(subCookie[1]);
  }
}

leedsMetCookie.prototype.save = function() {
  var newCookie = "";
  for (var subCookie in this) {
	if (subCookie.charAt(0)!="$" && typeof this[subCookie]!="function") {
	  newCookie += (newCookie?"||":"") + subCookie + "::" + escape(this[subCookie]);
	}
  }

  var fullCookie = this.$name + "=";
  if (newCookie)
    fullCookie += newCookie + (this.$expiry ? "; expires=" + this.$expiry.toUTCString() : '');
  else
	fullCookie += "; expires=Fri, 02-Jan-1970 00:00:00 GMT";
  fullCookie += (this.$path ? "; path=" + this.$path : '') +
				(this.$domain ? "; domain=" + this.$domain : '');

  document.cookie = fullCookie;
}

function init_cookies(cookie)
{
  if (cookie==undefined) {
	cookie = '__test__';
  }

  var can_cook = navigator.cookieEnabled;
  var settings = null;

  // if cookieEnabled property is undefined, be more cunning:
  if (can_cook===undefined) {
    // first, instantiate the cookie object, set a dummy value and save it.
    settings = new leedsMetCookie(cookie, 24*365);
    settings.t_t = 't';
    settings.save();
    settings = null;
  }

  if (can_cook!==false) {
    // cookieEnabled property is either undefined or true -- do the only or second cookie
	// fetch (respectively)
    settings = new leedsMetCookie(cookie, 24*365);
	if (can_cook===undefined) {
	  // being cunning: see if we got the test value, and delete it if we did.
	  if (settings.t_t) {
	    // ok, cookies work
	    delete settings.t_t;
	    settings.save()
      }
      else {
	    // no, they don't -- return the bad news
        settings = null;
      }
	}
  }
  // return the cookie object, or null
  return settings;
}
