/**
 * VisualDNA API
 *
 * @author Imagini 
 */

var VDNA_urls = { 
	live: "http://my.visualdna.com",
	staging: "http://my.staging.youniverse.com",
	deploytest: "http://my.deploytest.youniverse.com",
	vm: "http://www.my.vm.visualdna.com"
}
var VDNA_url = VDNA_urls.live;

var VDNA_cookieName = "vdnaUserId";
var VDNA_permCookieName = "vdnaUserPermission";


var xmlhttp;
var VDNA_userPermission;
var VDNA_lastUserResponse;
var VDNA_userProfile;
var VDNA_userFeedback;
var VDNA_userID;
/**
 * Fetches UserService id for current user
 *
 */
function VDNA_GetUserID()
{
	if (VDNA_clientHasPermission()) 
	{
		if (VDNA_LocalCookieExists(VDNA_cookieName)) 
		{
			VDNA_userID = VDNA_GetInfoFromCookie(VDNA_cookieName);
			return VDNA_userID;
		}
		else 
		{
			if (VDNA_RequestPeriodOver()) 
			{
				VDNA_GetUserIDRemote();
			}
			else 
			{
				return 0;
			}
		}
	}
}

/**
 * Determines if a client has access to a user's VDNA data
 *
 */
function VDNA_clientHasPermission()
{
	return true;
}

/*
* Method called by VDNA flash app to determine the current domain name (utility function)
*
*/
function VDNA_getCookieDomain()
{
	var thisDomain = document.domain;
	var domainArr = thisDomain.split(".");
	thisDomain = '.' + domainArr[domainArr.length-2] + "." + domainArr[domainArr.length-1];
	
	return thisDomain;
}

/*
* Verifies if local cookie exists or not
*
*/
function VDNA_LocalCookieExists(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1)
		{
			return true;
		}
	}
	return false;
}

/*
* Parse local cookie data
*
*/
function VDNA_GetInfoFromCookie(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1)
		{
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) 
			{
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return false;
}

/*
* Write data to cookie
*/
function VDNA_SetUpInfoCookie(name, infoStr)
{
	var availability = 1000 * 60 * 60 * 24 * 356; // one year
	if (name == 'vdnaTimestamp')
	{
		infoStr = Math.round(new Date().getTime() / 1000);
	}
	
	if (name == VDNA_cookieName)
	{
		if (infoStr == 0)
			return false;
		availability = 1000 * 60 * 60 * 24; // one day
	}	
	
	//cookie val: timestamp;
	var thisDomain = VDNA_getCookieDomain();

	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );	
	var expires_date = new Date( today.getTime() + availability ); // one year
	document.cookie = name + "=" + escape(infoStr) +
					  ";expires=" + expires_date.toGMTString() +
					  ";path=/" +
					  ";domain=" + thisDomain;
}	

/*
* Write data to cookie
*/
function VDNA_DeleteLocalCookie(name)
{
	var thisDomain = VDNA_getCookieDomain();
	var deleteTime = 'Thu, 01-Jan-1970 00:00:01 GMT';
	document.cookie = name + "=0" + 
					  ";expires=" + deleteTime +
					  ";path=/" +
					  ";domain=" + thisDomain;
}	

/*
* Verifies that the time period from the former request is over 24h
*
*/
function VDNA_RequestPeriodOver()
{
	var cookieTimestamp = VDNA_GetInfoFromCookie('vdnaTimestamp');
	if (!cookieTimestamp) 
	{
		return true;
	}
	
	var timestamp = Math.round(new Date().getTime() / 1000);
	if (timestamp - cookieTimestamp > 60*60*24) // period passed is biger than 24h we try again :)
	{
		return true;
	}
	return false;	
}

/*
* Return user id from remote cookie, if available
*
*/
function VDNA_GetUserIDRemote()
{
	if ( VDNA_userID === false || VDNA_userID == undefined || VDNA_userID == 'false')
	{
		var headID = document.getElementsByTagName("head")[0];
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = VDNA_url + '/api/getremotecookie'; 
		headID.appendChild(newScript);
	
		setTimeout('VDNA_GetUserIDRemote()', 300);
	}
	else
	{
		if (typeof(VDNA_config) == "undefined")
		{
			var VDNA_config = { userID: "0" };
		}
		else
		{
			VDNA_config.userID = VDNA_userID;
		}
		
		VDNA_SetUpInfoCookie('vdnaTimestamp', '');
		VDNA_SetUpInfoCookie(VDNA_cookieName, VDNA_userID);
		VDNA_SetUpInfoCookie(VDNA_permCookieName, VDNA_userPermission);
	}
}



