// Cookie Functions
// Write cookie by name
// Example:
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours)
{
  var expire = "";
  if(hours != null)
  {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire;
}

// Retrieve cookie by name
// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}

//Clear cookie
function clearCookie ( name ) {
	var threeDays = 3 * 24 * 60 * 60 * 1000;
	var expDate = new Date();
	expDate.setTime (expDate.getTime() - threeDays);
	document.cookie = name + "=ImOutOfHere; expires=" + expDate.toGMTString();
}


// Append to cookie with custom delimiter.

function appendCookie(myCookie,myValue,myDelimiter,addOrRemove){
 // Check for cookies
 if (document.cookie && document.cookie != ""){
  // Read old cookie
  oldValue = readCookie(myCookie);
  // Check if new value exists in old cookie
  isCurrent = oldValue.indexOf(myValue);
  // Check old cookie value and whether to add or remove cookie value
  if (isCurrent == -1 && addOrRemove == 'add') {
   if (oldValue && oldValue != '') {
    // Append cookie
   document.cookie= myCookie + '=' + escape(oldValue+myDelimiter+myValue);
   }
	 else{
    //Start new cookie using myValue for cookie value
    document.cookie = myCookie + '=' + escape(myValue);
   } 
	}	
	else if (isCurrent != -1 && addOrRemove == 'remove') {
   if (oldValue && oldValue != '') {
    // Remove cookie
 	  myNewValue = oldValue.replace(myValue, '');		
    document.cookie= myCookie + '=' + escape(myNewValue);
	 }
	}
	// Clean up delimeters
	myCleanString = readCookie(myCookie).replace(/;*;/gi, ';');
	myCleanString = myCleanString.replace(/^;/gi, '');
	myCleanString = myCleanString.replace(/;$/gi, '');
	document.cookie = myCookie + '=' + escape(myCleanString);
 }
}
