/**
 * A3non Sandbox - Request.SandboxContent
 * 
 * @author Andi Dittrich <andi.dittrich@a3non.org>
 * @url http://www.a3non.org
 * @license Creative Commons BY-NC, Creative Commons Namensnennung-Keine kommerzielle Nutzung 3.0 Deutschland Lizenz, 
 * @license http://creativecommons.org/licenses/by-nc/3.0/de/
 * @version 1.3
 */
Sandbox.Net.Request.SandboxContent = new Class({
	Extends: Request,

	options: {
		secure: true,
		evalScripts: true
	},

	destinations: null,

	initialize: function(destinations, options){
		this.parent(options);
		this.destinations = destinations;
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);
		var dynJS = "";
		var THIS = this;

		
		if (this.response.json){
			// create new hash
			var containerContent = new Hash(this.response.json.container);
			
			// set title
			$try(function(){
				document.title = containerContent.title;
			});
			
			// strip js
			containerContent.each(function(value, key){
				containerContent.set(key, value.stripScripts(
					function(script){
						dynJS += script;
					}.bind(this))
				);			
			}.bind(this));
			
			// update container
			this.destinations.each(function(value, key){
				// if container updated
				if (containerContent.get(key) && containerContent.get(key).length > 0){
					value.set('html', containerContent.get(key));
				}
			});
	
			// load additional js/css files
			var myAsset = new Sandbox.Util.Asset({
				js: this.response.json.extern.js,
				css: this.response.json.extern.css
			});
			myAsset.addEvent('complete', function(){
				// direct exec scripts
				if (this.options.evalScripts) {
					$exec(dynJS);
					$exec(this.response.json.js);
				}
			
				// success
				this.onSuccess(this.response.json);	
			}.bind(this));
			myAsset.load();
		
		}else{
			this.onSuccess(this.response.json);
		}
		
	}
	
});