//
// cookie management routines
//

/**
 * Returns the actual cookie name for the specified neutral name such as "P", "C" etc. 
 * To help separate cookies between different running musubi environments such as
 * production, trunk, staging etc, the actual cookie names are the nuetral name concatenated with 
 * a suffix. This helps to prevent them from overlapping with cookies from different 
 * environment of musubi.
 * For example for STAGING environment given the name "P" => will return "P_staging".
 * 
 * The result cookie name is the concatenation of the 'name' + '_' and the 
 * configured cookies name suffix for the current running environment / run mode.
 */
function generateCookieName(neutralName)
{
	if (config.CookiesNameSuffix != "")
		return neutralName + '_' + config.CookiesNameSuffix;
	else
		return neutralName;
}


// These three are from quirksmode.org:
//
//
function midnight(aDate) {
    var d = aDate;
    if (!d)
    {
        d = new Date();
    }
    return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}

function createCookie(name,value,days)
{
	name = generateCookieName(name);
    var expires = "";
    if (days)
    {
        var m = midnight();
        m.setTime(m.getTime()+(days*24*60*60*1000));
        expires = "; expires="+m.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/; domain=" + config.CookiesDomain + ";";
}

function readCookie(name)
{
  var nameEQ = generateCookieName(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)
{
  createCookie(name,"",-1);
}

function unencodeCookie( cookieName )
{
  c = readCookie( cookieName );
  if ( c ) {
    s = unescape( c );
    if (s.charAt(0)=='"')
      s = s.substring( 1, s.length-1 );
    return MochiKit.Base.evalJSON( s );
  }
  return null;
}

function emptyProfile()
{
  return { "e": "", c:"", "l" : { "s" : null, "c": null, "z": null } };
}

function emptySessionClear()
{
  return { "n": "", "q":"", "fb_feed":null};
}

var gProfile = unencodeCookie("P") || emptyProfile();
var gClearSession = unencodeCookie("C") || emptySessionClear();

function updateProfileCookie()
{
  createCookie( "P", escape(MochiKit.Base.serializeJSON( gProfile )), 365*10 );
}

function updateClearSessionCookie()
{
  createCookie( "C", escape(MochiKit.Base.serializeJSON( gClearSession )), 1 );
}

function getProfileEmail()
{
  return gProfile["e"];
}

function getProfileCompany()
{
  return gProfile["c"] || "";
}

function resetProfileEmail()
{
  gProfile["e"]=null;
  updateProfileCookie();
}

function resetProfileAndSession()
{
  eraseCookie("P");
  eraseCookie("C");
  eraseCookie("S");
  gProfile = emptyProfile();
  gClearSession =  emptySessionClear();
}

function isUserConfirmed() 
{
    return gClearSession["c"] || null;
}

function getSessionUserName()
{
  return gClearSession["n"];
}

function getSessionQuery()
{
  return gClearSession["q"] || "";
}

function getSessionPhoneCall()
{
  return gClearSession["p"] || "";
}

function getSessionPhoneNumber()
{
  return gClearSession["pn"] || "";
}

function getSessionFbFeed() {
  gClearSession = unencodeCookie("C") || emptySessionClear(); // unencode this again just incase it was set via ajax
  return gClearSession["fb_feed"] || null;
}

function clearSessionFbFeed() {
  gClearSession["fb_feed"] = null;
  updateClearSessionCookie();
}

function getProfileLocation()
{
  return gProfile["l"] || resetProfileLocation();
}

function getProfileState()
{
  l = getProfileLocation();
  return l.s;
}

function getProfileCity()
{
  l = getProfileLocation();
  return l.c;
}

function getProfileZip()
{
  l = getProfileLocation();
  return l.z;
}

function getProfileNeighborhood()
{
  l = getProfileLocation();
  return l.n;
}

function getProfileUserId() {
    return gProfile["uid"] || null
}

function resetProfileLocation()
{
  gProfile["l"] = { "s" : null, "c": null, "z": null, "n":null };
  updateProfileCookie();
  return gProfile["l"];
}

function setProfileLocation( s, c, z, n )
{
  gProfile["l"] = { "s" : s, "c": c, "z": z, "n":n };
  updateProfileCookie();
}

function setLinkback( url )
{
  gClearSession["il"]=url;
  updateClearSessionCookie();
}

function getProfileCoupons() {
	coupons =  gProfile["k"];
	if (!coupons) {
		coupons = new Array();
		gProfile["k"] = coupons;
	}
	jslog('debug', 'getProfileCoupons', coupons);
	return coupons;
}

function indexOfCoupon(cid) {
	var coupons = gProfile["k"];
	if (!coupons) return false;
	var len = coupons.length;
	for (var i = 0; i < len; i++) {
		if (coupons[i] == cid)
			return i;
	}
	return -1;
}

function insertProfileCoupon(cid) {
	coupons = gProfile["k"];
	if (indexOfCoupon(cid) == -1) {
		coupons[coupons.length] = cid;
		setProfileCoupons(coupons);
		return true;
	}
	return false;
}

function deleteProfileCoupon(cid) {
	coupons = gProfile["k"];
	var idx = indexOfCoupon(cid);
	if (idx != -1) {
		cid = coupons[idx];
		delete coupons[idx];
		setProfileCoupons(coupons);
		return cid;
	}
	return 0;
}

function setProfileCoupons(coupons) {
	gProfile["k"] = coupons;
	updateProfileCookie();
}

function getProfileTimesLoggedIn() {
    return gProfile["n"] || 0
}

function getProfileAlias() {
    return gProfile["alias"] || "Profile"
}


/*
  directory navigation
 */

/*
  Fills in the location of the 2 box search
*/
function qnNav()
{
  s = getProfileState();
  c = getProfileCity();
  z = getProfileZip();
  n = getProfileNeighborhood();
  qn = '';
  qcs = ''; //neighborhood
  
  if ( s ) {

    if ( s && c && z ) {
     qn = c+', ' + s + ' ' + z;
    }
    else if ( s && c && n ) {
     qn = c+', ' + s;
     qcs = n;
     try {
         updateNodeAttributes('qcs', {'value': qcs} );
     } catch (e) {
         log(e);
     }
    }
    else if ( s && c ) {
     qn = c+', ' + s;
    }
    else if ( s ){
     qn = s;
    }
  }

  updateNodeAttributes('q', {'value':getSessionQuery()});
  updateNodeAttributes('qn', {'value': qn} );
}

function writeProfileStyle(id) {
	if (id && getProfileCompany() == id) {
		document.write('<link rel="stylesheet" type="text/css" href="/static/style/consumer/owner.css" />');
	} else if (getProfileCompany() != "") {
		document.write('<link rel="stylesheet" type="text/css" href="/static/style/consumer/merchant.css" />');
	} else if (isConsumer()) {
		document.write('<link rel="stylesheet" type="text/css" href="/static/style/consumer/neighbor.css" />');
	}
}

function writeNeighborStyle(id) {
    if (id && getProfileUserId() == id) {
        document.write('<style type="text/css"> .profileNotOwner { display: none; }</style>');
    }
}

function fillPhone()
{
  s = getSessionPhoneNumber();
  if ( s ) {
    updateNodeAttributes('codeBox', {'value': s} );
  }
}


function isLoggedIn() {
    return getSessionUserName() ? true : false;
}

function isForumAdmin() {
    return gClearSession["fa"] ? true : false;
    
}

function isForumModerator (){
    return gClearSession["fm"] ? true: false;
}

function isAdmin() {
    return gClearSession["fa"] ? true : false;
}

function isModerator (){
    return gClearSession["fm"] ? true: false;
}

function isConsumer (){
    return (getProfileCompany()=="") ? true: false;
}


function writeForumStyle(which) {
	document.write('<link rel="stylesheet" type="text/css" href="/static/css/consumer/forum/' + which +'.css">');
}

function showPostsByOwner () {
    // expecting an array or null
    posts = eval(gClearSession["fo"]);
    if (posts) {
        for (var i = 0; i < posts.length; i++) {
            var elt = $('post-' + posts[i]);
            if (elt) {
                showElement(elt);
            }
        }
    }
}
function toggleForum() {
    alert("toggleForum deprecated")
    // if (!isLoggedIn()) {
    //     writeForumStyle('unregistered');
    // } else {
    //     writeForumStyle('registered')
    // }
    // if (isForumAdmin()) {
    //     writeForumStyle('admin');
    // } else if (isForumModerator()) {
    //     writeForumStyle('moderator');
    // }
    // showPostsByOwner();
}

function getProfileInbox() {
	inbox =  gClearSession["in"];
	if (!inbox) {
		inbox = new Array();
		gClearSession["in"] = inbox;
	}
	jslog('debug', 'getClearSessionCookie', inbox);
	return inbox;
}

function setProfileInbox(rowid,msgstatus) {
    id= rowid + '_' + msgstatus;
    if (!gClearSession["in"]) {
       gClearSession["in"] = new Array();
    }
    gClearSession["in"].push(id);
	updateClearSessionCookie();
}

function createNudgeCookie(cnt){
	createCookie('nudge', cnt, 1)
}

function nudgeCount(){
    return readCookie('nudge');
}

function createDashboardNudgeCookie(data){
	//overwrites nudge cookie
	// if you see this then you're a logged in person. It doesn't matter.
	// expires after 1 days
	createCookie('nudge',  data, 1);
}

