/* -----------------------------------------------------------

Javascript for managing cookies.

NOTE: This file does not contain any course-specific code.

Created by Philip Hutchison for the 
University of California, San Francisco (UCSF) Medical Center.
2006-2007

Cookie functions (createCookie, readCookie) by Peter-Paul Koch
Copied from http://www.quirksmode.org/js/cookies.html

----------------------------------------------------------- */

function createCookie(name,value,days) {
	
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	
	document.cookie = name+"="+value+expires+"; path=/";
	//alert("creating document.cookie: " +document.cookie);
	
}

function readCookie(name) {
	
	//alert("reading document.cookie: " +document.cookie);
	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;
}

function eraseCookie(name) {
	var answerOK = confirm("Are you sure you want to delete the cookie\n\"" +name +"\"?");
	if (answerOK){
		createCookie(name,"",-1);
	}
	else {
		return false;
	}
}


//----- Course cookie function(s) -----//
//Extracts course data from cookie and returns as a variable (bookmark = object, completedPages = nested array) 
//targets available: bookmark (object), completedPages (array)
function getCookieData(cookieName, targetVariable){

	//alert("getCookieData called. name: \"" +cookieName +"\"" +"\n" +"Target data: " +targetVariable);

	//If cookie doesn't exists, stop here.
	if( !(readCookie(cookieName)) ) return null;
	
	//Otherwise, read cookie
	var cookieData = readCookie(cookieName);

	var returnedData = null;
	
	if(targetVariable == "bookmark"){
		returnedData = {};
		returnedData.url = cookieData.split("|`|")[0].split("^")[0];
		returnedData.title = cookieData.split("|`|")[0].split("^")[1];
	}
	if(targetVariable == "completionData"){
		if(cookieData.split("|`|")[1]){
			returnedData = cookieData.split("|`|")[1].split(",");
		}
		else {
			returnedData = null;
		}
	}
	return returnedData;
}
