/*
 _   _  ____  __  __  __    ____  ____    __    ___
( )_( )(_  _)(  \/  )(  )  ( ___)(  _ \  /__\  / __)
 ) _ (   )(   )    (  )(__  )__)  )   / /(__)\( (_-.
(_) (_) (__) (_/\/\_)(____)(__)  (_)\_)(__)(__)\___/

   HTML Fragments
   By Nike in 2009
 */

/* Creates a dom object, based on an html fragment from a template. */
/* In the template, all elements having the class given in convclass are considered dynamic. */
/* Therefore, a reference to their dom object can be found in the property Hash 'domrefs'. */
/* The keys of this hash are the objects ids in the template.*/
/* These ids of the new objects are sufixed with a random number found in the property 'sufix' */


/* if url is null, get then template with templateid is fetch directly from document  */
/* if url is not empty, template is ajaxed and cached as templateid */
var htmlfrag = new Class({
  initialize: function(templateid,templateurl,convclass){
    this.sufix='_'+Math.random().toString().substring(2,11);
    this.templateid=templateid;
    this.templateurl=templateurl;
    this.convclass=convclass;
    this.domrefs = new Hash();
    this.domnode=null;
    if(templateurl!=''){
      if(!$(templateid)) { this.update_cache(); }
      else this._clonefrag();
    }
    else this._clonefrag();
  },

  _clonefrag: function() {
    //we'll remove the ids ourself, while scanning, because we first use them as hash keys.

    this.domnode=$(this.templateid).clone(true,true);
    this.domnode.set('id',this.templateid+this.sufix); // Quickly, because we can have a race condition here !
    this.domnode.setStyle('display','block');
    this.domnode.getElements('.'+this.convclass).each(function(obj){
      this.domrefs[obj.id]=obj;
      obj.set('id',obj.id+this.sufix);
      obj.removeClass(this.convclass);
    }.bind(this));
    //alert('template '+this.templateid+' ready');
  },

  update_cache: function() {
    var cache=new Element('div',{'id':this.templateid,'style':'display:none;'});
    cache.inject(document.body);
    //document.body.setStyle('cursor','progress'); //crashes ie6
    this.templaterequest=new Request.HTML({'async':false,
      'onSuccess':function(responseTree, responseElements, responseHTML, responseJavaScript){
        cache.set('html',responseHTML);
        //document.body.setStyle('cursor','default');
        this._clonefrag();
      }.bind(this),
      'onFailure':function(){
        alert('Could not fetch a template for '+this.templateid/'\nPlease advice the sys-admin!');
        this.domnode=null;
      }.bind(this)
    }).get(this.templateurl+'?rnd='+Math.random());
  }
});



