dojo.require('dojo.storage.*');

var cache_id = AGCookie.getCookieValue('mc_s','sid');

function getCurrentTimeStamp()
{
	var date = new Date();
	return date.getTime();
}

function get_display_personalization()
{
	var product = webvars['prodnum'] || webvars['product'];
	var path = webvars['path'];
	return PersData.get(product, path).data;
}

function set_display_personalization(data)
{
	var product = webvars['prodnum'];
	var path = webvars['path'];
	PersData.store(product, path, data);
}

function delete_display_personalization()
{
	var product = webvars['prodnum'];
	var path = webvars['path'];
	PersData.remove(product, path);
}

function PersDataItem(sid, product, path, data) {
	this.sid = sid;
	this.data = data;
	this.product = product;
	this.path = path;
	this.last_updated = getCurrentTimeStamp();
}

var PersData = {
	sid: cache_id,
	key: "perscache_" + cache_id,
	asset_key: "user_assets_" + cache_id,
	personalizations: new Object(),
	assets: new Object(),
	_initialized: false,

	initialize: function(){
		pdata_debug('starting PersData.initialize');
		this.personalizations = dojo.storage.get(this.key);
		if (!this.personalizations){
			this.personalizations = new Object();
        }

		this.assets = dojo.storage.get(this.asset_key);
		if (!this.assets)
		{
			this.assets = new Object();
		}

        this.cleanup();
        
		this._initialized = true;
		pdata_debug('finished PersData.initialize');
	},
	
	store_assets: function(type, data)
	{
		var asset_data = {'type': type, 'data': data, 'last_updated': getCurrentTimeStamp()};
		this.assets[type] = asset_data;
		try{
			dojo.storage.put(this.asset_key, this.assets, function(status, key, message){});	
		}catch(exp){}
	},
	
	get_assets: function(type)
	{
		try{
			var data = this.assets[type]
			if (getCurrentTimeStamp() > data.last_updated + 86400000) // more than a day clear the data and return null
			{
				//this.remove_assets(type)
				return new Object();
			} else {
				return data.data;
			}
		} catch(e){
				return new Object();
		}
	},
	
	store: function(product, path, data)
	{
		var this_key = product + "_" + path;
		this.personalizations[this_key] = new PersDataItem(this.sid, product, path, data);
		try{
			dojo.storage.put(this.key, this.personalizations, function(status, key, message){});	
		}catch(exp){}
	},
	
	get: function(product, path)
	{
		var this_key = product + "_" + path;
		try{
			var data = this.personalizations[this_key]
			if (getCurrentTimeStamp() > data.last_updated + 86400000) // more than a day clear the data and return null
			{
				this.remove(product, path)
				return new PersDataItem(this.sid, product, path, new Object())
			} else {
				return data;
			}
		} catch(e){
				return new PersDataItem(this.sid, product, path, "")
		}
	},
	
	remove: function(product, path)
	{
		var this_key = product + "_" + path;
		delete(this.personalizations[this_key]);
		try{
			dojo.storage.put(this.key, this.personalizations, function(status, key, message){});	
		}catch(exp){}
	},

	remove_assets: function(type)
	{
		delete(this.assets[type]);
		try{
			dojo.storage.put(this.asset_key, this.assets, function(status, key, message){});	
		}catch(exp){}
	},
	
	clear: function()
	{
		try{
			dojo.storage.put(this.key, new Object(), function(status, key, message){});	
		} catch(e){}
	}, 
	
	cleanup: function()
	{
		var updated = false;
		// first we remove any stored caches for other sessions
		var keys = dojo.storage.getKeys();
		for (var i = 0; i < keys.length; i++)
		{
			if ( (keys[i].indexOf('perscache_') == 0 && keys[i] != this.key) ||
				(keys[i].indexOf('user_assets_') == 0 && keys[i] != this.asset_key) )
			{
				try {
					dojo.storage.remove(keys[i]);
				} catch(e) {
					// flash storage doesn't support remove?
					dojo.storage.put(keys[i], new Object(), function(status, key, message){});
				}
			}
		}
		
		// next we remove any outdated PersDataItem objects
		for (key in this.personalizations)
		{
			if (getCurrentTimeStamp() > this.personalizations[key].last_updated + 86400000)
			{
				delete(this.personalizations[key]);
				updated = true;
			}
		}
		
		if (updated)
		{
			try{
				dojo.storage.put(this.key, this.personalizations, function(status, key, message){});	
			}catch(exp){}
		}

		updated = false;
		for (key in this.assets)
		{
			if (getCurrentTimeStamp() > this.assets[key].last_updated + 86400000)
			{
				delete(this.assets[key]);
				updated = true;
			}
		}
		
		if (updated)
		{
			try{
				dojo.storage.put(this.asset_key, this.assets, function(status, key, message){});	
			}catch(exp){}
		}
	}
}

