// Copyright Pierre Saslawsky 2006 - pierre(at@)photobiker(dot.)com


//-----------------------------------------------------------------------
//	Utilities
//-----------------------------------------------------------------------

function strParamVal(str, paramName) {
	var paramList = str.substr(0,str.length);
	var aParam = paramList.split("&")
	for (i=0; i<aParam.length; i++) {
		if (paramName == aParam[i].split("=")[0]) {

			return aParam[i].split("=")[1]
		}
	}
	return "";
}	

function paramVal(paramName) {
	return strParamVal(location.search.substring(1), paramName);
}	


//-----------------------------------------------------------------------
//	Cookies
//-----------------------------------------------------------------------

function getCookie(Name) {
   var search = Name + "=";
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search);
      if (offset != -1) { // if cookie exists 
         offset += search.length;
         // set index of beginning of value
         end = document.cookie.indexOf(";", offset);
         // set index of end of cookie value
         if (end == -1) 
            end = document.cookie.length;

         return unescape(document.cookie.substring(offset, end));
      } 
   }
   return "";
}


function getCookieParam(paramName) {
	var cookie = getCookie("MerrittGrooms");
	var cookieTemp = getCookie("MerrittGroomsTemp");
	if (cookieTemp.length > 0)
		cookie += '&' + cookieTemp;
	return strParamVal(unescape(cookie), paramName);
}


function writeCookieParam(paramName, value, isPersistent) {
	var cookieName = (isPersistent ? "MerrittGrooms" : "MerrittGroomsTemp");
	var cookie = getCookie(cookieName);

	cookie = unescape(cookie);
	var offset = cookie.indexOf(paramName);
	if (offset != -1) {
		// remove the old param/value pair
		var end = cookie.indexOf('&', offset);
		if (end == -1) {
			// the pair was last in the cookie
			cookie = cookie.substring(0, offset);
		}
		else {
			// the pair was inside the cookie
			cookie = cookie.substring(0, offset-1) + cookie.substring(end+1);
		}
	}

	value = String(value);
	if (value.length > 0) {
		if (cookie.length > 0 && cookie.charAt(cookie.length-1) != '&')
			cookie += '&';
		cookie += paramName + '=' + value;
	}
	
	var cookieString = cookieName + "=" + escape(cookie) + ";path=/";
	if (isPersistent) {
		var today = new Date();
		var expires = new Date();
		expires.setTime(today.getTime() + 1000*60*60*24*365);
		cookieString += ";expires=" + expires.toGMTString();

	}
	document.cookie = cookieString;

}


function writeCommentsCookie(commentsEnabled) {
	writeCookieParam('comments', commentsEnabled, false);
}



function readCommentsCookie() {
	return getCookieParam('comments');
}