/*
* Returns last response for a given module
* 
*/
function VDNA_GetLastResponse(moduleID, callback)
{
	if (callback == null)
		callback = 'VDNA_processLastUserResponse';
	
	var url = VDNA_url + '/api/getlastresponse?user_id=' + VDNA_config.userID + '&module_id=' + moduleID + '&api_key=' + VDNA_config.apiKey + '&key_salt=' + VDNA_config.salt + '&callback=' + callback;

	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = url; 
	headID.appendChild(newScript);
}

/*
* Returns user profile
* 
*/
function VDNA_GetUserProfile(callback)
{
	if (callback == null)
		callback = 'VDNA_processUserProfile';
	var url = VDNA_url + '/api/getuserprofile?user_id=' + VDNA_config.userID + '&api_key=' + VDNA_config.apiKey + '&key_salt=' + VDNA_config.salt + '&callback=' + callback;

	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = url; 
	headID.appendChild(newScript);
}

/*
* Returns response feedback data
* 
*/
function VDNA_GetUserFeedback(responseID, schema_id, callback)
{
	if (callback == null)
		callback = 'VDNA_processUserFeedback';
	var url = VDNA_url + '/api/getuserfeedback?response_id=' + responseID + '&api_key=' + VDNA_config.apiKey + '&key_salt=' + VDNA_config.salt + '&schema_id=' + schema_id + '&callback=' + callback;

	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = url; 
	headID.appendChild(newScript);
}

/*
*  Write user id to cookie, function called from Flash
* 
*/
function VDNA_FlashGetUserID(user_id)
{
	// set cookie on local domain
	VDNA_SetUpInfoCookie(VDNA_cookieName, user_id);

	// adding userid to the config var
	VDNA_config.userID = user_id
	VDNA_userID = user_id;

	var scriptUrl = VDNA_url + '/api/setremotecookie?user_id=' + user_id;
	// set cookie on remote domain (my.visualdna.com) 
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = scriptUrl;
	headID.appendChild(newScript);
}	

/*
*  function for unsetting "Save my VisualDNA"
* 
*/
function VDNA_FlashSetVDNA(bool)
{
	if (bool == 'false') 
	{
		var confText = 'Saving your VisualDNA is recommended, as it allows you to have a more personalised experience on' +
		' this site. We respect your privacy, and your VisualDNA is under your total control at all times -' +
		' simply go to my.visualdna.com to manage your VisualDNA.' +
		'\n\n Are you sure you want to change this setting?';
		var conf = confirm(confText);
		
		if (conf) 
		{
			VDNA_FlashGetUserPerm('false');
			VDNA_DeleteCookie();
			return 'false';
		}
		
		return 'true';
	}
	else 
	{
		if (bool == 'true') 
		{
			VDNA_FlashGetUserPerm('true');
			return 'true';
		}
	}
}	

/*
*  Delete user id cookie and all the association between him and his responses
* 
*/
function VDNA_DeleteCookie()
{
	// delete cookie on local domain
	VDNA_DeleteLocalCookie(VDNA_cookieName);

	// delete cookie on remote domain(my.visualdna.com) an remove associations 
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = VDNA_url + '/api/deletecookie?api_key=' + VDNA_config.apiKey + '&key_salt=' + VDNA_config.salt; 
	headID.appendChild(newScript);
}	

/*
* Get user id from cookie, function called from Flash
* 
*/
function VDNA_FlashSendUserID()
{
	VDNA_userID = VDNA_GetInfoFromCookie(VDNA_cookieName);
	return VDNA_userID;
}	

/*
*  Write user permission to cookie, function called from Flash or JS
* 
*/
function VDNA_FlashGetUserPerm(bool)
{
	// set cookie on local domain
	VDNA_SetUpInfoCookie(VDNA_permCookieName, bool);

	// set cookie on remote domain (my.visualdna.com) 
	var headID = document.getElementsByTagName("head")[0];
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = VDNA_url + '/api/setremotecookie?permission=' + bool; 
	headID.appendChild(newScript);
}	

/*
* Get user permission from cookie, function called from Flash or JS
* 
*/
function VDNA_FlashSendUserPerm()
{
	VDNA_userPerm = VDNA_GetInfoFromCookie(VDNA_permCookieName);
	return VDNA_userPerm;
}	
