/*
Script: Request.DynHTML.js
  Extends the Request.HTML Class with additional methods for managing scripted html responses. Overrides some methods
 
License:
  MIT-style license.
*/
 
Request.DynHTML = new Class({
 
  Extends: Request.HTML,
 
  options: {
	//evaluates external scripts
	loadExternalScripts:true
  },
  
  //   /<script.*?(?:src="([^"]*)")?>(.*?)<\/script>/g
  success: function(text){
    var options = this.options, response = this.response;
	response.html = text.stripScripts(false);
	var parser = /<script.*?(?:src="([^"]*)")?>(.*?)<\/script>/g ;
    var temp = this.processHTML(response.html);
	var matches=[];
	var oneliner=text.replace(/\n/g,"");
	matches = parser.exec(oneliner);
	var tmp=[];
	response.javascript="";
	var i=0;
	while(matches){
		if (matches[1]) {
			tmp.push(matches[1]);
		}
		if (matches[2]) {
			response.javascript+=matches[2]+"\n";
		}
		matches = parser.exec(oneliner);
	}
 
    response.tree = temp.childNodes;
    response.elements = temp.getElements('*');
    if (options.update) {
		$(options.update).empty().set('html', response.html);
	}
	else 
		if (options.append) {
			$(options.append).adopt(temp.getChildren());
		}
	if(options.evalScripts){
		if(options.loadExternalScripts){
			tmp.each(function(item,index,array){
				if(item && !array.contains(item,index+1)){
					new Request({method:'get',url:matches[1],onSuccess:function(text,xml){
						$exec(text);
					}}).send();
				}
			});
		}
		$exec(response.javascript);
	}
    this.onSuccess(response.tree, response.elements, response.html, response.javascript);
  }
 
});
 
Element.Properties.load = {
 
  set: function(options){
    var load = this.retrieve('load');
    if (load) {
		load.cancel();
	}
    return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get',loadExternalScripts:true}, options));
  },
 
  get: function(options){
    if (options || ! this.retrieve('load')){
      if (options || !this.retrieve('load:options')) {
	  	this.set('load', options);
	  }
      this.store('load', new Request.DynHTML(this.retrieve('load:options')));
    }
    return this.retrieve('load');
  }
 
};
 
Element.implement({
 
  load: function(){
    this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type}));
    return this;
  }
 
});