if (dojo.storage.manager.isInitialized() == false)
{
	dojo.event.connect(dojo.storage.manager, "loaded", PersData, PersData.initialize);
} else {
	dojo.event.connect(dojo, "loaded", PersData, PersData.initialize);
}

var UserAssets = null;
var DeletedUserAssets = null;

var AssetStorage = {
	store: function()
	{
		if (UserAssets == null)
			return;
		
		var url_to_open = ahost+'/assets/flash_helper.pd?action=create&type=MG&data=' + encodeURIComponent(UserAssets);

		var send_method = 'GET';
		var allow_async = false;
		var show_waiting = false;
		var req = new Requester(url_to_open, send_method, allow_async, show_waiting);
		req.onsuccess = AssetStorage.onsuccess;
		req.onerror = AssetStorage.onerror;
		req.sendRequest();		
	},
	
	remove: function()
	{
		if (DeletedUserAssets == null)
			return;
		
		var url_to_open = ahost+'/assets/flash_helper.pd?action=delete&id=' + encodeURIComponent(DeletedUserAssets);

		var send_method = 'GET';
		var allow_async = false;
		var show_waiting = false;
		var req = new Requester(url_to_open, send_method, allow_async, show_waiting);
		req.onsuccess = AssetStorage.onsuccess;
		req.onerror = AssetStorage.onerror;
		req.sendRequest();
		DeletedUserAssets = null;
	},

	onerror: function(){
		// nothing to be done here
	},
	
	onsuccess: function(){
		// nothing to be done here
	}
}

function pdata_tools()
{
	var button = document.createElement('button');
	button.onclick = function(){alert(dojo.storage.getKeys())};
	document.body.appendChild(button);
	button.appendChild(document.createTextNode('storage keys'));

	var button2 = document.createElement('button');
	button2.onclick = function(){dojo.storage.clear()};
	document.body.appendChild(button2);
	button2.appendChild(document.createTextNode('clear storage'));

}
//dojo.addOnLoad(pdata_tools);

function pdata_debug(str)
{
	var debug = webvars['pdebug']
	if (!debug)
		return;
	str = getCurrentTimeStamp() + ": " + str;
	try {
		if (console && console.log)
		{
			console.log(str);
		} else {
			var par = document.createElement('P');
			document.body.appendChild(par);
			par.appendChild(document.createTextNode(str));
		}
	} catch (e) {
		try{
			var par = document.createElement('P');
			document.body.appendChild(par);
			par.appendChild(document.createTextNode(str));
		} catch (e){}
	}
}

dojo.addOnUnload(AssetStorage.store);
dojo.addOnUnload(AssetStorage.remove);

function remove_storage()
{
	AssetStorage.remove();
}

function init_remove_storage()
{
	if (dojo.byId('agi-signout'))
		dojo.event.connect('before', dojo.byId('agi-signout'), 'onclick', 'remove_storage');
}

dojo.addOnLoad(init_remove_storage);

