var Browser=new function(){

 this.SupportsDOM=document.getElementById?true:false;
 this.userAgentString=navigator.userAgent.toLowerCase();


 this.Is=function(val){
  return this.userAgentString.indexOf(val)+1;
 }

 if(this.Is("firefox")){

  this.Name="Firefox";
  var is=this.Is("firefox")+7;
  var end=this.userAgentString.indexOf(" ",is);
  if(end==-1){
   end=this.userAgentString.length;
  }
  this.Version=this.userAgentString.substring(is,end);

 }else if(navigator.appName=="Netscape"){

  this.Name="Netscape";
  this.Version=this.userAgentString.charAt(8);

 }else if(document.all&&this.Is("msie")){

  this.Name="Internet Explorer";
  var is=this.Is("msie")+4;
  var end=this.userAgentString.indexOf(";",is);
  if(end==-1){
   end=this.userAgentString.length;
  }
  this.Version=this.userAgentString.substring(is,end);

 }else if(window.opera&&this.Is("opera")){

  this.Name="Opera";
  var is=this.Is("opera")+5;
  var end=this.userAgentString.indexOf(" ",is);
  if(end==-1){
   end=this.userAgentString.length;
  }
  this.Version=this.userAgentString.substring(is,end);

 }

 if(this.Is("linux")){
  this.OS="Linux";
 }else if(this.Is("x11")){
  this.OS="Unix";
 }else if(this.Is("mac")){
  this.OS="Mac";
 }else if(this.Is("win")){
  this.OS="Windows";
 }

};

function cCheckbox(){

 var self=this;
 //this.cssClass;
 //this.hoverCssClass;
 //this.selectedCssClass;

 this.createInstance=function(val){

  var main=document.createElement("div");
  main.selected=false;
  main.disabled=false;
  main.className=self.cssClass;

  var checkboxInput=document.createElement("input");
  checkboxInput.setAttribute("type","hidden");
  if(self.formName!=null){
   checkboxInput.setAttribute("name",self.formName);
  }
  checkboxInput.value="";
  main.resultBox=main.appendChild(checkboxInput);
  checkboxInput=null;

  if(typeof(this.onFocus)=="function"){
   main.onfocus=this.onFocus;
  }

  if(typeof(this.onBlur)=="function"){
   main.onblur=this.onBlur;
  }

  main.Disable=function(){
   this.disabled=true;
  };

  main.Enable=function(){
   this.disabled=false;
  };

  main.Select=function(rf){
   if(!this.selected){
    this.selected=true;
    this.className=self.selectedCssClass;
    this.resultBox.value=val;
    if(!rf&&typeof(self.onSelect)=="function"){
     self.onSelect();
    }
   }
  };

  main.DeSelect=function(rf){
   if(this.selected){
    this.className=self.hoverCssClass;
    this.selected=false;
    this.resultBox.value="";
    if(!rf&&typeof(self.onDeSelect)=="function"){
     self.onDeSelect();
    }
   }
  };

  main.onclick=function(){
   if(!this.disabled){
    if(this.selected){
     this.DeSelect();
    }else{
     this.Select();
    }
   }
  };

  main.onmouseover=function(){
   if(!this.disabled){
    if(!this.selected){
     this.className=self.hoverCssClass;
    }
   }
  };

  main.onmouseout=function(){
   if(!this.disabled){
    if(this.selected){
     this.className=self.selectedCssClass;
    }else{
     this.className=self.cssClass;
    }
   }
  };

  main.Destroy=function(){

   System.Element.Destroy(this);
   this.resultBox=null;
   this.Select=null;
   this.DeSelect=null;
   this.Enable=null;
   this.Disable=null;
   this.Destroy=null;
   self=null;
   main=null;

  };

  return main;

 };

}

function cContext(){

 var self=this;
 var contextParsed=null;
 var subArr=[];			//array with all sub's for parsing
 var openedArr=[];		//array with sub boxes
 var selectedItem=null;
 var openedSubArr=[];		//array with items that open sub boxes
 var subArrNoPop=[];		//array with all sub's for parsing, always open
 var cachedBreakItems=[];
 var cachedItems=[];
 this.shadow=false;

 this.left=0;
 this.top=0;


 this.Destroy=function(){

  this.closeMenu();

  System.Event.DestroyHandler(this);

  this.contextFloat=null;
  selectedItem=null;

  if(document.body.EventHandler){
   document.body.EventHandler.DestroyGroup(this);
  }

  while(subArr.length>0){

   System.Element.Destroy(subArr[subArr.length-1]);
   subArr[subArr.length-1]=null;
   subArr.pop();

  }
  subArr=null;

  while(openedArr.length>0){

   System.Element.Destroy(openedArr[openedArr.length-1]);
   openedArr[openedArr.length-1]=null;
   openedArr.pop();

  }
  openedArr=null;

  while(openedSubArr.length>0){

   System.Element.Destroy(openedSubArr[openedSubArr.length-1]);
   openedSubArr[openedSubArr.length-1]=null;
   openedSubArr.pop();

  }
  openedSubArr=null;

  while(subArrNoPop.length>0){

   System.Element.Destroy(subArrNoPop[subArrNoPop.length-1]);
   subArrNoPop[subArrNoPop.length-1]=null;
   subArrNoPop.pop();

  }
  subArrNoPop=null;


  while(cachedBreakItems.length>0){
 
   cachedBreakItems[cachedBreakItems.length-1].Hide=null;
   cachedBreakItems[cachedBreakItems.length-1].UnHide=null;
   cachedBreakItems[cachedBreakItems.length-1].IsHidden=null;
   cachedBreakItems[cachedBreakItems.length-1]=null;
   cachedBreakItems.pop();

  }
  cachedBreakItems=null;


  while(cachedItems.length>0){

   System.Element.Destroy(cachedItems[cachedItems.length-1]);
   cachedItems[cachedItems.length-1].setText=null;
   cachedItems[cachedItems.length-1].getText=null;
   cachedItems[cachedItems.length-1].Disable=null;
   cachedItems[cachedItems.length-1].Enable=null;
   cachedItems[cachedItems.length-1].Hide=null;
   cachedItems[cachedItems.length-1].UnHide=null;
   cachedItems[cachedItems.length-1].IsHidden=null;
   cachedItems[cachedItems.length-1]=null;
   cachedItems.pop();

  }
  cachedItems=null;


  this.createInstance=null;
  this.closeMenu=null;
  this.parse=null;
  this.addItem=null;
  this.addBreak=null;
  this.Destroy=null;
  this.openSub=null;
  this.closeSub=null;
  this.AdjustToElementPosition=null;
  this.Hide=null;
  this.UnHide=null;
  this.show=null;

  self=null;

 }

 this.createInstance=function(){

  var contextFloat=document.createElement("div");
  System.Element.SetOpacity(contextFloat,90);
  contextFloat.style.position="absolute";
  contextFloat.style.display="none";
  contextFloat.style.left="0px";
  contextFloat.style.top="0px";
  contextFloat.className="context_box";
  subArr[subArr.length]=contextFloat;
  this.contextFloat=contextFloat;

  System.Event.CreateHandler(this).EnableListener("hide");
 };


 this.HasItems=false;


 this.closeMenu=function(){

  if(subArr){

   for(var i=openedArr.length-1;i>-1;i--){
    openedArr[i].style.display="none";
   }
   subArr[0].style.display="none";

   while(openedArr.length>0){

    openedArr[openedArr.length-1]=null;
    openedArr.pop();

   }

   while(openedSubArr.length>0){

    openedSubArr[openedSubArr.length-1].className="context_item_p";
    openedSubArr[openedSubArr.length-1].childNodes[0].className="context_item_l";
    openedSubArr[openedSubArr.length-1].childNodes[1].className="context_item";
    openedSubArr[openedSubArr.length-1]=null;
    openedSubArr.pop();

   }

   this.EventHandler.Listeners.hide.Fire(null,this);

  }

 };


 this.parse=function(el){

  this.contextParsed=document.body.appendChild(this.contextFloat);

  /* close the menu when asked for */
  var closeMenuf=function(e){

   e=e||window.event;
   var target=e.srcElement||e.target;

   if(self.contextParsed.contains(target)){
    return;
   }

   for(var i=openedArr.length-1;i>-1;i--){
    if(openedArr[i].contains(target)){
     return;
    }
   }

   self.closeMenu();
  };

  System.Event.CreateHandler(document.body).EnableListener("mousedown").CreateGroup(this).Append(closeMenuf);

  if(el){
   System.Event.CreateHandler(el).EnableListener("mousedown").Append(closeMenuf);
  }

  for(var i=0;i<subArrNoPop.length;i++){
   document.body.appendChild(subArrNoPop[i]);
  }
 }


 this.addBreak=function(){
  var contextFloatItem=document.createElement("div");
  contextFloatItem.className="context_break_p";
  contextFloatItem.innerHTML="<div class='context_break_l'></div><div class='context_break'></div>";

  contextFloatItem.IsHidden=false;

  contextFloatItem.Hide=function(){
   if(!this.IsHidden){
    this.IsHidden=true;
    this.style.display="none";
   }
  };

  contextFloatItem.UnHide=function(){
   if(this.IsHidden){
    this.IsHidden=false;
    this.style.display="";
   }
  };

  return cachedBreakItems[cachedBreakItems.length]=this.contextFloat.appendChild(contextFloatItem);
 }


 this.addItem=function(img,linkn,function_ref,st){
  this.HasItems=true;

  var contextFloatItem=document.createElement("div");
  contextFloatItem.className="context_item_p";


  if(st!=null){
   var cs="<div class='context_item' style='"+st+"'>"+linkn+"</div>";
  }else{
   var cs="<div class='context_item'>"+linkn+"</div>";
  }
  if(img!=""&&img!=null){
   contextFloatItem.innerHTML="<div class='context_item_l'><img src='"+img+"' alt='' /></div>"+cs;
  }else{
   contextFloatItem.innerHTML="<div class='context_item_l'></div>"+cs;
  }

  contextFloatItem.style.borderBottom="none";

  contextFloatItem.IsDisabled=true;
  contextFloatItem.IsHidden=false;

  contextFloatItem.setText=function(val){
   this.childNodes[1].innerHTML=val;
  }

  contextFloatItem.getText=function(){
   return this.childNodes[1].innerHTML;
  }

  contextFloatItem.Hide=function(){
   if(!this.IsHidden){
    this.IsHidden=true;
    this.style.display="none";
   }
  }

  contextFloatItem.UnHide=function(){
   if(this.IsHidden){
    this.IsHidden=false;
    this.style.display="";
   }
  }

  contextFloatItem.Disable=function(){
   if(!this.IsDisabled){
    this.IsDisabled=true;

    System.Element.SetOpacity(this,30);

    if(function_ref){
     this.EventHandler.DestroyListener("click");
    }
    this.onmouseover=null;
    this.onmouseout=null;
    this.onclick=null;
   }
  }

  contextFloatItem.Enable=function(){
   if(this.IsDisabled){
    this.IsDisabled=false;

    System.Element.SetOpacity(this,100);

    System.Event.CreateHandler(this);

    if(function_ref){
     this.EventHandler.EnableListener("click",self).Append(function_ref);
    }
    this.EventHandler.EnableListener("click",self).Append(function(){this.closeMenu();});


    this.onmouseover=function(){
     var subRemove=false;
     var popCount=0;
     thisParent=this.parentNode;
     for(var i=0;i<openedSubArr.length;i++){
      if(subRemove){
       openedSubArr[i].className="context_item_p";
       openedSubArr[i].childNodes[0].className="context_item_l";
       openedSubArr[i].childNodes[1].className="context_item";
       popCount++;
      }else if(openedSubArr[i].parentNode==thisParent){
       i--;
       subRemove=true;
      }
     }
     for(i=0;i<popCount;i++){
      openedSubArr.pop();
     }

     for(var i=openedArr.length-1;i>-1;i--){
      if(thisParent!=openedArr[i]){
       openedArr[i].style.display="none";
       openedArr.pop();
      }else{
       break;
      }
     }
     this.className="context_item_p_mouseover";
     this.childNodes[0].className="context_item_l_mouseover";
     this.childNodes[1].className="context_item_mouseover";
    }

    this.onmouseout=function(){
     this.className="context_item_p";
     this.childNodes[0].className="context_item_l";
     this.childNodes[1].className="context_item";
    }

    this.onclick=function(){
     this.className="context_item_p";
     this.childNodes[0].className="context_item_l";
     this.childNodes[1].className="context_item";
    }
   }
  }

  contextFloatItem.Enable();

  return cachedItems[cachedItems.length]=this.contextFloat.appendChild(contextFloatItem);
 }


 this.openSub=function(contextFloatItem,st){
  var contextFloat=document.createElement("div");

  System.Element.SetOpacity(contextFloat,90);
  contextFloat.className="context_box";

  if(st!=null){
   if(Browser.Name=="Internet Explorer"){
    contextFloat.style.setAttribute("cssText",st);	//goddamnit IE is stupid
   }else{
    contextFloat.setAttribute("style",st);
   }
  }

  contextFloat.style.display="none";
  contextFloat.style.position="absolute";
  contextFloat.style.left="0px";
  contextFloat.style.top="0px";

  contextFloatItem.onclick=function(e){
   this.contextFloat=contextFloat;
   thisParent=this.parentNode;
   for(var i=openedArr.length-1;i>-1;i--){
    if(thisParent!=openedArr[i]){
     openedArr[i].style.display="none";
    }else{
     break;
    }
   }
   openedArr[openedArr.length]=this.contextFloat;
   this.contextFloat.style.left=System.Element.GetXPosition(this)+this.offsetWidth+1+"px";
   this.contextFloat.style.top=System.Element.GetYPosition(this)+2+"px";
   this.contextFloat.style.display="";
  }


  //disable onmouseout handler that was enabled in addItem
  contextFloatItem.onmouseout=function(){
  };


  contextFloatItem.onmouseover=function(){
   var subRemove=false;
   var popCount=0;
   for(var i=0;i<openedSubArr.length;i++){
    if(subRemove){
     openedSubArr[i].className="context_item_p";
     openedSubArr[i].childNodes[0].className="context_item_l";
     openedSubArr[i].childNodes[1].className="context_item";
     popCount++;
    }else if(openedSubArr[i].parentNode==this.parentNode){
     i--;
     subRemove=true;
    }
   }
   for(i=0;i<popCount;i++){
    openedSubArr.pop();
   }
   openedSubArr[openedSubArr.length]=this;
   this.className="context_item_p_mouseover";
   this.childNodes[0].className="context_item_l_mouseover";
   this.childNodes[1].className="context_item_mouseover";
   this.contextFloat=contextFloat;
   thisParent=this.parentNode;
   for(var i=openedArr.length-1;i>-1;i--){
    if(thisParent!=openedArr[i]){
     openedArr[i].style.display="none";
     openedArr.pop();
    }else{
     break;
    }
   }
   openedArr[openedArr.length]=this.contextFloat;
   this.contextFloat.style.left=System.Element.GetXPosition(this)+this.offsetWidth+1+"px";
   this.contextFloat.style.top=System.Element.GetYPosition(this)+2+"px";
   this.contextFloat.style.display="";
  }

  subArr[subArr.length]=contextFloat;
  this.contextFloat=contextFloat;

  return contextFloatItem;
 }


 this.closeSub=function(){
  del_item=subArr.pop();

  //document.body.appendChild(self.contextFloat);	replaced with below (will be parsed with this.parse()), because IE might crash while doing this
  subArrNoPop[subArrNoPop.length]=this.contextFloat;

  this.contextFloat=subArr[subArr.length-1];
 }

 this.ToElement=false;

 this.AdjustToElementPosition=function(el,x,y){
  this.ToElement=true;
  if(this.contextParsed==null){
   this.parse();
  }

  if(isNaN(x)){
   x=0;
  }
  if(isNaN(y)){
   y=0;
  }

  this.contextParsed.style.left=System.Element.GetXPosition(el)+x+"px";
  this.contextParsed.style.top=System.Element.GetYPosition(el)+y+el.offsetHeight+"px";
 }


 this.UnHide=function(){
  if(this.contextParsed){
   this.contextParsed.style.display="block";
  }
 };


 this.Hide=function(){
  this.closeMenu();
 };


 this.IsHidden=function(){
  if(this.contextParsed){
   if(this.contextParsed.style.display=="block"){
    return false;
   }else{
    return true;
   }
  }
 };


 this.show=function(e){

  e=e||window.event;
  if(self.contextParsed==null){
   this.parse();
  }
  if(this.contextParsed!=null){
   if(arguments.length>1){
    this.argument=arguments[1];
    this.arguments=[];
    for(var i=1;i<arguments.length;i++){
     this.arguments[i-1]=arguments[i];
    }
   }else{
    this.argument=null;
    this.arguments=null;
   }

   this.UnHide();	//first unhide, so offsetHeight can be calced

   if(!this.ToElement){

    var Ymouse=get_mousePosition(e,"y");
    var Xmouse=get_mousePosition(e,"x");

    var winw=document.documentElement.offsetWidth;
    var winh=document.documentElement.offsetHeight;

    var hscrll=document.documentElement.scrollTop;
    var wscrll=document.documentElement.scrollLeft;

    elHeight=this.contextParsed.offsetHeight;
    elWidth=this.contextParsed.offsetWidth;

    var top=self.top;
    var left=self.left;

    if(winh+hscrll<Ymouse+hscrll+elHeight+top){
     top-=elHeight;
    }

    if(winw+wscrll<Xmouse+wscrll+elWidth+left){
     left-=elWidth;
    }

    this.contextParsed.style.position="absolute";
    this.contextParsed.style.top=(hscrll+Ymouse+top)+"px";
    this.contextParsed.style.left=(wscrll+Xmouse+left)+"px";
   }

  }
 }


}

function cDrag(){

 var self=this;

 var cDragItem=null;
 var OriginalDragItem=null;

 var cDrag_startX, cDrag_startY=null;

 var cDrag_startmouseX, cDrag_startmouseY;

 var cachedEventHandlers=[];
 var cachedElements=[];


 System.Event.CreateHandler(document.body);

 this.Destroy=function(){

  this.cancelDrag(true);

  OriginalDragItem=null;
  cDragItem=null;

  document.body.EventHandler.DestroyGroup(this);

  this.DragItem=null;
  this.cancelDrag=null;
  this.createFloatBox=null;
  this.createDropBox=null;
  this.createDragBox=null;


  while(cachedEventHandlers.length>0){

   cachedEventHandlers[cachedEventHandlers.length-1].DestroyGroup(this);
   cachedEventHandlers.pop();

  }
  cachedEventHandlers=null;


  while(cachedElements.length>0){

   System.Element.Destroy(cachedElements[cachedElements.length-1]);
   cachedElements[cachedElements.length-1]=null;
   cachedElements.pop();

  }
  cachedElements=null;


  self=null;

 };


 this.cancelDrag=function(disable){

  if(disable&&cDragItem){
   cDragItem.style.display='none';
  }

  //remove any body handlers
  if(document.body.EventHandler.Listeners.mousemove&&document.body.EventHandler.Listeners.mousemove.Groups[this]&&document.body.EventHandler.Listeners.mousemove.Groups[this].Groups["tmp"]){
   document.body.EventHandler.Listeners.mousemove.Groups[this].Groups.tmp.Destroy();
  }

  if(document.body.EventHandler.Listeners.mouseup&&document.body.EventHandler.Listeners.mouseup.Groups[this]&&document.body.EventHandler.Listeners.mouseup.Groups[this].Groups["tmp"]){
   document.body.EventHandler.Listeners.mouseup.Groups[this].Groups.tmp.Destroy();
  }

  cDrag_startmouseX=null;
  cDrag_startmouseY=null;
  cDrag_startX=null;
  cDrag_startY=null;
  cDragItem=null;

 }


 this.DragItem=function(){
  return OriginalDragItem;
 };


 this.createFloatBox=function(el,floatEl,fixedLeft,fixedTop,floatCondition){

  if(typeof(floatCondition)!="function"){
   floatCondition=function(){return true;};
  }

  if(!floatEl){
   floatEl=document.body.appendChild(el.cloneNode(true));
  }

  //this.createDragBox(floatEl,null,true);
  floatEl.style.display='none';
  floatEl.style.zIndex='2000';
  floatEl.style.position='absolute';
  floatEl.style.top='0';
  floatEl.style.left='0';
  System.Element.SetOpacity(floatEl,70);


  cachedElements[cachedElements.length]=floatEl;


  var ev=cachedEventHandlers[cachedEventHandlers.length]=System.Event.CreateHandler(el);

  ev.EnableListener("mousedown").CreateGroup(this).Append(function(e){
   if(!is_rightclick(e)){

    System.Event.CancelBubble(e);
    cDrag_startmouseX=get_mousePosition(e,'x',true);
    cDrag_startmouseY=get_mousePosition(e,'y',true);
    cDrag_startX=cDrag_startmouseX-System.Element.GetXPosition(el);
    cDrag_startY=cDrag_startmouseY-System.Element.GetYPosition(el);

   }
  });


  ev.EnableListener("mousemove").CreateGroup(this).Append(function(e){

   if(floatCondition()&&cDragItem==null&&cDrag_startX!=null&&(get_mousePosition(e,'x',true)-cDrag_startmouseX>5||cDrag_startmouseX-get_mousePosition(e,'x',true)>5||get_mousePosition(e,'y',true)-cDrag_startmouseY>5||cDrag_startmouseY-get_mousePosition(e,'y',true)>5)){

    if(!fixedLeft){
     floatEl.style.left=get_mousePosition(e,'x',true)+"px";
    }else{
     floatEl.style.left=System.Element.GetXPosition(el)+"px";
    }
    if(!fixedTop){
     floatEl.style.top=get_mousePosition(e,'y',true)+"px";
    }else{
     floatEl.style.top=System.Element.GetYPosition(el)+"px";
    }
    floatEl.style.display='';
    cDragItem=floatEl;
    OriginalDragItem=el;


    document.body.EventHandler.EnableListener("mousemove").CreateGroup(self).CreateGroup("tmp").Append(function(e){
     if(cDragItem){
      if(!fixedLeft){
       cDragItem.style.left=get_mousePosition(e,'x',true)+10+"px";
      }
      if(!fixedTop){
       cDragItem.style.top=get_mousePosition(e,'y',true)+"px";
      }
     }
    });


    document.body.EventHandler.EnableListener("mouseup").CreateGroup(self).CreateGroup("tmp").Append(function(){
     self.cancelDrag(true);
    });

   }

  });


  ev.EnableListener("mouseup").CreateGroup(this).Append(function(e){

   cDrag_startX=null;
   cDrag_startY=null;

  });

 };



 this.createDragBox=function(el,floatCondition,noEvents){

  if(typeof(floatCondition)!="function"){
   floatCondition=function(){return true;};
  }

  if(!noEvents){
   var ev=cachedEventHandlers[cachedEventHandlers.length]=System.Event.CreateHandler(el);

   ev.EnableListener("mousedown").CreateGroup(this).Append(function(e){

    if(floatCondition()){

     System.Event.CancelBubble(e);

     if(cDragItem!=el){

      if(Browser.Name!="Internet Explorer"){	//if we don't do this, IE crashes because it doesn't understand -moz-inline-box

       var elOldDisplay=el.style.display;
       el.style.display="-moz-inline-box";	//if we don't do this, FF might give the wrong coordinates on inline elements

      }

      var cDrag_startmouseX=get_mousePosition(e,'x',true);
      var cDrag_startmouseY=get_mousePosition(e,'y',true);
      cDrag_startX=cDrag_startmouseX-System.Element.GetXPosition(el);
      cDrag_startY=cDrag_startmouseY-System.Element.GetYPosition(el);
      el.ondragstart=function(){return false};
      el.onselectstart=function(){return false};
      if(Browser.Name!="Internet Explorer"){
       el.style.display=elOldDisplay;		//if we don't change the display back, FF might not display the element
      }
      cDragItem=null;



      document.body.EventHandler.EnableListener("mousemove").CreateGroup(self).CreateGroup("tmp").Append(function(e){
       if(cDragItem==null&&cDrag_startX!=null&&(get_mousePosition(e,'x',true)-cDrag_startmouseX>5||cDrag_startmouseX-get_mousePosition(e,'x',true)>5||get_mousePosition(e,'y',true)-cDrag_startmouseY>5||cDrag_startmouseY-get_mousePosition(e,'y',true)>5)){

        el.ondragstart=function(){return false};
        el.onselectstart=function(){return false};
        el.style.position="absolute";
        el.style.styleFloat="";
        el.style.cssFloat="";
        el.style.left=get_mousePosition(e,'x',true)-cDrag_startX+"px";
        el.style.top=get_mousePosition(e,'y',true)-cDrag_startY+"px";
        cDragItem=document.body.appendChild(el);

       }else if(cDragItem){

        cDragItem.style.left=get_mousePosition(e,'x',true)-cDrag_startX+"px";
        cDragItem.style.top=get_mousePosition(e,'y',true)-cDrag_startY+"px";

       }
      });


      document.body.EventHandler.EnableListener("mouseup").CreateGroup(self).CreateGroup("tmp").Append(function(){
       self.cancelDrag();
      });

     }

    }

   });

  }

 }



 this.createDropBox=function(el,clickExec,moveExec,outExec){

  if(typeof(moveExec)=="function"){
   document.body.EventHandler.EnableListener("mousemove").CreateGroup(this).Append(function(e){

    if(cDragItem!=null){

     mouseX=get_mouseElementPosition(e,"x",el,true);

     if(mouseX>0&&mouseX<100){

      mouseY=get_mouseElementPosition(e,"y",el,true);
      if(mouseY>0&&mouseY<100){
       moveExec(e);
      }

     }
    }
   });
  }


  if(typeof(outExec)=="function"){

  }


  if(typeof(clickExec)=="function"){

   document.body.EventHandler.EnableListener("mouseup").CreateGroup(this).Append(function(e){

    if(cDragItem!=null){

     mouseX=get_mouseElementPosition(e,"x",el,true);

     if(mouseX>0&&mouseX<100){

      mouseY=get_mouseElementPosition(e,"y",el,true);

      if(mouseY>0&&mouseY<100){
       clickExec(e);
      }

     }
    }
   });
  }

 }
}

function cDropdown(){

 var self=this;
 //this.cssClass;
 //this.buttonCssClass;
 //this.selectBoxCssClass;
 //this.dropDownCssClass;

 //this.focusCssClass;
 //this.buttonFocusCssClass;
 //this.selectBoxFocusCssClass;

 //self.selected;
 self.focus=false;
 self.open=false;
 self.itemhover=false;
 self.Items=[];
 self.EventK=false;

 this.createInstance=function(){

  var main=document.createElement("div");
  main.className=self.cssClass;


  var dropdownInput=document.createElement("input");
  dropdownInput.setAttribute("type","hidden");
  if(self.formName!=null){
   dropdownInput.setAttribute("name",self.formName);
  }
  main.resultBox=main.appendChild(dropdownInput);

  main.onmouseover=function(){
   this.hover();
  }

  main.onmouseout=function(){
   this.unHover();
  }

  main.onfocus=function(){
   self.focus=true;
  }

  var selectbox=main.appendChild(document.createElement("div"));
  selectbox.className=this.selectBoxCssClass;
  if(self.fixedText!=null){
   selectbox.innerHTML=self.fixedText;
  }else if(self.defaultText!=null){
   selectbox.innerHTML=self.defaultText;
  }
  selectbox.onfocus=function(){
   main.focus();
  }
  selectbox.onblur=function(){
   self.focus=false;
   self.open=false;
   main.deFocus();
  }


  var dropdown=document.body.appendChild(document.createElement("div"));


  var downa=main.appendChild(document.createElement("a"));
  downa.setAttribute("href","#");
  downa.onfocus=function(){
   main.focus();
   self.focus=true;
  };
  downa.onkeydown=function(){
   this.firstChild.onclick();
  };
  downa.onclick=function(){
   return false;
  };

  var down=downa.appendChild(document.createElement("div"));
  down.className=this.buttonCssClass;
  down.onclick=function(){
   if(dropdown.style.display=="none"){
    self.itemhover=true;
    dropdown.style.top=System.Element.GetYPosition(main)+main.offsetHeight+"px";
    dropdown.style.left=System.Element.GetXPosition(main)+"px";
    dropdown.style.display="";
    dropdown.focus();
    self.open=true;
   }else{
    self.itemhover=false;
    self.open=false;
    dropdown.style.display="none";
   }
  };
  down.onmouseover=function(){
   self.itemhover=true;
  };
  down.onmouseout=function(){
   self.itemhover=false;
  };
  down.onfocus=function(){
   main.focus();
   self.focus=true;
  };
  down.onblur=function(){
   main.deFocus();
  };


  dropdown.className=this.dropDownCssClass;
  dropdown.style.position="absolute";
  dropdown.style.top="0px";
  dropdown.style.left="0px";
  dropdown.style.display="none";
  dropdown.onblur=function(){
   if(!self.itemhover){
    self.open=false;
    main.deFocus();
   }
  }


  main.unHover=function(){
   if(!self.focus){
    dropdown.style.display="none";
    this.className=self.cssClass;
    selectbox.className=self.selectBoxCssClass;
    down.className=self.buttonCssClass;
   }
  }


  main.deFocus=function(){
   if(!self.open){
    if(typeof(self.onBlur)=="function"){
     self.onBlur();
    }
    self.focus=false;
    this.unHover();
   }
  }


  main.hover=function(){
   this.className=self.focusCssClass;
   selectbox.className=self.selectBoxFocusCssClass;
   down.className=self.buttonFocusCssClass;
  }


  main.focus=function(){
   this.hover();
   if(typeof(self.onFocus)=="function"){
    self.onFocus();
   }
   self.focus=true;
  }


  main.addItem=function(inner,val,cssclass,selectcssclass,funct,mousedownfunct){
   if(self.EventK){
    var a=dropdown.appendChild(document.createElement("a"));

    a.setAttribute("href","#");
    a.style.textDecoration="none";

    a.onclick=function(){
     return false;
    };

    if(typeof(funct)=="function"){
     addEvent(a,"click",funct);
    }else if(funct!=null){
     a.setAttribute("href","javascript:"+funct);
    }

    if(typeof(mousedownfunct)=="function"){
     addEvent(a,"mouseup",mousedownfunct);
    }

    var idiv=a.appendChild(document.createElement("div"));
   }else{
    var idiv=document.createElement("div");

    if(typeof(funct)=="function"){
     addEvent(idiv,"click",funct);
    }

    if(typeof(mousedownfunct)=="function"){
     addEvent(idiv,"mouseup",mousedownfunct);
    }

   }
   idiv.innerHTML=inner;
   idiv.className=cssclass;
   idiv.val=val;


   idiv.onmouseover=function(){
    self.itemhover=true;
    this.className=selectcssclass;
   }


   idiv.onmouseout=function(){
    self.itemhover=false;
    if(self.selected!=this){
     this.className=cssclass;
    }
   }

   idiv.onclick=function(f){
    this.Select();
    if(!f){
     selectbox.focus();
    }
   }

   idiv.Select=function(){
    if(self.selected){
     self.selected.className=cssclass;
    }
    if(self.fixedText==null){
     selectbox.innerHTML=this.innerHTML;
    }
    this.className=selectcssclass;
    main.resultBox.value=main.value=this.val;
    self.selected=this;
    dropdown.style.display="none";
    self.open=false;
    self.itemhover=false;
   }

   if(self.EventK){
    self.Items[self.Items.length]=idiv;
   }else{
    self.Items[self.Items.length]=dropdown.appendChild(idiv);
   }

   return idiv;
  };

  main.Close=function(){
   dropdown.style.display="none";
   self.open=false;
  };

  main.setIndex=function(val){
   if(self.Items.length>val){
    self.Items[val].Select();
   }
  };

  main.setText=function(val){
   selectbox.innerHTML=val;
  };

  main.GetValues=function(){
   var rArr=[];

   for(var i=0;i<self.Items.length;i++){
    if(self.EventK){
     rArr[rArr.length]=self.Items[i].firstChild.val;
    }else{
     rArr[rArr.length]=self.Items[i].val;
    }
   }

   return rArr;
  }

  return main;
 }

}

function cTree(){

 var self=this;

 self.currentlyOpen=null;
 self.currentlyHovered=null;


 this.setInstance=function(el){

  el.selectedCSSClass=self.selectedCSSClass;

  el.hoverItem=function(){
   return self.currentlyHovered;
  }

  el.selectedItem=function(){
   return self.currentlyOpen;
  };

  el.Deselect=function(){
   self.currentlyOpen=null;
  };


  el.openTree=function(arr,prop){
   var exists=false;
   for(var node in this.childNodes){
    var nnode=this.childNodes[node];
    if(nnode[prop]==arr[0][prop]){
     exists=true;
     arr.shift();
     nnode.Expand();
     if(arr.length>0){
      if(nnode.HasItems){
       nnode.openTree(arr,prop);
      }else{
       setTimeout(function(){nnode.openTree(arr,prop);},500);
      }
     }else{
      nnode.Select(false);
     }
     break;
    }
   }
   if(!exists){
    var nnode=this.addItem(arr[0]);
    nnode.Expand();
    arr.shift();
    if(arr.length>0){
     setTimeout(function(){nnode.openTree(arr,prop);},500);
    }else{
     nnode.Select(false);
    }
   }
  };


  el.HasEmptyText=false;

  el.SetEmptyText=function(val){
   if(this.IsEmpty()){
    this.HasEmptyText=true;
    this.innerHTML=val;
   }
  };


  el.createItem=function(val,onclickEvent,onOpenEvent,onMouseUpEvent,hi){

   var container=document.createElement("div");
   container.style.whiteSpace="nowrap";

   container.Loading=false;
   container.Reloading=false;

   container.IndicateHasItems=false;
   if(hi){
    container.IndicateHasItems=true;
   }
   container.HasItems=false;

   var img=document.createElement("img");
   if(!hi){
    img.style.visibility="hidden";
   }
   img.style.display="inline";
   img.src=self.expandImageUrl;
   img.onclick=function(){
    expandNode=this.parentNode.childNodes[2];
    if(expandNode.style.display=="none"){
     this.parentNode.Expand();
    }else{
     this.parentNode.Collapse();
    }
   };


   container.Hide=function(){
    this.style.display="none";
   };


   container.UnHide=function(){
    this.style.display="";
   };


   container.Expand=function(){
    var expandNode=this.childNodes[2];
    if(expandNode.style.display=="none"&&typeof(onOpenEvent)=="function"){
     onOpenEvent.call(el);
    }
    if(this.Loading||this.IndicateHasItems||this.HasItems){
     this.childNodes[0].src=self.collapseImageUrl;
     expandNode.style.display="";
    }
   };


   container.Reload=function(){
    this.Reloading=true;
    var expandNode=this.childNodes[2];
    if(this.HasItems){
     expandNode.innerHTML="";
     expandNode.style.display="";
    }
    if(typeof(onOpenEvent)=="function"){
     onOpenEvent.call(el);
    }
    this.Reloading=false;
   };


   container.Collapse=function(){
    var expandNode=this.childNodes[2];
    if(expandNode.style.display==""){
     this.childNodes[0].src=self.expandImageUrl;
     expandNode.style.display="none";
    }
   };


   container.setText=function(val){
    this.childNodes[1].innerHTML=val;
   };


   container.getText=function(val){
    return this.childNodes[1].innerHTML;
   };


   var textBody=document.createElement("div");
   textBody.style.marginLeft="3px";
   textBody.style.whiteSpace="nowrap";
   textBody.style.display="inline";
   textBody.innerHTML=val;
   if(self.defaultCSSClass!=null){
    textBody.className=self.defaultCSSClass;
   }


   var selectedCSSClass=self.selectedCSSClass;


   textBody.onclick=function(val){

    if(self.currentlyOpen!=this.parentNode||container.HasDifferentClass){

     container.HasDifferentClass=false;

     if(self.currentlyOpen){
      self.currentlyOpen.childNodes[1].className=defaultCSSClass;
     }

     self.currentlyOpen=this.parentNode;
     if(selectedCSSClass!=null){
      this.className=selectedCSSClass;
     }

    }

    if(val||val==null){
     if(typeof(onclickEvent)=="function"){
      onclickEvent.call(el);
     }
    }

   };


   if(self.hoverCSSClass!=null){
    var hoverCSSClass=self.hoverCSSClass;
    var defaultCSSClass=self.defaultCSSClass;
    textBody.onmouseover=function(){
     self.currentlyHovered=this.parentNode;
     if(self.currentlyOpen!=this.parentNode){
      this.className=hoverCSSClass;
     }
    };

    textBody.onmouseout=function(){
     self.currentlyHovered=null;
     if(self.currentlyOpen!=this.parentNode){
      this.className=defaultCSSClass;
     }
    };
   }

   if(typeof(onMouseUpEvent)=="function"){
    addEvent(textBody,"mouseup",onMouseUpEvent,null,null,el);
   }

   var expand=document.createElement("div");
   expand.style.display="none";
   expand.style.marginLeft="16px";


   container.setLoadText=function(val){
    this.Loading=true;
    var exp=this.childNodes[2];
    exp.innerHTML=val;
    exp.style.display="";
    exp=null;
   };


   container.HasDifferentClass=false;

   container.SetCssClass=function(val){

    if(val==self.selectedCSSClass){
     this.HasDifferentClass=false;
    }else{
     this.HasDifferentClass=true;
    }

    this.childNodes[1].className=val;
   };


   container.appendChild(img);
   container.appendChild(textBody);
   container.appendChild(expand);


   textBody=null;
   img=null;


   container.Select=function(val){
    this.childNodes[1].onclick(val);
   };


   container.addItem=function(val){
    if(this.Loading){
     this.childNodes[2].innerHTML="";
     this.Loading=false;
    }
    this.childNodes[0].style.visibility="";
    val=this.childNodes[2].appendChild(val);
    this.HasItems=true;
    return val;
   };

   container.addItems=function(val){
    if(this.Loading){
     this.childNodes[2].innerHTML="";
     this.Loading=false;
    }
    if(val.length>0){
     this.HasItems=true;
    }
    for(var i=0;i<val.length;i++){
     this.addItem(val[i]);
    }
   };

   container.Remove=function(){
    this.style.display="none";
   };

   container.openTree=function(arr,prop){
    var exists=false;
    var exp=this.childNodes[2];
    for(var node in exp.childNodes){
     var nnode=exp.childNodes[node];
     if(nnode[prop]==arr[0][prop]){
      exists=true;
      arr.shift();
      nnode.Expand();
      if(arr.length>0){
       if(nnode.HasItems){
        nnode.openTree(arr,prop);
       }else{
        setTimeout(function(){nnode.openTree(arr,prop);},500);
       }
      }else{
       nnode.Select(false);
      }
      break;
     }
    }
    if(!exists){
     var nnode=this.addItem(arr[0]);
     nnode.Expand();
     arr.shift();
     if(arr.length>0){
      setTimeout(function(){nnode.openTree(arr,prop);},500);
     }else{
      nnode.Select(false);
     }
    }
   };
   exp=null;

   return container;
  };


  expand=null;


  el.addItem=function(val){
   if(this.HasEmptyText){
    this.HasEmptyText=false;
    this.innerHTML="";
   }
   return this.appendChild(val);
  };


  el.addItems=function(val){
   for(var i=0;i<val.length;i++){
    this.addItem(val[i]);
    val[i]=null;
   }
   val=null;
  };


  el.IsEmpty=function(){
   return !this.hasChildNodes();
  };


  return el;
 }


}

/* static check functions */

function validateChar(allow_chars,del_from_last,valObj){
 var i=0;
 var foundValidatedChar=false;
 while(true){
  if(i==valObj.value.length){
   break;
  }
  allow_chars_instr=allow_chars.indexOf(valObj.value.charAt(i));
  if(allow_chars_instr==-1){
   if(del_from_last&&foundValidatedChar){
    valObj.value=valObj.value.substring(0,i);
    break;
   }else{
    valObj.value=valObj.value.substring(0,i)+valObj.value.substring(i+1,valObj.value.length);
   }
  }else{
   foundValidatedChar=true;
   i++;
  }
 }
}


function validateNumeric(curObj){
 validateChar("1234567890.",false,curObj);
 doubleSpl=curObj.value.split('.');
 if(doubleSpl.length>2){
  curObj.value=doubleSpl[0]+'.'+doubleSpl[1];
 }
}


function validateDouble(curObj){
 validateChar("1234567890.",false,curObj);
 var curVal=curObj.value;
 doubleSpl=curVal.split('.');
 if(doubleSpl.length>1){
  doubleVal=doubleSpl[1];
  if(doubleVal.length>2){
   curObj.value=curVal.substring(0,doubleSpl[0].length+3);
  }
 }
}


function validateInt(curObj){
 validateChar("1234567890",true,curObj);
}


/* on the fly check functions */

function checkNumeric(curObj,e){
 validateNumeric(curObj);
 var gkeyCode=get_keycode(e);
 if(((gkeyCode>47&&gkeyCode<58)||gkeyCode==46||is_std_input(e))&&((curObj.value.indexOf('.')>-1&&get_keycode(e)!=46)||curObj.value.indexOf('.')==-1)){
  return true;
 }else{
  return false;
 }
}


function checkInt(curObj,e){
 if(checkNumeric(curObj,e)){
  validateInt(curObj);
  var gkeyCode=get_keycode(e);
  if(gkeyCode==46){
   return false;
  }else{
   return true;
  }
 }else{
  return false;
 }
}


function checkDouble(curObj,e){
 if(checkNumeric(curObj,e)){
  validateDouble(curObj);
  if(curObj.value.indexOf('.')>-1&&!is_std_input(e)){
   curObj_spl=curObj.value.split(".");
   if(curObj_spl[1].length>1){
    return false;
   }
  }
  return true;
 }else{
  return false;
 }
}

ActiveWYSIWYG=null;

function cWysiwyg(){

 var self=this;

 self.Frame=null;
 self.menuArray=[];

 self.fonts=["Arial"];
 self.formats=["p","h1","h2","h3","h4","h5","h6","pre"];
 self.fontsizemin=1;
 self.fontsizemax=7;

 var NoStateCommands=["indent","outdent","hyperlink","custom","redo","undo","cut","copy","paste"];
 var undoStack=[];
 var undoID=-1;
 var pasteStack=[];

 this.createMenuItem=function(val,cssclass,hovercssclass,selectedcssclass,img,tooltip,funct,keepState){

  if(val=="font"||val=="format"||val=="fontsize"){
   var aI=new cDropdown();

   aI.cssClass='dropdown';
   aI.selectBoxCssClass='dropdownselect';
   aI.buttonCssClass='dropdownbutton';
   aI.dropDownCssClass='dropdownbox';

   aI.focusCssClass='dropdownfocus';
   aI.selectBoxFocusCssClass='dropdownselectfocus';
   aI.buttonFocusCssClass='dropdownbuttonfocus';

   aI.EventK=true;

   if(val=="font"){
    aI.defaultText="Font";
   }else if(val=="format"){
    aI.defaultText="Formatting";
   }else if(val=="fontsize"){
    aI.defaultText="Fontsize";
   }

   var a=aI.createInstance();
   a.Type=val;

   if(val=="font"){
    for(var i=0;i<self.fonts.length;i++){
     a.addItem("<span style='font-family:"+self.fonts[i].toLowerCase()+";'>"+self.fonts[i]+"</span>",this.fonts[i],cssclass,hovercssclass,function(){alert("boe");},true);
    }
   }else if(val=="format"){
    for(var i=0;i<=self.formats.length;i++){
     var f=self.formats[i];
     var f_o=null;
     var f_c=null;
     if(f!=null){
      f=f.toLowerCase();
      var inner="";
      if(f.substring(0,1)!="h"){
       switch(f){
        case "strong":
         inner="<strong style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Strong</strong>";
         break;
        case "code":
         inner="<code style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Code</code>";
         break;
        case "em":
         inner="<em style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Emphasis</em>";
         break;
        case "p":
         inner="<p style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Paragraph</p>";
         break;
        case "pre":
         inner="<pre style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Pre formatted</pre>";
         break;
        case "ul":
         inner="<ul style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'><li style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Bulleted</li></ul>";
         break;
        case "ol":
         inner="<ol style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'><li style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Numbered</li></ol>";
         break;
       }
      }else{
       inner="<"+f+" style='border:none;margin-top:0px;margin-bottom:0px;padding-top:0px;padding-bottom:0px;'>Heading "+f.substring(1,2)+"</"+f+">";
      }
      if(f=="code"){
       a.addItem(inner,"<"+f+">",cssclass,hovercssclass,function(){var wysFrame=self.Frame;wysFrame.setState('inserthtml','<code>'+wysFrame.getSelection()+'</code>');});
      }else{
       var cf=function(){
        var fr=f;
        a.addItem(inner,"<"+fr+">",cssclass,hovercssclass,function(){self.Frame.setState('formatblock','<'+fr+'>');});
       }();
      }
     }
    }
   }else if(val=="fontsize"){
    for(var i=self.fontsizemin;i<=self.fontsizemax;i++){
     a.addItem("<font size='"+i+"'>Size "+i+"</font>",i,cssclass,hovercssclass,function(){self.Frame.setState("fontsize",i);});
    }
   }
  }else{
   var a=document.createElement("a");
   a.setAttribute("href",tooltip);
   a.style.textDecoration="none";

   a.onclick=function(){return false;};

   a.Type=val;
   a.CssClass=cssclass;
   a.HoverCssClass=hovercssclass;
   a.SelectedCssClass=selectedcssclass;

   var div=a.appendChild(document.createElement("div"));
   div.className=cssclass;

   if(img!=null){
    div.style.backgroundImage="url("+img+")";
   }else{
    div.innerHTML=val;
   }

   div.title=tooltip;

   div.onmouseover=function(){
    this.className=hovercssclass;
   };

   if(keepState){
    div.Selected=false;
   }

   div.onmouseout=function(){
    if(!this.Selected){
     if(NoStateCommands.indexOf(val)==-1){
      if(self.Frame.checkState(val)){
       this.className=selectedcssclass;
      }else{
       this.className=cssclass;
      }
     }else{
      this.className=cssclass;
     }
    }else{
     this.className=selectedcssclass;
    }
   };

   if(val=="custom"){


    if(keepState){
     var clickev=System.Event.CreateHandler(div).EnableListener("click");
     div.Selected=false;

     clickev.Append(function(){
      if(this.Selected){
       this.Selected=false;
      }else{
       this.Selected=true;
      }
     });

     clickev.Append(funct);

    }else{
     div.onclick=funct;
    }

   }else{
    div.onclick=function(){
     self.Frame.setState(val);
     self.Frame.updateMenuState();
     if(NoStateCommands.indexOf(val)==-1){
      if(!self.Frame.checkState(val)){
       this.className=hovercssclass;
      }
     }
    };

   }
  }

  self.menuArray[self.menuArray.length]=a;

  return a;
 }


 this.createInstance=function(){

  var wysiwygIframe=document.createElement("iframe");

  var ev=System.Event.CreateHandler(wysiwygIframe).EnableListener("paste");

  var pasteChangeElement=document.body.appendChild(document.createElement("div"));
  pasteChangeElement.style.display="none";
  pasteChangeElement.style.position="absolute";
  pasteChangeElement.style.border="1px solid #0A246A";
  pasteChangeElement.style.zIndex="10000";
  pasteChangeElement.style.backgroundColor="#FFFFFF";
  pasteChangeElement.style.backgroundImage="url(img/wysiwyg/paste.gif)";
  pasteChangeElement.style.backgroundRepeat="no-repeat";
  pasteChangeElement.style.backgroundPosition="50% 50%";
  pasteChangeElement.style.height="18px";
  pasteChangeElement.style.width="18px";


  wysiwygIframe.SetPasteHovers=function(){

   var wysiwygdoc=wysiwygIframe.contentWindow.document;
   var cpasteEl;

   for(var i=0;i<pasteStack.length;i++){

    cpasteEl=wysiwygdoc.getElementById("__wysiwyg_paste_"+pasteStack[i][0]);

    var stackEvent=System.Event.CreateHandler(cpasteEl);

    stackEvent.EnableListener("mouseover").Append(function(e){

     var el=this;
     wysiwygIframe.pasteContextMenu.Hide();

     var wysiwygLeft=System.Element.GetXPosition(wysiwygIframe);
     var wysiwygTop=System.Element.GetYPosition(wysiwygIframe);

     var leftMax=wysiwygLeft+wysiwygIframe.offsetWidth-40;
     var topMax=wysiwygTop+wysiwygIframe.offsetHeight-40;

     var leftScroll=wysiwygdoc.pageXOffset||wysiwygdoc.body.scrollLeft||wysiwygdoc.documentElement.scrollLeft;
     var topScroll=wysiwygdoc.pageYOffset||wysiwygdoc.body.scrollTop||wysiwygdoc.documentElement.scrollTop;

     var left=System.Element.GetXPosition(this)+this.offsetWidth+wysiwygLeft-20;
     var top=System.Element.GetYPosition(this)+this.offsetHeight+wysiwygTop-1;


     if(left>leftMax){
      pasteChangeElement.style.left=leftMax+"px";
     }else{
      pasteChangeElement.style.left=left+"px";
     }


     if(top>topMax){
      pasteChangeElement.style.top=topMax+"px";
     }else{
      pasteChangeElement.style.top=top+"px";
     }

     pasteChangeElement.style.display="block";

     var openc=function(){

      el.style.backgroundColor="#CECECE";
      pasteChangeElement.style.borderBottom="none";
      pasteChangeElement.style.width="24px";
      pasteChangeElement.style.backgroundColor="#C2DBF8";
      wysiwygIframe.pasteContextMenu.AdjustToElementPosition(pasteChangeElement,0,-1);
      wysiwygIframe.pasteContextMenu.show(e,el);

     };

     pasteChangeElement.onmouseover=openc;
     pasteChangeElement.onmouseup=openc;

     pasteChangeElement.onmouseout=function(){
      el.style.backgroundColor="";
     };

     wysiwygIframe.pasteContextMenu.EventHandler.Listeners.hide.Append(function(){

      pasteChangeElement.style.display="none";
      pasteChangeElement.style.borderBottom="1px solid #0A246A";
      pasteChangeElement.style.width="18px";
      pasteChangeElement.style.backgroundColor="#FFFFFF";

     });

    });

   }


  };


  ev.Append(function(){

   wysiwygIframe.stackInner();
   var uindex=getUniqueIndex();
   var wysiwygdoc=wysiwygIframe.contentWindow.document;

   // force uniqeness
   while(wysiwygdoc.getElementById("__wysiwyg_paste_"+uindex)){
    uindex=getUniqueIndex();
   }

   if(Browser.Name=="Internet Explorer"){
    wysiwygIframe.setState("inserthtml","</p><span id=\"__wysiwyg_paste_"+uindex+"\">&nbsp;<span id=\"__wysiwyg_paster_"+uindex+"\">paste here</span>&nbsp;</span>",true);

    var sellRange=wysiwygIframe.getSelection(2).createRange();
    sellRange.moveToElementText(wysiwygdoc.getElementById("__wysiwyg_paster_"+uindex));
    sellRange.select();

   }else{
    wysiwygIframe.setState("inserthtml","<span id=\"__wysiwyg_paste_"+uindex+"\"></span>");
   }

   setTimeout(function(){

    var pasteEl=wysiwygdoc.getElementById("__wysiwyg_paste_"+uindex);
    if(pasteEl){

     //remove the pasterEl if still there
     var pasterEl=wysiwygdoc.getElementById("__wysiwyg_paster_"+uindex);
     if(pasterEl&&(pasterEl.innerHTML=="paste here"||pasterEl.innerHTML=="")){
      pasteEl.removeChild(pasterEl);
     }

     pastedText=pasteEl.innerHTML;

     if(Browser.Name=="Internet Explorer"){
      pastedText=pastedText.substring(6,pastedText.length-6);


      try{
       pasteEl.innerHTML=pastedText;
      }catch(e){	//strip all block level elements

       var blockPasteEl=wysiwygIframe.contentWindow.document.createElement("div");
       blockPasteEl.setAttribute("id","__wysiwyg_paste_"+uindex);
       blockPasteEl.innerHTML=pastedText;

       pasteEl.parentNode.replaceChild(blockPasteEl,pasteEl);
       pasteEl=wysiwygdoc.getElementById("__wysiwyg_paste_"+uindex);
       
      }
     }


     if(pastedText.replace(/<br\/{0,1}>/gi,"").indexOf("<")>-1){	//no HTML tags, no formatting

      //unique index of paste item, the original text, the current text
      pasteStack[pasteStack.length]=[uindex,pasteEl.innerHTML,pasteEl.innerHTML];

      wysiwygIframe.SetPasteHovers();

     }
    }

   },100);

  });


  if(Browser.Name=="Internet Explorer"){
   ev.Append(function(){
    setTimeout(function(){
     wysiwygIframe.stackInner();
    },600);
   });

  }



  wysiwygIframe.setAttribute("border","0");
  wysiwygIframe.setAttribute("frameBorder","0");
  wysiwygIframe.setAttribute("marginWidth","0");
  wysiwygIframe.setAttribute("marginHeight","0");
  wysiwygIframe.setAttribute("leftMargin","0");
  wysiwygIframe.setAttribute("topMargin","0");
  wysiwygIframe.setAttribute("allowtransparency","true");
  if(this.cssClass!=null){
   wysiwygIframe.className=this.cssClass;
  }
  if(this.style!=null){
   if(Browser.Name=="Internet Explorer"){
    wysiwygIframe.style.setAttribute("cssText",this.style);	//goddamnit IE is stupid
   }else{
    wysiwygIframe.setAttribute("style",this.style);
   }
  }


  wysiwygIframe.eventTargetElement=null;


  var wysiwygInput=document.createElement("input");
  wysiwygInput.setAttribute("type","hidden");
  if(this.formName!=null){
   wysiwygInput.setAttribute("name",this.formName);
  }
  wysiwygIframe.resultBox=wysiwygInput;

  var menuStateKeyCodes=[8,13,37,38,39,40];

  wysiwygIframe.Write=function(val){
   var inner=this.contentWindow.document;
   inner.open();
   inner.write(val);
   inner.close();


   /* add events here because these will be removed when the document is rewritten */
   inner.EventHandler=null;
   var ev=System.Event.CreateHandler(inner);
   var keyupev=ev.EnableListener("keyup");
   keyupev.Append(function(e){
    if(is_ctrl(e)||menuStateKeyCodes.indexOf(get_keycode(e))>-1){
     wysiwygIframe.updateMenuState();
    }
   });


   keyupev.Append(function(){

    var cpasteEl, wysiwygdoc=wysiwygIframe.contentWindow.document;

    if(!wysiwygIframe.pasteChangeCheckRunning){
     wysiwygIframe.pasteChangeCheckRunning=true;

     for(var i=0;i<pasteStack.length;i++){

      cpasteEl=wysiwygdoc.getElementById("__wysiwyg_paste_"+pasteStack[i][0]);
      if(cpasteEl.innerHTML!=pasteStack[i][2]){

       System.Event.DestroyHandler(cpasteEl);
       pasteStack.splice(i,1);
       i--;

      }

     }

     wysiwygIframe.pasteChangeCheckRunning=false;

    }

   });


   var keydownev=ev.EnableListener("keydown");
   keydownev.Append(function(e){
    e=e||window.event;

    wysiwygIframe.eventTargetElement=e.target||e.srcElement;

    if(is_ctrl(e)){

     if(get_keycode(e)==86){
      wysiwygIframe.EventHandler.Listeners.paste.Fire();
     }else if(get_keycode(e)==90){

      wysiwygIframe.setState("undo");
      System.Event.CancelBubble(e);

     }else if(get_keycode(e)==89){

      wysiwygIframe.setState("redo");
      System.Event.CancelBubble(e);

     }

    }

   });

   keydownev.Append(function(e){
    if(get_keycode(e)==9||e.tabKey){
     System.Event.CancelBubble(e);
     var el=inner;
     el.focus();
     var sel=document.selection.createRange();
     sel.text="\t";
    }
   });

   var mouseupev=ev.EnableListener("mouseup");
   mouseupev.Append(function(){wysiwygIframe.updateMenuState();});
   this.stackInner();
  };


  wysiwygIframe.MatchFormat=function(val){

   var MatchTableFormat=function(el){
    var newTable, oldTbody, newTbody, oldTr, newTr, oldTd, newTd, colspan, rowspan;

    newTable=wysiwygIframe.contentWindow.document.createElement("TABLE");
    newTable.border="1";

    for(var i=0;i<el.childNodes.length;i++){
     oldTbody=el.childNodes[i];
     if(oldTbody.tagName=="TBODY"||oldTbody.tagName=="THEAD"){
      newTbody=newTable.appendChild(wysiwygIframe.contentWindow.document.createElement(oldTbody.tagName));

      for(j=0;j<oldTbody.childNodes.length;j++){
       oldTr=oldTbody.childNodes[j];
       if(oldTr.tagName=="TR"){
        newTr=newTbody.appendChild(wysiwygIframe.contentWindow.document.createElement("TR"));

        for(var k=0;k<oldTr.childNodes.length;k++){
         oldTd=oldTr.childNodes[k];
         if(oldTd.tagName=="TD"||oldTd.tagName=="TH"){
          newTd=newTr.appendChild(wysiwygIframe.contentWindow.document.createElement(oldTd.tagName));

          colspan=oldTd.getAttribute("colspan");
          if(colspan){
           newTd.setAttribute("colspan",colspan);
          }

          rowspan=oldTd.getAttribute("rowspan");
          if(rowspan){
           newTd.setAttribute("rowspan",rowspan);
          }

          LoopEls(oldTd);
          newTd.innerHTML=oldTd.innerHTML;
         }
        }

       }
      }

     }
    }

    el.parentNode.replaceChild(newTable,el);
   };


   var MatchFormat=function(oel){

    if(oel.nodeType==1){
     var tagName=oel.tagName;


     var res=null;
     if(tagName!="SCRIPT"){
      res=oel.innerHTML;
     }


     /* remove FONT & SCRIPT tags */
     if(tagName=="FONT"||tagName=="SCRIPT"){
      var nel=wysiwygIframe.contentWindow.document.createElement("span");
     }else{


      /* replace any block level elements in a p tag
       not a pretty solution... but it prevents any errors
       if we want a 100% check we need a custom HTML parser that closes p tags before opening other block elements
       or we should stop changing the innerHTML
       or simply create a div, set the innerhtml and append div to p. (what we're currently doing)

      if(tagName=="P"&&res.match(new RegExp("<(?:"+System.Element.BlockLevelTagNames.join("|")+")[^>]*>","i"))){
       res=res.replace(new RegExp("<\/{0,1}("+System.Element.BlockLevelTagNames.join("|")+")[^>]*>","ig"),function(val,tagName){
        if(tagName.toLowerCase()=="table"){
         return val;
        }else{
         return "";
        }
       });
      }

      */

      var nel=wysiwygIframe.contentWindow.document.createElement(tagName);

     }


     /* set the href attribute if it concerns a A tag */
     switch(tagName){
      case "A":

       nel.setAttribute("href",oel.getAttribute("href"));

       var aonclick=oel.getAttribute("onclick");
       if(aonclick&&aonclick.indexOf("return false")>-1){
        nel.setAttribute("onclick",aonclick);
       }

       nel.setAttribute("target","_blank");
       break;

      case "IMG":

       nel.setAttribute("src",oel.getAttribute("src"));
       break;

     }



     if(res){

      /* remove P in P tags */
      if(tagName=="P"){
       res=res.replace(/<\/{0,1}(o:){0,1}P>/gi,"");
      }

      /* remove all empty P tags */
      res=res.replace(/<(o:){0,1}P><\/(o:){0,1}P>/gi,"");

      try{
       nel.innerHTML=res;
      }catch(e){

       var div=wysiwygIframe.contentWindow.document.createElement("div");
       div.innerHTML=res;
       nel.appendChild(div);
       div=null;

      }

      /* remove single nested SPAN tags */
      if(nel.childNodes.length==1){
       if(nel.firstChild.tagName=="SPAN"){

        try{
         nel.innerHTML=nel.firstChild.innerHTML;
        }catch(e){}

       }
      }

      /* remove single nested P tags in LI, TD, TH */
      if((tagName=="LI"||tagName=="TD"||tagName=="TH")&&nel.childNodes.length==1){
       if(nel.firstChild.tagName=="P"){

        try{
         nel.innerHTML=nel.firstChild.innerHTML;
        }catch(e){}

       }
      }

     }

     oel.parentNode.replaceChild(nel,oel);
     oel=null;
     nel=null;

    }
   };


   var LoopEls=function(el){
    switch(el.tagName){
     case "TABLE":

      MatchTableFormat(el);
      break;

     default:

      for(var i=0;i<el.childNodes.length;i++){
       LoopEls(el.childNodes[i]);
      }

      MatchFormat(el);
      break;
    }
   };

   if(!val){
    val=wysiwygIframe.contentWindow.document.body;
   }
   LoopEls(val);

  };


  wysiwygIframe.getOriginalFromPasteStack=function(el){
   var elId=el.id;
   if(elId){
    elId=System.Convert.ToInt(elId.replace("__wysiwyg_paste_",""));
    for(var i=0;i<pasteStack.length;i++){
     if(pasteStack[i][0]==elId){
      return pasteStack[i][1];
     }
    }
   }
  };


  wysiwygIframe.setCurrentToPasteStack=function(el){
   var elId=el.id;
   if(elId){
    elId=System.Convert.ToInt(elId.replace("__wysiwyg_paste_",""));
    for(var i=0;i<pasteStack.length;i++){
     if(pasteStack[i][0]==elId){
      pasteStack[i][2]=el.innerHTML;
     }
    }
   }
  };


  wysiwygIframe.ChangePastInner=function(el,inner){

   var newEl=wysiwygIframe.contentWindow.document.createElement(el.tagName);
   newEl.setAttribute("id",el.id);
   newEl.innerHTML=inner;

   el.parentNode.replaceChild(newEl,el);

   wysiwygIframe.SetPasteHovers();

   return newEl;

  };


  wysiwygIframe.loadContextMenus=function(){

   var ev=System.Event.CreateHandler(this.contentWindow.document);
   var contextmenuev=ev.EnableListener("contextmenu");
   contextmenuev.Append(function(e){
    System.Event.CancelBubble(e);
    return false;
   });

   var thisleft=System.Element.GetXPosition(this);
   var thistop=System.Element.GetYPosition(this);

   var pasteContextMenu=new cContext();
   pasteContextMenu.createInstance();


   pasteContextMenu.addItem(null,"Keep format",function(){

    var el=this.arguments[0];
    var r=wysiwygIframe.getOriginalFromPasteStack(el);

    if(r){

     wysiwygIframe.ChangePastInner(el,r);
     wysiwygIframe.setCurrentToPasteStack(wysiwygIframe.contentWindow.document.getElementById(el.id));

    }

   });


   pasteContextMenu.addItem(null,"Match format",function(){
    var el=this.arguments[0];
    var r=wysiwygIframe.getOriginalFromPasteStack(el);
    if(r){

     el=wysiwygIframe.ChangePastInner(el,r);

     for(var i=0;i<el.childNodes.length;i++){
      wysiwygIframe.MatchFormat(el.childNodes[i]);
     }

     wysiwygIframe.setCurrentToPasteStack(el);

    }
   });


   pasteContextMenu.addItem(null,"Text only",function(){
    el=this.arguments[0];
    var r=wysiwygIframe.getOriginalFromPasteStack(el);

    if(r){

     wysiwygIframe.ChangePastInner(el,r.replace(/\n/g,"").replace(/\<br *\/{0,1}>/gi,"\n").replace(/<(?:o:){0,1}p>/gi,"").replace(/<\/(?:o:){0,1}p>/gi,"\n").replace(/<[^>]*>/g,"").replace(/\n/g,"<br />"));
     wysiwygIframe.setCurrentToPasteStack(wysiwygIframe.contentWindow.document.getElementById(el.id));

    }

   });

   pasteContextMenu.parse(this.contentWindow.document);

   this.pasteContextMenu=pasteContextMenu;

   var contextMenu=new cContext();
   contextMenu.createInstance();
   contextMenu.left=thisleft+2;
   contextMenu.top=thistop;

   var contextMenuCut=contextMenu.addItem("img/wysiwyg/cut.gif","<a href='#' onclick='return false;'>Cut</a>",function(){wysiwygIframe.setState("cut");},null);
   var contextMenuCopy=contextMenu.addItem("img/wysiwyg/copy.gif","<a href='#' onclick='return false;'>Copy</a>",function(){wysiwygIframe.setState("copy");},null);
   var contextMenuPaste=contextMenu.addItem("img/wysiwyg/paste.gif","<a href='#' onclick='return false;'>Paste</a>",function(){wysiwygIframe.setState("paste");},null);

   var contextGroupF=function(arr){
    var o=new function(){
     this.Hide=function(){
      for(var i=0;i<arr.length;i++){
       var arrEl=arr[i];
       if(arrEl){
        arr[i].Hide();
       }
      }
     };

     this.UnHide=function(){
      for(var i=0;i<arr.length;i++){
       var arrEl=arr[i];
       if(arrEl){
        arr[i].UnHide();
       }
      }
     };

     this.Disable=function(){
      for(var i=0;i<arr.length;i++){
       var arrEl=arr[i];
       if(arrEl){
        arr[i].Disable();
       }
      }
     };

     this.Enable=function(){
      for(var i=0;i<arr.length;i++){
       var arrEl=arr[i];
       if(arrEl){
        arr[i].Enable();
       }
      }
     };
    };
    return o;
   };

   if(wysiwygIframe.ContextHyperlinkAdd&&wysiwygIframe.ContextHyperlinkAdd.substring(0,1)!="&"){
    wysiwygIframe.ContextHyperlinkAdd="&"+wysiwygIframe.ContextHyperlinkAdd;
   }else{
    wysiwygIframe.ContextHyperlinkAdd="";
   }

   var contextGroups=new Object();

   contextGroups.element=contextGroupF([
    contextMenu.addBreak(),
    contextMenu.openSub(contextMenu.addItem("img/custom/macro/tag.gif","Element",null,"background-image:url(img/icon/right.gif);background-repeat:no-repeat;background-position:92px 50%;")),
    contextMenuAlign=contextMenu.openSub(contextMenu.addItem(null,"Align",null,"background-image:url(img/icon/right.gif);background-repeat:no-repeat;background-position:92px 50%;")),
    contextMenuAlignNone=contextMenu.addItem("img/wysiwyg/floatnone.gif","None",function(){this.argument.style.cssFloat="";this.argument.style.styleFloat="";}),
    contextMenuAlignLeft=contextMenu.addItem("img/wysiwyg/floatleft.gif","Left",function(){this.argument.style.cssFloat="left";this.argument.style.styleFloat="left";}),
    contextMenuAlignRight=contextMenu.addItem("img/wysiwyg/floatright.gif","Right",function(){this.argument.style.cssFloat="right";this.argument.style.styleFloat="right";}),
    contextMenu.closeSub(),
    contextMenuPos=contextMenu.openSub(contextMenu.addItem(null,"Position",null,"background-image:url(img/icon/right.gif);background-repeat:no-repeat;background-position:92px 50%;")),
    contextMenuPosStatic=contextMenu.addItem(null,"Static",function(){this.argument.style.position="static";}),
    contextMenuPosRelative=contextMenu.addItem(null,"Relative",function(){this.argument.style.position="relative";}),
    contextMenuPosAbsolute=contextMenu.addItem(null,"Absolute",function(){this.argument.style.position="absolute";}),
    contextMenu.closeSub(),
    contextMenu.closeSub()
   ]);

   contextGroups.table=contextGroupF([
    contextMenu.addBreak(),
    contextMenu.openSub(contextMenu.addItem(null,"Table",null,"background-image:url(img/icon/right.gif);background-repeat:no-repeat;background-position:92px 50%;")),
    contextMenu.addItem("img/wysiwyg/table/insertcleft.gif","Insert left",function(){var c=getFirstAncestor(this.argument,["td"]);var cIndex=c.cellIndex;var t=c.parentNode.parentNode;for(var i=0;i<t.childNodes.length;i++){t.childNodes[i].insertCell(cIndex);}}),
    contextMenu.addItem("img/wysiwyg/table/insertcright.gif","Insert right",function(){var c=getFirstAncestor(this.argument,["td"]);var cIndex=c.cellIndex;var t=c.parentNode.parentNode;for(var i=0;i<t.childNodes.length;i++){t.childNodes[i].insertCell(cIndex+1);}}),
    contextMenu.addItem("img/wysiwyg/table/delcolumn.gif","Delete column",function(){var c=getFirstAncestor(this.argument,["td"]);var cIndex=c.cellIndex;var t=c.parentNode.parentNode;for(var i=0;i<t.childNodes.length;i++){t.childNodes[i].deleteCell(cIndex);}}),
    contextMenu.addBreak(),
    contextMenu.addItem("img/wysiwyg/table/insertrabove.gif","Insert above",function(){var r=getFirstAncestor(this.argument,["tr"]);var nr=r.parentNode.insertRow(r.rowIndex);for(var i=0;i<r.childNodes.length;i++){nr.insertCell();}}),
    contextMenu.addItem("img/wysiwyg/table/insertrbelow.gif","Insert below",function(){var r=getFirstAncestor(this.argument,["tr"]);var nr=r.parentNode.insertRow(r.rowIndex+1);for(var i=0;i<r.childNodes.length;i++){nr.insertCell();}}),
    contextMenu.addItem("img/wysiwyg/table/delrow.gif","Delete row",function(){var r=getFirstAncestor(this.argument,["tr"]);r.parentNode.deleteRow(r.rowIndex);}),
    contextMenu.addBreak(),
    contextMenuTableMergeCells=contextMenu.addItem("img/wysiwyg/table/mergecells.gif","<a href='merge' onclick='return false;'>Merge Cells</a>",function(){var cells=wysiwygIframe.getSelectedCells();if(cells.length>-1){var colspan=cells[0].getAttribute("colspan")||1;for(var i=1;i<cells.length;i++){cells[0].innerHTML+=cells[i].innerHTML;colspan+=cells[i].getAttribute("colspan")||1;cells[i].parentNode.removeChild(cells[i]);}cells[0].colSpan=colspan;}}),
    contextMenuTableSplitCells=contextMenu.addItem("img/wysiwyg/table/splitcells.gif","<a href='split' onclick='return false;'>Split Cells</a>",function(){var cell=getFirstAncestor(this.argument,["td"]);var colspan=cell.getAttribute("colspan");var cellIndex=cell.cellIndex;cell.colSpan=1;var row=cell.parentNode;for(var i=1;i<colspan;i++){row.insertCell(cellIndex+1);}}),
    contextMenu.closeSub(),
   ]);

   contextGroups.href=contextGroupF([
    contextMenu.addBreak(),
    contextMenu.addItem("img/wysiwyg/hyperlink.gif","<a href='#' onclick='return false;'>Edit hyperlink</a>",function(){var w=window.open(new System.URL('?template=wysiwyg_hyperlink'+wysiwygIframe.ContextHyperlinkAdd).ToString(),'','scrollbars=no,resizable=no,width=426,height=259');w.eEl=this.argument;}),
    contextMenuHrefOpen=contextMenu.addItem(null,"Open hyperlink",function(){window.open(getFirstAncestor(this.argument,["a"]).href);}),
    contextMenu.addItem(null,"<a href='#' onclick='return false;'>Remove hyperlink</a>",function(){var aEl=getFirstAncestor(this.argument,["a"]);var inner=aEl.innerHTML;aEl.parentNode.removeChild(aEl);wysiwygIframe.setState("inserthtml",inner);})
   ]);

   contextGroups.file=contextGroupF([
    contextMenu.addBreak(),
    contextMenu.addItem("img/wysiwyg/addattach.gif","<a href='#' onclick='return false;'>Edit file location</a>",function(){window.open(new System.URL('?template=wysiwyg_upload'+wysiwygIframe.ContextHyperlinkAdd).ToString(),'','scrollbars=no,resizable=no,width=426,height=259');}),
    contextMenu.addItem(null,"Open file",function(){location.href=getFirstAncestor(this.argument,["a"]).href;}),
    contextMenu.addItem(null,"<a href='#' onclick='return false;'>Remove hyperlink</a>",function(){var aEl=getFirstAncestor(this.argument,["a"]);var inner=aEl.innerHTML;aEl.parentNode.removeChild(aEl);wysiwygIframe.setState("inserthtml",inner);})
   ]);

   contextGroups.img=contextGroupF([
    contextMenu.addBreak(),
    contextMenu.addItem("img/wysiwyg/image.gif","<a href='#' onclick='return false;'>Edit image</a>",function(){window.open(new System.URL('?template=wysiwyg_image'+wysiwygIframe.ContextHyperlinkAdd).ToString(),'','scrollbars=no,resizable=no,width=390,height=218');}),
   ]);

   contextMenu.parse(this.contentWindow.document);
   this.contextMenu=contextMenu;

   var mouseupev=ev.EnableListener("mouseup");

   mouseupev.Append(function(e){

    wysiwygIframe.stackInner();

    var anc;
    e=e||window.event;
    if(is_rightclick(e)){


     //hide all contextgroups and unhide only when asked for
     for(var g in contextGroups){
      contextGroups[g].Hide();
     }


     //check if there's a selection and enable/disable cut/copy buttons
     var sel=wysiwygIframe.getSelection();
     if(sel!=""&&sel!=null){
      contextMenuCut.Enable();
      contextMenuCopy.Enable();
     }else{
      contextMenuCut.Disable();
      contextMenuCopy.Disable();
     }



     var el=wysiwygIframe.eventTargetElement=e.target||e.srcElement;
     var pEls=getParentElementNames(el,true);


     //0 & 1 are html & body
     if(pEls.length>2){

      contextGroups.element.UnHide();

      if(pEls.indexOf("td")>-1){
       if(el.tagName=="TD"){
        contextMenuPos.Hide();
        contextMenuAlign.Hide();
       }

       contextGroups.table.UnHide();

       var sel=wysiwygIframe.getSelection();
       if(typeof(sel)=="string"&&((sel.indexOf("<tr>")==-1&&sel.indexOf("<TR>")==-1)&&(sel.indexOf("<td")>-1||sel.indexOf("<TD")>-1))){
        contextMenuTableMergeCells.Enable();
       }else{
        contextMenuTableMergeCells.Disable();
       }

       if(window.getSelection){
        anc=getFirstAncestor(wysiwygIframe.getSelection(2).getRangeAt(0).commonAncestorContainer,["td"]);
       }else{
        var r=wysiwygIframe.getSelection(2).createRange();
        if(r.parentElement){
         anc=getFirstAncestor(r.parentElement(),["td"]);
        }
       }

       if(anc){
        anc=anc.getAttribute("colspan");
       }else{
        anc=0;
       }


       if(typeof(sel)=="string"&&(sel.indexOf("<td")==-1&&sel.indexOf("<TD")==-1&&anc>1)){
        contextMenuTableSplitCells.Enable();
       }else{
        contextMenuTableSplitCells.Disable();
       }

      }else{
       contextMenuPos.UnHide();
       contextMenuAlign.UnHide();
      }

      elPos=el.style.position;
      if(elPos==null||elPos==""||elPos=="static"){
       contextMenuPosStatic.Disable();
      }else{
       contextMenuPosStatic.Enable();
      }
      if(elPos=="relative"){
       contextMenuPosRelative.Disable();
      }else{
       contextMenuPosRelative.Enable();
      }
      if(elPos=="absolute"){
       contextMenuPosAbsolute.Disable();
      }else{
       contextMenuPosAbsolute.Enable();
      }

      elFloat=el.style.cssFloat||el.style.styleFloat;
      if(elFloat==null||elFloat==""){
       contextMenuAlignNone.Disable();
      }else{
       contextMenuAlignNone.Enable();
      }
      if(elFloat=="left"){
       contextMenuAlignLeft.Disable();
      }else{
       contextMenuAlignLeft.Enable();
      }
      if(elFloat=="right"){
       contextMenuAlignRight.Disable();
      }else{
       contextMenuAlignRight.Enable();
      }

     }


     if(pEls.indexOf("a")>-1){

      var parentA=getFirstAncestor(wysiwygIframe.eventTargetElement,["a"]);
      parentAHref=parentA.href;
      if(parentAHref.indexOf("?template=wysiwyg_upload_download&file=")>-1){
       contextGroups.file.UnHide();
      }else if(parentA.onclick&&(parentA.onclick+"").indexOf("return false")>-1){
       contextMenuHrefOpen.Disable();
       contextGroups.href.UnHide();
      }else{
       contextMenuHrefOpen.Enable();
       contextGroups.href.UnHide();
      }
      parentA=null;

     }

     contextMenu.show(e,el);
    }
   });

  };


  wysiwygIframe.updateMenuState=function(){
   for(var i=0;i<self.menuArray.length;i++){
    var menuItem=self.menuArray[i];
    var menuItemType=menuItem.Type;
    if(menuItemType=="format"){
     var formatblock=this.checkState("formatblock");
     if(formatblock!=null){
      var fin=self.formats.indexOf(formatblock);
      if(fin>-1){
       menuItem.setIndex(fin);
      }else{
       menuItem.setText("No formatting");
      }
     }else{
      menuItem.setText("No formatting");
     }
    }else if(menuItemType=="fontsize"){
     menuItem.setIndex(System.Convert.ToInt(this.checkState("fontsize"))-1);
    }else if(menuItemType=="font"){

    }else if(NoStateCommands.indexOf(menuItemType)==-1){
     var state=this.checkState(menuItemType);
     if(state){
      menuItem.childNodes[0].className=menuItem.SelectedCssClass;
     }else{
      menuItem.childNodes[0].className=menuItem.CssClass;
     }
    }
   }
  };


  wysiwygIframe.getSelectedCells=function(){
   var cells=[];

   if(window.getSelection){
    var selRange=this.getSelection(2).getRangeAt(0);
    var tableEl=getFirstAncestor(selRange.commonAncestorContainer,["table"]);
   }else{
    var selRange=this.getSelection(2).createRange();
    var tableEl=getFirstAncestor(selRange.parentElement(),["table"]);
   }

   var cellRange;

   for(var i=0;i<tableEl.cells.length;i++){

    if(window.getSelection){
     cellRange=this.getSelection(2).getRangeAt(0);
    }else{
     cellRange=this.getSelection(2).createRange();
    }

    cellRange.moveToElementText(tableEl.cells[i]);

    if(selRange.inRange(cellRange)||(selRange.compareEndPoints('StartToStart',cellRange)>-1&&selRange.compareEndPoints('StartToEnd',cellRange)<-1)||(selRange.compareEndPoints('EndToStart',cellRange)>-1&&selRange.compareEndPoints('EndToEnd',cellRange)<-1)){
     cells[cells.length]=tableEl.cells[i];
    }

   }

   return cells;

  };


  wysiwygIframe.checkState=function(val){
   if(val=="justifyleft"){	//IE claims there's no alignment when none is identified
    if(!this.contentWindow.document.queryCommandState("justifyleft")){
     if(!this.contentWindow.document.queryCommandState("justifycenter")&&!this.contentWindow.document.queryCommandState("justifyright")&&!this.contentWindow.document.queryCommandState("justifyfull")){
      return true;
     }
     return false;
    }
    return true;
   }else if(val!="font"&&val!="fontsize"&&val!="formatblock"){
    return this.contentWindow.document.queryCommandState(val);
   }else if(val=="formatblock"){
    var fa;

    if(window.getSelection){
     fa=getFirstAncestor(this.getSelection(2).getRangeAt(0).commonAncestorContainer,self.formats);
    }else{
     var sel=this.getSelection(2).createRange();
     if(sel.parentElement){
      fa=getFirstAncestor(sel.parentElement(),self.formats);
     }
    }
    if(fa!=null){
     return fa.tagName.toLowerCase();
    }
   }else{
    return this.contentWindow.document.queryCommandValue(val);
   }
  };


  wysiwygIframe.stackInner=function(val){
   if(Browser.Name=="Internet Explorer"){
    if(!val){
     val=wysiwygIframe.contentWindow.document.body.innerHTML;
    }

    if(undoStack.length>1){
     if(undoStack[undoStack.length-1]==val){	//don't save connected duplicates
      return;
     }
    }

    undoStack[undoStack.length]=val;
    undoID=undoStack.length-1;
   }
  };


  wysiwygIframe.setState=function(setobj,setobjVal,noStack,selInner){
   this.contentWindow.focus();
   if(setobj=="inserthtml"&&Browser.Name=="Internet Explorer"){
    this.stackInner();
    var sel=this.contentWindow.document.selection.createRange();
    sel.pasteHTML(setobjVal);
    if(!noStack){
     this.stackInner();
    }
    if(selInner){
     sel.moveStart("character",-setobjVal.replace(/<[^>]*>/g,"").length);
     sel.select();
    }
    sel=null;
   }else if((setobj=="redo"||setobj=="undo")&&Browser.Name=="Internet Explorer"){
    if(setobj=="redo"&&undoID>-1&&undoID<undoStack.length-1){
     undoID++;
     this.contentWindow.document.body.innerHTML=undoStack[undoID];
    }else if(setobj=="undo"&&undoID>0){
     if(undoID==(undoStack.length-1)){
      this.stackInner();
     }
     undoID--;
     this.contentWindow.document.body.innerHTML=undoStack[undoID];
    }
   }else if(setobj=="paste"){
    this.EventHandler.Listeners.paste.Fire();
    try{
     this.contentWindow.document.execCommand("paste",false,null);
    }catch(e){
     alert("Please use ctrl+v to paste");
    }
   }else{

    this.stackInner();
    this.contentWindow.document.execCommand(setobj,false,setobjVal);
    this.stackInner();

   }
   this.contentWindow.focus();


  };


  wysiwygIframe.getSelection=function(val){
   if(window.getSelection){
    if(val==null||val==0){
     var sel=this.contentWindow.getSelection();
     if(sel.rangeCount>0){
      var range=sel.getRangeAt(0);
      var clonedSel=range.cloneContents();
      var div=document.createElement("div");
      div.appendChild(clonedSel);
      return div.innerHTML;
      div=null;
     }
    }else{
     return this.contentWindow.getSelection();
    }
   }else{
    if(val==null||val==0){
     return this.contentWindow.document.selection.createRange().htmlText;
    }else if(val==1){
     return this.contentWindow.document.selection.createRange().text;
    }else{
     return this.contentWindow.document.selection;
    }
   }
  };


  wysiwygIframe.fireUp=function(){
   this.parentNode.appendChild(this.resultBox);
   this.contentWindow.document.designMode="on";
   this.Write("");
  };


  wysiwygIframe.getSource=function(toxhtml){
   return this.contentWindow.document.body.innerHTML;
  };


  wysiwygIframe.setSource=function(val){
   this.contentWindow.document.body.innerHTML=val;
  };


  wysiwygIframe.Dump=function(toxhtml){
   this.resultBox.value=this.contentWindow.document.body.innerHTML;
  };


  wysiwygIframe.GetElementById=function(val){
   return this.contentWindow.document.getElementById(val);
  };


  wysiwygIframe.GetDocument=function(val){
   return this.contentWindow.document;
  };


  self.Frame=wysiwygIframe;

  ActiveWYSIWYG=wysiwygIframe;

  return wysiwygIframe;
 }

}

Dropdown=function(){

 var focussed=false;
 var opened=false;

 var div=document.createElement("div");
 
 var resultBox=div.appendChild(document.createElement("input"));
 resultBox.setAttribute("type","hidden");


 /* main events */
 var ev=System.Event.CreateHandler(main);
 ev.EnableDefaultListeners();

 ev.Listeners.mouseover=function(){
  Hover();
 };

 ev.Listeners.mouseout=function(){
  UnHover();
 };

 ev.Listeners.focus=function(){
  focussed=true;
 };


 /* selectbox */
 var selectBox=div.appendChild(document.createElement("div"));

 selectBox.onfocus=function(){
  div.focus();
 };

 selectBox.onblur=function(){
  focussed=false;
  opened=false;
  //main.deFocus();
 };


 /* dropdown box */
 var dropdownBox=document.body.appendChild(document.createElement("div"));



 return div;

};

function addEvent(el,ev_type,funct,before,forceBefore,obj){
 if(ev_type.substring(0,2)=="on"){
  ev_type=ev_type.substring(2);
 }

 if(before==false&&el.EventListenersForceBefore){
  before=true;
 }else{
  if(forceBefore){
   el.EventListenersForceBefore=true;
  }else{
   el.EventListenersForceBefore=false;
  }
 }

 if(!el.EventListeners){
  el.EventListeners=new Object();
 }

 if(!el.EventListenerExecutioner){
  el.EventListenerExecutioner=function(e,ev_t){
   if(this.EventListeners){
    var EventListenerArray=this.EventListeners[ev_t];
    if(EventListenerArray){
     for(var i=0;i<EventListenerArray.length;i++){
      if(obj){
       EventListenerArray[i].call(obj,e);
      }else{
       EventListenerArray[i](e);
      }
     }
    }
   }
  };
 }

 if(!el.EventListeners[ev_type]){
  el.EventListeners[ev_type]=[];
  if(document.addEventListener){
   el.addEventListener(ev_type,function(e){el.EventListenerExecutioner(e,ev_type);},false);
  }else{
   el.attachEvent("on"+ev_type,function(e){el.EventListenerExecutioner(e,ev_type);});
  }
 }

 if(!before){
  el.EventListeners[ev_type].push(funct);
 }else{
  el.EventListeners[ev_type].unshift(funct);
 }
}


function removeEvent(el,ev_type,todo){
 if(el.EventListeners&&el.EventListeners[ev_type]){
  for(var i=0;i<el.EventListeners[ev_type].length;i++){
   if(el.EventListeners[ev_type][i]==todo){
    el.EventListeners[ev_type].splice(i,1);
   }
  }
 }
}


function removeAllEvents(el,ev_type){
 if(el.EventListeners){
  if(ev_type){
   if(ev_type.substring(0,2)=="on"){
    ev_type=ev_type.substring(2);
   }
   el.EventListeners[ev_type]=[];
  }else{
   for(var o in el.EventListeners){
    el.EventListeners[o]=[];
   }
  }
 }
}

window.evalScriptNode=null;


Namespace=function(){
};


Namespace.prototype.namespace=function(namespace){
 this[namespace]=new Namespace();
};


function urlescape(val){
 return escape(val).replace(/\+/g,"%2B");
}


function is_rightclick(e){
 e=e||window.event;
 mbutton=e.button;
 if(mbutton==2){
  return true;
 }else{
  return false;
 }
}


/* function to check if a value equals nothing */
function isNothing(val){
 if(isNull(val)||val==""){
  return true;
 }
 return false;
}


/* function to check if a value equals null */
function isNull(val){
 if(val==null){
  return true;
 }else if(typeof(val)=="object"&&(""+val=="undefined"||""+val=="null")){
  return true;
 }
 return false;
}


function isDate(val){
 return System.Convert.ToBoolean(new Date(val));
}


__ocw_uniqueindex=null;
/* function to return a unique number */
function getUniqueIndex(){
 if(__ocw_uniqueindex==null){
  __ocw_uniqueindex=0;
 }else{
  __ocw_uniqueindex++;
 }
 return __ocw_uniqueindex;
}


var HTMLElement;	//declaration to not make IE complain
if(HTMLElement){
 HTMLElement.prototype.contains=function(el){
  var isParent=false;
  do{
   if(isParent=this==el){
    break;
   }
   el=el.parentNode;
  }
  while (el!=null);
  return isParent;
 }
}


/* function to check if a number is odd */
function isOdd(val){
 if((val%2)>0){
  return true;
 }
 return false;
}


function getFirstChildsChild(el){
 var arr=[];
 for(var i=0;i<el.childNodes.length;i++){
  arr[arr.length]=el.childNodes[i].firstChild;
 }
 return arr;
}


function getFirstConjoinedParent(){
 var checkEl, checkElc, first, firstc;
 var arg=toArray(arguments);

 first=arg[0];
 firstc=first;
 while(firstc.parentNode){

  for(var i=1;i<arg.length;i++){
   checkEl=arg[i];
   checkElc=checkEl;
   while(checkElc.parentNode){

    if(checkElc.parentNode==firstc.parentNode){
     if(arg.length==2){
      return [checkElc.parentNode,firstc,checkElc];
     }
    }
    checkElc=checkElc.parentNode;

   }
  }
  firstc=firstc.parentNode;

 }
}


function getElementsByTagNames(list,obj){
 if(obj==null){
  var obj=document;
 }
 if(typeof(list)=="string"){
  var tagNames=list.split(",");
 }else{
  var tagNames=list;
 }
 var resultArray=new Array();
 for (var i=0;i<tagNames.length;i++) {
  var tags=obj.getElementsByTagName(tagNames[i]);
  for (var j=0;j<tags.length;j++) {
   resultArray.push(tags[j]);
  }
 }
 var testNode=resultArray[0];
 if(!testNode){
  return [];
 }
 if (testNode.sourceIndex) {
  resultArray.sort(function(a,b){return a.sourceIndex-b.sourceIndex;});
 }else if(testNode.compareDocumentPosition){
  resultArray.sort(function(a,b){return 3-(a.compareDocumentPosition(b)&6);});
 }
 return resultArray;
}


function getParentElements(el){
 var p=el;
 var arr=[];
 while(p){
  arr[arr.length]=p;
  p=p.parentNode;
 }
 return arr;
}


function getParentElementNames(el,lower){
 var p=el;
 var arr=[];
 while(p){
  if(p.nodeType==1){
   if(lower){
    arr[arr.length]=p.tagName.toLowerCase();
   }else{
    arr[arr.length]=p.tagName;
   }
  }
  p=p.parentNode;
 }
 return arr;
}


function getElementsByClassName(el,clsName){
 var arr=[];
 var els=el.getElementsByTagName("*");
 for(var i=0;i<els.length;i++){
  if(els[i].className==clsName){
   arr[arr.length]=els[i];
  }
 }
 return arr;
}


function getFirstAncestor(val,types){
 var parentN=val;
 while(parentN){
  if(parentN.nodeType==1){
   if(types.indexOf(parentN.tagName.toLowerCase())>-1){
    return parentN;
   }
  }
  parentN=parentN.parentNode;
 }
}


function onMouseEnter(el,e){
 e=e||window.event;
 if(e.fromElement){
  return !el.contains(e.fromElement);
 }else if(e.relatedTarget){
  return !el.contains(e.relatedTarget);
 }
}


function onMouseLeave(el,e){
 e=e||window.event;
 if(e.toElement){
  return !el.contains(e.toElement);
 }else if(e.relatedTarget){
  return !el.contains(e.relatedTarget);
 }
}


function get_randomhash(hash_len){
 var newhash="";
 while(newhash.length<maxhaslen){
  newhash+=Math.random().toString(16).replace(/0\./g,"");
 }
 return newhash.substring(0,maxhaslen);
}


function insertAfter(newnode,nnode){
 var nnodenext=nnode.nextSibling;
 if(nnodenext){

  /* fix for IE */
  if(nnodenext.parentNode!=nnode.parentNode){
   while(nnodenext.parentNode){
    nnodenext=nnodenext.parentNode;
    if(nnodenext.parentNode==nnode.parentNode){
     break;
    }
   }
  }

  nnode.parentNode.insertBefore(newnode,nnodenext);

 }else{
  nnode.parentNode.appendChild(newnode);
 }
}


function insertBefore(newnode,nnode){
 nnode.parentNode.insertBefore(newnode,nnode);
}


function get_keycode(e){
 e=e||window.event;
 if(Browser.Name=="Netscape"){
  return e.which;
 }else{
  return e.keyCode;
 }
}


function is_ctrl(e){
 e=e||window.event;
 return e.ctrlKey;
}


function is_std_input(e){
 var keyCode=get_keycode(e);
 if(e.ctrlKey||e.altKey||e.shiftKey||keyCode==13||keyCode==9||keyCode==0||keyCode==8||(keyCode>36&&keyCode<41)){
  return true;
 }else{
  return false;
 }
}


function isArray(value){
 if(typeof(value)=="object"&&value!=null){
  if(value.constructor){
   if(value.constructor.toString().indexOf("Array()")>-1){
    return true;
   }
  }
 }
 return false;
}


/* String prototype to return a string without leading/ending whitespace */
String.prototype.trimAll=function(){
 return this.replace(/^[\s]+/,"").replace(/[\s]+$/,"");
};


/* String prototype to return a string without leading/ending spaces */
String.prototype.trim=function(){
 return this.replace(/^[ ]+/,"").replace(/[ ]+$/,"");
};


String.prototype.lpad=function(size,PaddingCharacter){ 
 var dif=size-this.length;
 var s=this;
 if(dif>0){
  for(;dif!=0;dif+=-1){
   s=PaddingCharacter+s;
  }
 }
 return(s);
};


/* extending objects */
function extend(original,source){
 for(property in source){
  original[property]=source[property];
 }
 return original;
}


if(!Array.prototype.unshift){
 Array.prototype.unshift=function(item){
  this[this.length]=null;
  for(var i=1;i<this.length;i++){
   this[i]=this[i-1];
  }
  this[0]=item;
 };
}


if(!Array.prototype.shift){
 Array.prototype.shift=function(){
  var item=this[0];
  for(var i=1;i<this.length;i++){
   this[i-1]=this[i];
  }
  this.pop();
  return item;
 };
}


if(!Array.prototype.equals){
 Array.prototype.equals=function(value){
  if(!value){
   return false;
  }
  var len=this.length;
  if(len!=value.length){
   return false;
  }
  for(var i=0;i<len;i++){
   if(this[i]!=value[i]){
    return false;
   }
  }
  return true;
 };
}


if(!Array.prototype.indexOf){
 Array.prototype.indexOf=function(value,f){
  var i;
  if(isArray(value)&&!f){
   for(var i=0;i<this.length;i++){
    if(this[i].equals(value)){
     return i;
    }
   }
  }else{
   for(var i=0;i<this.length;i++){
    if(this[i]===value){
     return i;
    }
   }
  }
  return -1;
 };
}


/* non prototype handler for arrays that claim to be objects */
function inArray(arr,value){
 var i;
 if(isArray(value)){
  for(var i=0;i<arr.length;i++){
   if(arr[i].equals(value)){
    return i;
   }
  }
 }else{
  for(var i=0;i<arr.length;i++){
   if(arr[i]===value){
    return i;
   }
  }
 }
 return -1;
}


/* to array converter for arrays that claim to be objects */
function toArray(arr){
 var narr=[];
 for(var i=0;i<arr.length;i++){
  narr[narr.length]=arr[i];
 }
 return narr;
}

//version=0.5

function Grid(){

 var container=document.createElement("div");

 container.SortedIndex=null;
 container.PreviousSortedElement=null;
 container.SortedElement=null;


 container.HoverRow=null;
 container.SelectedRow=null;


 var ev=System.Event.CreateHandler(container);
 ev.EnableListener("sort");
 ev.EnableListener("sortasc");
 ev.EnableListener("sortdesc");

 container.HeaderTable=container.appendChild(document.createElement("table"));
 container.HeaderTable.cellSpacing=0;
 container.HeaderTable.cellPadding=0;

 container.HeaderThead=container.HeaderTable.appendChild(document.createElement("thead"));

 container.HeaderTable.addRow=function(row){
  container.HeaderThead.appendChild(row);
 };

 container.BodyContainer=container.appendChild(document.createElement("div"));

 container.BodyTable=container.BodyContainer.appendChild(document.createElement("table"));
 container.BodyTable.cellSpacing=0;
 container.BodyTable.cellPadding=0;


 container.GetRows=function(){
  return this.BodyTable.rows;
 };


 container.Destroy=function(){

  if(this.DragObject){

   this.DragObject.Destroy();
   this.DragObject=null;

  }

  var hnodes=this.HeaderThead.childNodes;
  for(var i=0;i<hnodes.length;i++){
   for(var j=0;j<hnodes[i].childNodes.length;j++){
    System.Element.Destroy(hnodes[i].childNodes[j].firstChild);
   }
  }

  System.Event.DestroyHandler(this);

  this.HeaderThead=null;

  this.HeaderTable.addRow=null;
  this.HeaderTable=null;


  for(var i=0;i<this.BodyTable.childNodes.length;i++){

   this.BodyTable.childNodes[i].ValueArray=null;
   this.BodyTable.childNodes[i].addRow=null;
   this.BodyTable.childNodes[i].onmouseup=null;
   this.BodyTable.childNodes[i].ondblclick=null;
   this.BodyTable.childNodes[i].onclick=null;

  }

  this.BodyTable=null;


  this.LoadAllRows=null;
  this.Body=null;
  this.EnableSort=null;
  this.EnableShuffle=null;
  this.EnableResize=null;
  this.Row=null;
  this.Column=null;
  this.Sort=null;
  this.GetRows=null;


  if(this.BodyContainer.RowCache){

   while(this.BodyContainer.RowCache.length>0){

    this.BodyContainer.RowCache[this.BodyContainer.RowCache.length-1]=null;
    this.BodyContainer.RowCache.pop();

   }

   this.BodyContainer.RowCache=null;

  }

  this.BodyContainer.onscroll=null;

  this.BodyContainer=null;

  ev=null;

  this.Destroy=null;
  container=null;

 };


 container.CancelSort=false;


 container.EnableSort=function(el){

  el.SortSide=0;

  el.onclick=function(){

   if(!container.CancelSort){

    if(this.SortSide!=0&&container.SortedElement!=null&&container.SortedElement!=this){
     container.Sort(inArray(getFirstChildsChild(this.parentNode.parentNode),this),this.SortSide);
    }else if(this.SortSide==0||this.SortSide==1){

     container.Sort(inArray(getFirstChildsChild(this.parentNode.parentNode),this));
     this.SortSide=-1;

    }else{

     container.Sort(inArray(getFirstChildsChild(this.parentNode.parentNode),this),1);
     this.SortSide=1;

    }

   }else{
    container.CancelSort=false;
   }

  };

 };


 var isResizing=false;


 container.EnableShuffle=function(el){

  if(!this.DragObject){
   this.DragObject=new cDrag();
  }

  this.DragObject.createFloatBox(el,null,false,true,function(){if(!isResizing){return true;}});

  el.ondragstart=function(){return false;};
  el.onselectstart=function(){return false;};

  this.DragObject.createDropBox(el,function(e){

   var dragEl=container.DragObject.DragItem();
   if(dragEl!=el){

    e=e||window.event;

    var elPos=get_mouseElementPosition(e,"x",el,true);

    //get the original index
    var index=dragEl.parentNode.cellIndex;
    var nindex=el.parentNode.cellIndex;

    //move the header cols
    if(elPos>50){
     insertAfter(dragEl.parentNode,el.parentNode);
    }else{
     insertBefore(dragEl.parentNode,el.parentNode);
    }

    //loop all records and move the cols
    var rows=container.GetRows(), row;

    for(var i=0;i<rows.length;i++){

     row=rows[i];

     if(elPos>50){
      insertAfter(row.childNodes[index],row.childNodes[nindex]);
     }else{
      insertBefore(row.childNodes[index],row.childNodes[nindex]);
     }

    }

   }
  });


 };


 container.EnableResize=function(el){

  var ev=System.Event.CreateHandler(el);

  System.Event.CreateHandler(document.body).EnableListener('mouseup');
  document.body.EventHandler.EnableListener('mousemove');

  var fitForResize=false, leftElement, rightElement, mouseStartPos, lastDiff=0;

  ev.EnableListener("mousemove").Append(function(e){

   if(!isResizing){

    var elPos=get_mouseElementPosition(e,"x",this);

    if(elPos<5||elPos>(this.offsetWidth-4)){

     if(elPos<5){

      leftElement=this.parentNode.previousSibling;
      rightElement=this;
      if(leftElement){
       leftElement=leftElement.firstChild;
      }else{
       return;
      }

     }else{

      leftElement=this;
      rightElement=this.parentNode.nextSibling;
      if(rightElement){
       rightElement=rightElement.firstChild;
      }else{
       return;
      }

     }

     this.style.cursor="e-resize";
     fitForResize=true;

    }else{

     this.style.cursor="default";
     fitForResize=false;

    }

   }

  });


  ev.EnableListener("mousedown").Append(function(e){

   if(!isResizing&&fitForResize){

    if(typeof(this.SortSide)=="number"){
     container.CancelSort=true;
    }

    isResizing=true;

    rightElement.elStartWidth=System.Convert.ToInt(System.Element.GetStyle(rightElement,'width'));
    leftElement.elStartWidth=System.Convert.ToInt(System.Element.GetStyle(leftElement,'width'));
    mouseStartPos=get_mousePosition(e,'x');
    lastDiff=0;

    var moveHandler=function(e){


     var currentLastDiff=get_mousePosition(e,'x')-mouseStartPos;

     var leftWidth=leftElement.elStartWidth+currentLastDiff;
     var rightWidth=rightElement.elStartWidth-currentLastDiff;

     if(leftWidth>5&&rightWidth>5){

      leftElement.style.width=leftWidth+'px';
      rightElement.style.width=rightWidth+'px';
      lastDiff=currentLastDiff;

     }

    };

    document.body.EventHandler.Listeners.mousemove.Append(moveHandler);

    document.body.EventHandler.Listeners.mouseup.Append(function(){

     this.EventHandler.Listeners.mousemove.Remove(moveHandler);

     if(lastDiff!=0){

      //loop all records and change their colsize
      var index=leftElement.parentNode.cellIndex, cell1, cell2;

      var rows=container.GetRows();

      for(var i=0;i<rows.length;i++){

       cell1=rows[i].childNodes[index].firstChild;
       cell2=rows[i].childNodes[index+1].firstChild;

       cell1.style.width=(System.Convert.ToInt(System.Element.GetStyle(cell1,"width"))+lastDiff)+"px";
       cell2.style.width=(System.Convert.ToInt(System.Element.GetStyle(cell2,"width"))-lastDiff)+"px";

      }

     }

     isResizing=false;

    },false,true);

   }

  });

  ev=null;

 };


 container.Body=function(){

  var b=container.BodyTable.appendChild(document.createElement("tbody"));
  b.ValueArray=[];

  b.addRow=function(row){
   var rowIndex=this.appendChild(row).sectionRowIndex;

   /* opera enz... */
   if(rowIndex==undefined){
    rowIndex=inArray(this.parentNode.rows,row);
   }


   this.ValueArray[this.ValueArray.length]=[rowIndex].concat(row.ValueArray);
   row.ValueArray=null;
   row=null, rowIndex=null;
  };

  return b;

 };


 container.Row=function(){
  var row=document.createElement("tr");
  row.ValueArray=[];
  var arg;
  for(var i=0;i<arguments.length;i++){
   arg=arguments[i];
   row.ValueArray[i]=arg.SortValue;
   row.appendChild(arg.parentNode);
  }
  arg=null;
  return row;
 };


 container.Column=function(val,sortval){
  var col=document.createElement("td").appendChild(document.createElement("div"));
  col.innerHTML=val;
  col.SortValue=sortval;
  return col;
 };


 container.Sort=function(colIndex,side,sort){

  if(colIndex==null){
   colIndex=0;
  }

  this.SortedIndex=colIndex;
  this.PreviousSortedElement=this.SortedElement;
  this.SortedElement=this.HeaderThead.firstChild.childNodes[colIndex].firstChild;

  if(sort==null){
   sort=true;
  }

  colIndex++;

  if(sort==true){
   var tbodyArray=container.BodyTable.childNodes;
   var tbody=null;
   var tbodyClone=null;
   var table=container.BodyTable;

   for(var i=0;i<tbodyArray.length;i++){
    tbody=tbodyArray[i];
    tbodyArr=tbody.ValueArray;

    var tbodyArrSorted=tbodyArr.sort(function(a,b){
     a=a[colIndex];
     b=b[colIndex];
     return a>b?1:a<b?-1:0;
    });

    if(side==1){
     tbodyArrSorted.reverse();
    }

    var nrowArr=[];
    for(var j=0;j<tbodyArrSorted.length;j++){
     nrowArr[nrowArr.length]=tbody.childNodes[tbodyArrSorted[j][0]];
     tbodyArrSorted[j][0]=j;
    }

    for(var j=0;j<nrowArr.length;j++){
     tbody.appendChild(nrowArr[j]);
    }

    nrowArr=null;
    tbody.ValueArray=tbodyArrSorted;

    if(side==1){
     ev.Listeners.sortasc.Fire(null,this);
    }else{
     ev.Listeners.sortdesc.Fire(null,this);
    }
    ev.Listeners.sort.Fire(null,this);

   }

  }

 };


 return container;

}

var User=new function(){

 //this.Name=null;
 //this.IsAuthenticated=false;
 //this.IsAdministrator=false;

}


function ocw_createErrorDiv(){
 if(!document.getElementById('__ocw_errorDiv')){
  var errorDiv=document.createElement("div");
  errorDiv.style.position="absolute";
  errorDiv.style.zIndex=2000;
  errorDiv.style.display="none";
  errorDiv.id='__ocw_errorDiv';
  document.body.appendChild(errorDiv);
 }
}


ocw_errorParsed=false;

function ocw_parseErrorDiv(error_data,el){
 if(!ocw_errorParsed){
  ocw_errorParsed=true;
  ocw_createErrorDiv();
  ocw_error_divved=el;

  var errorDiv=document.getElementById("__ocw_errorDiv");

  errorDiv.style.left=System.Element.GetXPosition(el)+"px";
  errorDiv.style.top=System.Element.GetYPosition(el)+el.offsetHeight+"px";

  errorDiv.innerHTML="<div style='position:relative;top:1px;left:14px;background:url(img/error/pointer_up.gif);width:15px;height:16px;font-size:1px;'>&nbsp;</div><table border='0' cellspacing='0' cellpadding='0'><tr><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_left_top.gif);'></td><td style='height:5px;font-size:1px;background:#FFFFE1;border-top:1px solid #000000;'>&nbsp;</td><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_right_top.gif);'></td></tr><tr><td style='width:5px;font-size:1px;background:#FFFFE1;border-left:1px solid #000000;'>&nbsp;</td><td style='background:#FFFFE1;font-size:11px;font-family:verdana;padding:4px;' id='__ocw_errorDiv_inner'>"+error_data+"</td><td style='width:5px;font-size:1px;background:#FFFFE1;border-right:1px solid #000000;'>&nbsp;</td></tr><tr><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_left_bottom.gif);'></td><td style='height:5px;font-size:1px;background:#FFFFE1;border-bottom:1px solid #000000;'>&nbsp;</td><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_right_bottom.gif);'></td></tr></table>";

  errorDiv.style.display="";
  var winh=document.documentElement.offsetHeight;
  var hscrll=document.body.scrollTop;
  elHeight=errorDiv.offsetHeight;

  if(winh+hscrll<System.Element.GetYPosition(errorDiv)+hscrll+elHeight){
   errorDiv.style.top=(System.Element.GetYPosition(el)-elHeight)+"px";

   errorDiv.innerHTML="<table border='0' cellspacing='0' cellpadding='0'><tr><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_left_top.gif);'></td><td style='height:5px;font-size:1px;background:#FFFFE1;border-top:1px solid #000000;'>&nbsp;</td><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_right_top.gif);'></td></tr><tr><td style='width:5px;font-size:1px;background:#FFFFE1;border-left:1px solid #000000;'>&nbsp;</td><td style='background:#FFFFE1;font-size:11px;font-family:verdana;padding:4px;' id='__ocw_errorDiv_inner'>"+error_data+"</td><td style='width:5px;font-size:1px;background:#FFFFE1;border-right:1px solid #000000;'>&nbsp;</td></tr><tr><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_left_bottom.gif);'></td><td style='height:5px;font-size:1px;background:#FFFFE1;border-bottom:1px solid #000000;'>&nbsp;</td><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_right_bottom.gif);'></td></tr></table><div style='position:relative;top:-1px;left:14px;background:url(img/error/pointer_down.gif);width:15px;height:16px;font-size:1px;'>&nbsp;</div>";

  }

 }
}


function ocw_closeErrorDiv(force){
 if((!ocw_errorParsed)||force){
  ocw_createErrorDiv();
  ocw_errorParsed=false;
  document.getElementById('__ocw_errorDiv').style.display="none";
 }
}

function adjust_to_pos(e,type,left,top,pos_obj){
 pos_obj.style.position="absolute";
 var Ymouse=get_mousePosition(e,"y");
 var Xmouse=get_mousePosition(e,"x");
 var hscrll=document.documentElement.scrollTop;
 var wscrll=document.documentElement.scrollLeft;
 if(type==0){
  pos_obj.style.top=hscrll+top+'px';
  pos_obj.style.left=wscrll+left+'px';
 }else if(type==1){
  pos_obj.style.top=hscrll+Ymouse+top+'px';
  pos_obj.style.left=wscrll+Xmouse+left+'px';
 }
}


function move_background(e,move_obj){
 move_obj.style.backgroundPosition=get_mouseElementPosition(e,"x",move_obj)/(move_obj.offsetWidth/100)+"% "+get_mouseElementPosition(e,"y",move_obj)/(move_obj.offsetHeight/100)+"%";
}


function get_mouseElementPosition(e,mouse_x_y,el,perc){
 e=e||window.event;
 if(mouse_x_y=="x"){
  var pos=get_mousePosition(e,'x')-System.Element.GetXPosition(el);
  if(perc){
   return pos/(el.offsetWidth/100);
  }
  return pos;
 }else{
  var pos=get_mousePosition(e,'y')-System.Element.GetYPosition(el);
  if(perc){
   return pos/(el.offsetHeight/100);
  }
  return pos;
 }
}


function get_mousePosition(e,mouse_x_y,toScroll){
 e=e||window.event;
 if(toScroll){
  var hscrll=document.documentElement.scrollTop;
  var wscrll=document.documentElement.scrollLeft;
 }else{
  var hscrll=0;
  var wscrll=0;
 }
 if(mouse_x_y=="x"){
  if(e.clientX){
   return e.clientX+wscrll
  }else{
   return e.clientX+wscrll;
  }
 }else{
  if(e.clientY){
   return e.clientY+hscrll;
  }else{
   return e.clientY+hscrll;
  }
 }
}

System=new Namespace();

/* enable XMLHttpRequest for IE */
if(!window.XMLHttpRequest){
 window.XMLHttpRequest=function(){
  var types=["Microsoft.XMLHTTP","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP"];
  for(var i=0;i<types.length;i++){
   try{
    return new ActiveXObject(types[i]);
   }catch(e){}
  }
  window.XMLHttpRequest=null;
  return null;
 };
}


System.namespace("Ajax");


System.Ajax.GetPostString=function(el){

 var formElements=[el.getElementsByTagName("input"),el.getElementsByTagName("textarea"),el.getElementsByTagName("select")];
 var postString=null;

 for(var i=0;i<formElements.length;i++){

  for(var j=0;j<formElements[i].length;j++){

   formItem=formElements[i][j];

   if(formItem.type.toLowerCase()=="radio"){
    if(!formItem.checked){
     continue;
    }
   }

   if(postString){
    postString+="&"+formItem.name+"="+urlescape(formItem.value);
   }else{
    postString=formItem.name+"="+urlescape(formItem.value);
   }

  }

 }

 return postString;

};


System.Ajax.Request=function(loc,async,el,header,method){

 var request=new XMLHttpRequest();
 var waitStartTime;

 var ev=System.Event.CreateHandler(this);
 ev.EnableListener("statechange");
 ev.EnableListener("stateready");

 //get the current time in ms, to ensure fresh data
 var d=new Date();
 var time=d.getTime();
 d=null;

 var postString;

 if(!method){
  method="GET";
 }

 if(el){
  postString=System.Ajax.GetPostString(el);

  if(el.method){
   method=el.method;
  }

  if(!loc){
   loc=el.action;
  }

 }

 if(async==undefined){
  async=true;
 }

 if(typeof(loc)=="object"&&loc.ToString){
  loc=loc.ToString();
 }else{
  loc=new System.URL(loc).ToString();
 }

 request.open(method,loc,async);

 this.Response={};

 var self=this;

 var rStateChange=function(e){

  self.ReadyState=request.readyState;

  if(request.readyState==4){
   self.Response.Text=request.responseText;
  }

  self.EventHandler.Listeners.statechange.Fire(e,self);

  if(request.readyState==4){

   //set transfertime
   var d=new Date();
   self.Response.WaitTime=d.getTime()-waitStartTime;
   d=null;

   self.EventHandler.Listeners.stateready.Fire(e,self);

   //clean up
   System.Event.DestroyHandler(self);
   self=null;
   request.onreadystatechange=function(){};
   request=null;

  }


 };


 if(async){
  request.onreadystatechange=rStateChange;
 }


 if(header){

  var header_spl=header.split(":");
  request.setRequestHeader(header_spl[0],header_spl[1]);
  header_spl=null;

 }else if(el){
  request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 }


 this.Send=function(pString){

  //init transfer time
  var d=new Date();
  waitStartTime=d.getTime();
  d=null;

  if(pString){
   postString=pString;
  }

  request.send(postString);

  if(!async){
   rStateChange();
  }

 };

};


System.Ajax.CreateContainer=function(el){

 System.Event.CreateHandler(el).EnableListener("statechange");
 System.Event.CreateHandler(el).EnableListener("stateready");
 System.Event.CreateHandler(el).EnableListener("destroy");


 el.Destroy=function(e){

  this.EventHandler.Listeners.statechange.Fire(e,this);
  this.EventHandler.Listeners.destroy.Fire(e,this);
  System.Element.Destroy(this);
  this.BaseURL=null;
  this.Reload=null;
  this.Post=null;
  this.Response=null;
  this.SetLocation=null;
  this.SetText=null;
  this.Destroy=null;
  this.IsAjaxContainer=null;

 };


 el.IsAjaxContainer=true;


 el.SetText=function(val){
  this.innerHTML=val;
 };


 el.Reload=function(){
  this.SetLocation(this.Location);
 };


 el.Response={};


 el.Post=function(el,async){

  if(el.tagName=="FORM"){
   this.SetLocation(el.action,async,"Content-Type:application/x-www-form-urlencoded",el);
  }else{
   window.alert("NOT A FORMNODE!");
  }

 };


 el.BaseURL=new System.URL();


 el.SetLocation=function(loc,async,header,formEl,method,pString){


  //set the document hash
  if(el.id){
   window.location.hash=el.id+".Location="+loc;
  }

  //init total time
  var d=new Date();
  var totalStartTime=d.getTime();
  d=null;

  if(async==undefined){
   async=true;
  }

  this.Location=loc;

  //create an url object to work with
  var url=new System.URL(loc);
  url.QueryString.MakeUnique();

  url.Union(this.BaseURL,true);

  var req=new System.Ajax.Request(url.ToString(),async,formEl,header);

  url=null;


  req.EventHandler.Listeners.statechange.Append(function(e){


   el.ReadyState=this.ReadyState;
   el.EventHandler.Listeners.statechange.Fire(e,el);

  });


  req.EventHandler.Listeners.stateready.Append(function(e){

   el.Response.WaitTime=this.Response.WaitTime;

   //init parsetime
   var d=new Date();
   var parseStartTime=d.getTime();
   d=null;


   var rText=el.Response.Text=this.Response.Text;


   //get & remove script tags before evalling
   var scriptArray=[];

   rText=rText.replace(/<script[^>]*>((?:\r|\n|.)*?)<\/script>/gi,function(val,inner){

    scriptArray[scriptArray.length]=inner;
    return "";

   });


   el.innerHTML="<div style=\"display:none;\">&nbsp;</div>"+rText;	//http://msdn.microsoft.com/en-us/library/ms533897.aspx -> first comment

   rText=null;


   //run scripts
   for(var i=0;i<scriptArray.length;i++){

    (function(){
     eval(scriptArray[i]);
    })();

   }

   scriptArray=null;


   System.Element.EvaluateScriptNodes(el);


   //set parsetime
   var d=new Date();
   el.Response.ParseTime=d.getTime()-parseStartTime;
   d=null;


   //set totaltime
   var d=new Date();
   el.Response.TotalTime=d.getTime()-totalStartTime;
   d=null;

   el.EventHandler.Listeners.stateready.Fire(e,el);

   if(window.CollectGarbage){
    window.CollectGarbage();
   }

  });

  req.Send(pString);

 };


 return el;

};

System.Convert=new function(){

 this.ToBoolean=function(val){
  if(val==true||val=="true"||val=="yes"||val=="y"||val=="1"||val>0){
   return true;
  }
  return false;
 };


 this.ToInt=function(val){
  if(typeof(val)=="string"){
   var rval=val.replace(/^0*/,"");
   if(rval==""){
    return 0;
   }else{
    return parseInt(rval);
   }
  }else if(typeof(val)=="number"||typeof(val)=="object"){
   return parseInt(val);
  }else if(typeof(val)=="boolean"){
   if(val==true){
    return 1;
   }else{
    return 0;
   }
  }
 };


 this.ToFloat=function(val){
  return parseFloat(val);
 };


 this.Round=function(val,dec){
  if(typeof(val)=="string"||typeof(val)=="number"){
   if(!isNaN(val)){

    var rPow=Math.pow(10,dec);
    return Math.round(val*rPow)/rPow;

   }
  }else if(typeof(val)=="boolean"){
   if(val==true){
    return 1;
   }else{
    return 0;
   }
  }
 };


 this.ToChar=this.ToString;


 this.ToString=function(val,allowNull){
  if((allowNull==null||allowNull)&&isNull(val)){
   return null;
  }
  return ""+val;
 };


 this.DateFormat="dd/mm/yyyy";
 this.TimeFormat="hh:mm:ss";
 this.DateServerSynch=false;


 this.ToDateString=function(val){
  if(this.DateServerSynch){
   yi=this.DateFormat.indexOf("yyyy");
   mi=this.DateFormat.indexOf("mm");
   di=this.DateFormat.indexOf("dd");
   var d=new Date(val.substring(yi,yi+4),Convert.ToInt(val.substring(mi,mi+2))-1,val.substring(di,di+2));
  }else{
   var d=new Date(val);
  }
  return this.DateFormat.replace("dd",Convert.ToString(d.getDate()).lpad(2,"0")).replace("mm",Convert.ToString(d.getMonth()+1).lpad(2,"0")).replace("yyyy",d.getFullYear());
 };


 this.ToTimeString=function(val){
  var d=new Date(val);
  return this.TimeFormat.replace("hh",Convert.ToString(d.getHours()).lpad(2,"0")).replace("mm",Convert.ToString(d.getMinutes()).lpad(2,"0")).replace("ss",Convert.ToString(d.getSeconds()).lpad(2,"0"));
 };


 this.ToDateTimeString=function(val){
  return this.ToDateString(val)+" "+this.ToTimeString(val);
 };


 this.ToDateOffset=function(val){
  if(this.DateServerSynch){
   yi=this.DateFormat.indexOf("yyyy");
   mi=this.DateFormat.indexOf("mm");
   di=this.DateFormat.indexOf("dd");
   var valspace=val.indexOf(" ");
   if(valspace>-1){
    tval=val.substring(valspace+1);
    thi=this.TimeFormat.indexOf("hh");
    tmi=this.TimeFormat.indexOf("mm");
    tsi=this.TimeFormat.indexOf("ss");
    var d=new Date(val.substring(yi,yi+4),Convert.ToInt(val.substring(mi,mi+2))-1,val.substring(di,di+2),tval.substring(thi,thi+2),tval.substring(tmi,tmi+2),tval.substring(tsi,tsi+2));
   }else{
    var d=new Date(val.substring(yi,yi+4),Convert.ToInt(val.substring(mi,mi+2))-1,val.substring(di,di+2));
   }
  }else{
   var d=new Date(val);
  }
  return d.getTime();
 };

 //number, string, boolean, object, function, undefined

};

System.namespace("Effects");

System.Effects.ShiftOpacity=function(el,newOpacity,timeFrame,onComplete){

 var currentOpacity=System.Element.GetOpacity(el);
 var opacityDifference=newOpacity-currentOpacity;
 var Steps=timeFrame/40;
 var opacityStep=opacityDifference/Steps;

 if(el._OpacityInterval){
  window.clearInterval(el._OpacityInterval);
 }

 el._OpacityInterval=window.setInterval(function(){

  currentOpacity+=opacityStep;
  if((opacityDifference<1&&currentOpacity<newOpacity)||(opacityDifference>1&&currentOpacity>newOpacity)||currentOpacity==newOpacity){

   System.Element.SetOpacity(el,newOpacity);
   window.clearInterval(el._OpacityInterval);
   el._OpacityInterval=null;

   if(typeof(onComplete)=="function"){
    onComplete();
   }

  }else{
   System.Element.SetOpacity(el,currentOpacity);
  }

 },40);

};


System.Effects.Morph=function(el,newStyle,timeFrame,onComplete){


 //if newStyle is a string, objectify
 if(typeof(newStyle)=="string"){

  var newStyleSplit=newStyle.split(";"), newStyleSplitSplit;
  newStyle={};

  for(var i=0;i<newStyleSplit.length;i++){

   newStyleSplitSplit=newStyleSplit[i].split(":");
   newStyle[newStyleSplitSplit[0].trimAll()]={
    end:newStyleSplitSplit[1].trimAll(),
    step:1
   };

  }

 }else{

  //loop all items in newStyle, and set property end to the given value
  for(var i in newStyle){

   if(typeof(newStyle[i])!="object"){

    newStyle[i]={
     end:newStyle[i],
     step:1
    };

   }

  }

 }


 //clear any existing morhps on this element
 if(el._MorphInterval){
  window.clearInterval(el._MorphInterval);
 }


 //set an interval that will execute the work for us
 el._MorphInterval=window.setInterval(function(){


  //loop all items in newStyle, to morph them
  for(var i in newStyle){

   newStyle[i]._resultStepping+=newStyle[i].step;	//up the stepping

   //morph
   switch(i){

    case "width":
     el.style.width=newStyle[i]._resultStepping;
     break;

   }


  }


/*

  if(done){

   //final morph here
   window.clearInterval(el._MorphInterval);
   el._MorphInterval=null;

   if(typeof(onComplete)=="function"){
    onComplete();
   }

  }else{
   //morph here
  }
*/


 },40);


};

System.namespace("Element");


System.Element.BlockLevelTagNames=["address","blockquote","center","dir","div","dl","fieldset","form","h1","noscript","ol","p","pre","table","ul"];


System.Element.EvaluateScriptNodes=function(evalScriptNode,deep){

 var onode=window.evalScriptNode;
 window.evalScriptNode=evalScriptNode;

 var processedAllScriptNodes=false;

 while(!processedAllScriptNodes){

  //toArray cuts the reference to getElementsByTagName
  var scriptTags=toArray(evalScriptNode.getElementsByTagName("script"));


  evalScriptStopBubble=false;

  processedAllScriptNodes=true;


  for(var i=0;i<scriptTags.length;i++){

   if(!evalScriptStopBubble&&!scriptTags[i].__evalled){

    //give script tags their own scope
    (function(){
     eval(scriptTags[i].innerHTML);
    })();

    scriptTags[i].__evalled=true;

    if(deep){
     processedAllScriptNodes=false;
    }

   }
  }



 }

 window.evalScriptNode=onode;

 scriptTags=null;
};


System.Element.DestroyEventProperties=function(obj){

 System.Event.DestroyHandler(obj);

 for(var i in obj){
  if(i.substring(0,2)=="on"){
   obj[i]=null;
  }
 }

 obj=null;

};


System.Element.Destroy=function(obj){

 this.DestroyEventProperties(obj);

 if(obj.parentNode){
  obj.parentNode.removeChild(obj);
 }

 //prevent psuedo leak
 if(typeof(obj.outerHTML)!=="undefined"){
  obj.outerHTML="";
 }

 obj=null;

};


System.Element.DestroyChilds=function(obj){

 var deleteem=function(node){

  if(node){
   var childNode;

   for(var i=node.childNodes.length;i>=0;i--){

    childNode=node.childNodes[i];

    if(childNode.hasChildNodes()){
     deleteem(childNode);
    }

    System.Element.Destroy(childNode);

    childNode=null;

   }
  }

 };


 deleteem(obj);

 deleteem=null;

};


System.Element.AddClass=function(el,className){

 var preClassNames=el.className;
 if(preClassNames){

  var preClassNamesSplit=preClassNames.split(" ");
  if(preClassNamesSplit.indexOf(className)==-1){
   el.className=preClassNames+" "+className;
  }

 }else{
  el.className=className;
 }

};


System.Element.RemoveClass=function(el,className){

 var preClassNames=el.className;
 if(preClassNames){

  var preClassNamesSplit=preClassNames.split(" ");
  var classNameIndex=preClassNamesSplit.indexOf(className);

  if(classNameIndex>-1){

   preClassNamesSplit.splice(classNameIndex,1);
   el.className=preClassNamesSplit.join(" ");

  }

 }

};


System.Element.GetMouseXPosition=function(e,mouse_x_y,el,perc){
 e=e||window.event;
 var pos=get_mousePosition(e,'x')-System.Element.GetXPosition(el);
 if(perc){
  return pos/(el.offsetWidth/100);
 }
 return pos;
};


System.Element.GetMouseYPosition=function(e,mouse_x_y,el,perc){
 e=e||window.event;
 var pos=get_mousePosition(e,'y')-System.Element.GetYPosition(el);
 if(perc){
  return pos/(el.offsetHeight/100);
 }
 return pos;
};


System.Element.GetOpacity=function(el){
 if(typeof(el._Opacity)=="number"){
  return el._Opacity;
 }else{
  return 100;
 }
};


System.Element.SetOpacity=function(el,alpha){
 if(Browser.Name=="Internet Explorer"){

/*	doesn't work whenever a element has no css defined alpha, and the below fires twice
  var filter=el.parentNode?el.filters.alpha||el.filters["DXImageTransform.Microsoft.Alpha"]:false;
  if(filter){
   filter.opacity=alpha;
  }else{
   el.style.filter=el.style.filter+" alpha(opacity="+alpha+")";
  }
*/

  el.style.filter="alpha(opacity="+alpha+")";

 }else{

  el.style.KHTMLOpacity=alpha/100;
  el.style.MozOpacity=alpha/100;
  el.style.opacity=alpha/100;

 }
 el._Opacity=alpha;
};


System.Element.GetStyle=function(el,val){

 if(document.defaultView&&document.defaultView.getComputedStyle){
  return document.defaultView.getComputedStyle(el,"").getPropertyValue(val);
 }else if(el.currentStyle){

  val=val.replace(/\-(\w)/g,function(strMatch,p1){
   return p1.toUpperCase();
  });
  return el.currentStyle[val];

 }

};


System.Element.GetHeight=function(el){
 return el.offsetHeight;
};


System.Element.GetWidth=function(el){
 return el.offsetWidth;
};


System.Element.GetXPosition=function(el){

 //IE again...
 try{
  el.offsetParent;
 }catch(e){
  return null;
 }

 var elLeft=0;

 if(el.offsetParent){
  var elParent;
  elLeft=el.offsetLeft;
  while(el.offsetParent){
   elParent=el.offsetParent;
   elLeft+=elParent.offsetLeft;
   el=elParent;
  }
 }else if(el.x){
  elLeft=el.x;
 }
 return elLeft;
};


System.Element.GetYPosition=function(el,includeScrollPos){

 //IE again...
 try{
  el.offsetParent;
 }catch(e){
  return null;
 }

 var elTop=0;
 if(el.offsetParent){
  var elParent;
  elTop=el.offsetTop;
  while(el.offsetParent){
   elParent=el.offsetParent;
   elTop+=elParent.offsetTop-elParent.scrollTop;
   if(includeScrollPos){
    elTop+=elParent.scrollTop;
   }
   el=elParent;
  }
 }else if(el.y){
  elTop=el.y;
 }
 return elTop;
};

System.namespace("Event");


System.Event.Get=function(e){
 var ev=e||window.event;
 if(!ev){
  var c=this.Get.caller;
  while(c){
   ev=c.arguments[0];
   if(ev&&Event==ev.constructor){
    break;
   }
   c=c.caller;
  }
 }
 return ev;
};


System.Event.CancelBubble=function(e){
 e=e||window.event;
 if(e.preventDefault||e.stopPropagation){
  e.preventDefault();
  e.stopPropagation();
 }else{
  e.returnValue=false;
 }
 e.cancelBubble=true;
 return false;
};


System.Event.DestroyHandler=function(obj){

 var i=null;

 if(obj&&obj.EventHandler){

  i=obj.EventHandler.Destroy();
  obj.EventHandler=null;

 }

 obj=null;
 return i;

};


/* the real eventlistener objects */
System.Event.EventListener=function(){

 this.EventListeners=[];
 this.Groups={};

};


System.Event.EventListener.prototype.Destroy=function(){

 //drop listeners
 var EventListenerArray=this.EventListeners;

 var j=EventListenerArray.length;	//drop counter

 for(var i=EventListenerArray.length-1;i>=0;i--){

  EventListenerArray[i]=null;
  EventListenerArray.pop();

 }


 //drop groups
 var GroupArray=this.Groups;

 for(var i in GroupArray){

  j+=GroupArray[i].Destroy();
  GroupArray[i]=null;
  delete GroupArray[i];

 }

 return j;

};


System.Event.EventListener.prototype.Fire=function(e,obj){

 //fire listeners
 var EventListenerArray=this.EventListeners;
 var currentLength;

 for(var i=0;i<EventListenerArray.length;i++){

  currentLength=EventListenerArray.length;

  if(currentLength<1){
   break;
  }

  if(obj){
   EventListenerArray[i].call(obj,e);
  }else{
   EventListenerArray[i](e);
  }

  //check for reseeds
  if(EventListenerArray.length<currentLength){
   i=i-(currentLength-EventListenerArray.length);
  }

 }


 //fire groups
 var GroupArray=this.Groups;

 for(var i in GroupArray){
  GroupArray[i].Fire(e,obj);
 }

};


System.Event.EventListener.prototype.Append=function(funct,before,runOnce){
 if(before){
  this.EventListeners.unshift(funct);
 }else{
  this.EventListeners[this.EventListeners.length]=funct;
 }

 if(runOnce){
  var self=this;
  this.EventListeners[this.EventListeners.length]=function(){
   var tfunct=self.EventListeners.indexOf(funct);

   self.EventListeners[tfunct]=null;
   self.EventListeners[tfunct+1]=null;

   self.EventListeners.splice(tfunct,2);	//remove the actual function and this function
   funct=null;self=null;
  };
 }
};


System.Event.EventListener.prototype.CreateGroup=function(name){

 if(typeof(name)=="object"){

  if(!name.__EventUniqueIdent){
   name=name.__EventUniqueIdent=getUniqueIndex();
  }else{
   name=name.__EventUniqueIdent;
  }
 }

 if(!this.Groups[name]){
  this.Groups[name]=new System.Event.EventListener();
 }
 return this.Groups[name];
};


System.Event.EventListener.prototype.Remove=function(funct,runOnce){
 var tfunct=this.EventListeners.indexOf(funct);

 this.EventListeners[tfunct]=null;
 if(runOnce){
  this.EventListeners[tfunct+1]=null;
  runOnce=2;
 }else{
  runOnce=1;
 }

 this.EventListeners.splice(tfunct,runOnce);	//remove the function, and the runonce function if required
 funct=null;
};


System.Event.CreateHandler=function(obj){

 if(!obj.EventHandler){
  obj.EventHandler=new function(){

   this.Listeners={};

   this.EnableDefaultListeners=function(){
    var args=toArray(arguments);
    if(args.length==0){
     if(obj.tagName){
      switch(obj.tagName.toLowerCase()){
       case "body": case "img":
        args=["mouse","key","focus","load"];
        break;
       case "form":
        args=["mouse","key","focus","form"];
        break;
       case "input": case "textarea":
        args=["mouse","key","focus","input"];
        break;
       default:
        args=["mouse","key","focus"];
        break;
      }
     }else{
      args=["mouse","key","focus","input","form","load"];
     }
    }

    if(args.indexOf("mouse")>-1){
     this.EnableListener("click");
     this.EnableListener("dblclick");
     this.EnableListener("mousedown");
     this.EnableListener("mouseup");
     this.EnableListener("mousemove");
     this.EnableListener("mouseout");
     this.EnableListener("mouseover");
    }

    if(args.indexOf("key")>-1){
     this.EnableListener("keydown");
     this.EnableListener("keyup");
     this.EnableListener("keypress");
    }

    if(args.indexOf("focus")>-1){
     this.EnableListener("blur");
     this.EnableListener("focus");
    }

    if(args.indexOf("input")>-1){
     this.EnableListener("change");
     this.EnableListener("select");
    }

    if(args.indexOf("form")>-1){
     this.EnableListener("submit");
     this.EnableListener("reset");
    }

    if(args.indexOf("load")>-1){
     this.EnableListener("abort");
     this.EnableListener("error");
     this.EnableListener("load");
     this.EnableListener("unload");
    }

   };


   var cachedRealListeners=[];
   var cachedRealTypes=[];


   this.EnableListener=function(eventType,objCaller){
    if(eventType.substring(0,2)=="on"){
     eventType=eventType.substring(2);
    }

    if(!this.Listeners[eventType]){
     this.Listeners[eventType]=new System.Event.EventListener();

     cachedRealTypes[cachedRealTypes.length]=eventType;


     if(obj.addEventListener){
      obj.addEventListener(eventType,cachedRealListeners[cachedRealListeners.length]=function(e){
       obj.EventHandler.Listeners[eventType].Fire(e,objCaller||obj);},
      false);
     }else if(obj.attachEvent){
      obj.attachEvent("on"+eventType,cachedRealListeners[cachedRealListeners.length]=function(e){
       obj.EventHandler.Listeners[eventType].Fire(e,objCaller||obj);
      });
     }

    }

    return this.Listeners[eventType];
   };


   this.DestroyListener=function(eventType){

    var j=0;

    if(eventType.substring(0,2)=="on"){
     eventType=eventType.substring(2);
    }

    if(this.Listeners[eventType]){

     j+=this.Listeners[eventType].Destroy();
     delete this.Listeners[eventType];

     var i=cachedRealTypes.indexOf(eventType);

     if(obj.removeEventListener){
      obj.removeEventListener(cachedRealTypes[i],cachedRealListeners[i],false);
     }else if(obj.detachEvent){
      obj.detachEvent("on"+cachedRealTypes[i],cachedRealListeners[i]);
     }

     cachedRealTypes[i]=null;
     cachedRealTypes.splice(i,1);

     cachedRealListeners[i]=null;
     cachedRealListeners.splice(i,1);

    }

    return j;

   };


   this.GetListener=function(eventType){
    if(eventType.substring(0,2)=="on"){
     eventType=eventType.substring(2);
    }
    return this.Listeners[eventType];
   };


   this.Destroy=function(){

    var j=0;


    //drop all listeners
    if(cachedRealListeners){

     while(cachedRealListeners.length>0){
      j+=this.DestroyListener(cachedRealTypes[cachedRealTypes.length-1]);
     }

    }

    cachedRealTypes=null;
    cachedRealListeners=null;
    this.Listeners=null;

    obj=null;

    return j;
   };


   this.DestroyGroup=function(val){

    if(typeof(val)=="object"){
     val=val.__EventUniqueIdent;
    }

    var j=0;
    for(var eventType in this.Listeners){

     if(this.Listeners[eventType].Groups[val]){

      j+=this.Listeners[eventType].Groups[val].Destroy();
      delete this.Listeners[eventType].Groups[val];

     }

    }

    return j;
   };


  }();

 }
 return obj.EventHandler;
};


windowLoaded=false;
System.Event.CreateHandler(window).EnableListener("load").Append(function(){windowLoaded=true;},false,true);

System.GetQueryString=function(){

 var querystring=window.location.search;
 var returnObj={};

 if(querystring){

  querystring=querystring.substring(1);

  querystring=querystring.split("&");
  var querystringSplit;

  for(var i=0;i<querystring.length;i++){

   querystringSplit=querystring[i].split("=");

   if(querystringSplit.length==2){
    returnObj[querystringSplit[0]]=querystringSplit[1];
   }

  }

 }

 return returnObj;

};

System.namespace("GUI");

System.GUI.ContextMenu=function(){


 this.Destroy=function(){

  System.Event.DestroyHandler(this);

  if(document.body.EventHandler){
   document.body.EventHandler.DestroyGroup(this);
  }

 };



 this.CreateItem=function(){

  var el=document.createElement("div");

  el.style.cssText="";


  this.Destroy=function(){


  };


  this.Append=function(){

  };


  this.IsDisabled=false;


  this.Disable=function(){

   if(!this.IsDisabled){

    this.IsDisabled=true;

    System.Element.SetOpacity(this,30);

/*
    if(function_ref){
     this.EventHandler.DestroyListener("click");
    }

    this.onmouseover=null;
    this.onmouseout=null;
    this.onclick=null;

*/

   }

  };


  this.Enable=function(){

   if(this.IsDisabled){

    this.IsDisabled=false;

    System.Element.SetOpacity(this,100);

   }

  };


  this.IsHidden=false;


  this.Hide=function(){

   if(!this.IsHidden){

    this.IsHidden=true;
    this.style.display="none";

   }

  };


  this.UnHide=function(){

   if(this.IsHidden){

    this.IsHidden=false;
    this.style.display="";

   }

  };


  this.GetText=function(){

  };


  this.SetText=function(){

  };


 };


 this.CreateBreak=function(){


 };


 this.Append=function(){


 };


 this.Hide=function(){


 };


 this.UnHide=function(){


 };


 this.FixedToElementPosition=false;


 this.FixToElementPosition=function(el,x,y){

   this.FixedToElementPosition=true;

   this.x.style.left=(System.ElementGetXPosition(el)+x)+"px";
   this.x.style.top=(System.ElementGetYPosition(el)+y+el.offsetHeight)+"px";

 };


};

Grid=function(){

 var container=document.createElement("div");
 container.className="grid";


 //destroy
 container.Destroy=function(){

  this.Header=null;
  this.BodyContainer=null;
  this.BodyTable=null;

  //loop all elements and destroy their event properties
  System.Element.DestroyEventProperties();

 };


 //header
 container.HeaderContainer=container.appendChild(document.createElement("div"));
 container.HeaderContainer.className="header";
 container.Header=container.HeaderContainer.appendChild(document.createElement("table")).appendChild(document.createElement("thead"));


 container.Header.Row=function(){

  var row=document.createElement("tr");

  row.Column=function(inner){

   var widthCol=container.BodyTable.firstChild.firstChild.appendChild(document.createElement("th"));
   widthCol.style.height="0px";
   widthCol.style.display="block";
   widthCol.style.width="52px";
   widthCol=null;

   var col=document.createElement("th");
   col.style.width="52px";
   col.innerHTML=inner;
   return col;

  };

  row.AddColumn=function(col){
   this.appendChild(col);
  };

  return row;

 };


 container.Header.AddRow=function(row){
  this.appendChild(row);
 };


 //body
 container.BodyContainer=container.appendChild(document.createElement("div"));
 container.BodyContainer.className="container";

 container.BodyContainer.onscroll=function(){
  container.HeaderContainer.scrollLeft=this.scrollLeft;
 };


 container.BodyTable=container.BodyContainer.appendChild(document.createElement("table"));


 //sets the with on the cols
 var widthRow=container.BodyTable.appendChild(document.createElement("thead")).appendChild(document.createElement("tr"));
 widthRow.style.position="absolute";
 widthRow=null;


 container.Body=function(){

  var body=document.createElement("tbody");


  body.AddSet=function(arr){

   var row;

   for(var i=0;i<arr.length;i++){

    row=new this.Row();

    for(var j=0;j<arr[i].length;j++){
     row.AddColumn(new row.Column(arr[i][j]));
    }

   }

  };


  body.AddRow=function(row){
   this.appendChild(row);
  };


  body.Row=function(){

   var row=document.createElement("tr");

   row.Column=function(inner){

    var col=document.createElement("td");
    col.innerHTML=inner;
    return col;

   };

   row.AddColumn=function(col){
    this.appendChild(col);
   };

   return row;

  };


  return body;

 };


 container.AddBody=function(body){
  this.BodyTable.appendChild(body);
 };


 container.Sort=function(col,side){

  var colIndex=0;

  if(typeof(col)=="number"){

   colIndex=col;
   col=container.Header.firstChild.childNodes[colIndex];

  }else if(typeof(col)=="object"){
   colIndex=col.cellIndex;
  }


  if(this.SortedElement){
   System.Element.RemoveClass(this.SortedElement,"sorted");
  }

  System.Element.AddClass(col,"sorted");


  this.SortedIndex=colIndex;
  this.SortedElement=col;


  var sortFunction=function(a,b){

   var c=a.cells[colIndex].innerText;
   var d=b.cells[colIndex].innerText;
   return c>d?1:c<d?-1:0;

  };


  var tbodyArray=this.BodyTable.childNodes, tbody, tbodySorted;

  for(var i=1;i<tbodyArray.length;i++){

   tbody=tbodyArray[i];

   tbodySorted=toArray(tbody.childNodes).sort(sortFunction);

   if(side){
    tbodySorted.reverse();
   }

   for(var j=0;j<tbodySorted.length;j++){
    tbody.appendChild(tbodySorted[j]);
   }

   tbodySorted=null;

  }


 };


 return container;

};

 System.QueryString=function(){

  var qObject=new Object();

  this.Load=function(val){

   if(val.substring(0,1)=="?"){
    val=val.substring(1);
   }

   var valSplit=val.split("&");

   for(var i=0;i<valSplit.length;i++){
    var itemSplit=valSplit[i].split("=");
    this.Set(itemSplit[0],unescape(itemSplit[1]));
   }

  };


  this.LoadCurrent=function(){
   this.Load(System.GetQueryString());
  };


  this.Set=function(str,val){
   qObject[str]=val;
  };


  this.Get=function(str){
   if(!str){
    return qObject;
   }else{
    return qObject[str];
   }
  };


  this.Union=function(nqObj,overwrite){

   var nqObjr=nqObj.Get();
   for(var i in nqObjr){

    if(overwrite||!this.Get(i)){
     this.Set(i,nqObjr[i]);
    }

   }

  };


  this.MakeUnique=function(){
   this.Set("UniqueQueryStringIdent",(new Date()).getTime());
  };


  this.ToString=function(){
   var qItem, qString;

   this.Union(System.BaseURL.QueryString,true);

   for(var qItem in qObject){
    if(qString){
     qString+="&"+qItem+"="+urlescape(qObject[qItem]);
    }else{
     qString=qItem+"="+urlescape(qObject[qItem]);
    }
    
   }

   return qString;
  };

 };

System.namespace("Security");


/*------------------------------------------------------*/
/* Security.Cryptography namespace			*/
/*							*/
/*							*/
/*							*/
/*------------------------------------------------------*/

System.Security.namespace("Cryptography");


 System.Security.Cryptography.Rijndael=function(){

function Cipher(input, w) {    // main Cipher function [§5.1]
  var Nb = 4;               // block size (in words): no of columns in state (fixed at 4 for AES)
  var Nr = w.length/Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys

  var state = [[],[],[],[]];  // initialise 4xNb byte-array 'state' with input [§3.4]
  for (var i=0; i<4*Nb; i++) state[i%4][Math.floor(i/4)] = input[i];

  state = AddRoundKey(state, w, 0, Nb);

  for (var round=1; round<Nr; round++) {
    state = SubBytes(state, Nb);
    state = ShiftRows(state, Nb);
    state = MixColumns(state, Nb);
    state = AddRoundKey(state, w, round, Nb);
  }

  state = SubBytes(state, Nb);
  state = ShiftRows(state, Nb);
  state = AddRoundKey(state, w, Nr, Nb);

  var output = new Array(4*Nb);  // convert state to 1-d array before returning [§3.4]
  for (var i=0; i<4*Nb; i++) output[i] = state[i%4][Math.floor(i/4)];
  return output;
}


function SubBytes(s, Nb) {    // apply SBox to state S [§5.1.1]
  for (var r=0; r<4; r++) {
    for (var c=0; c<Nb; c++) s[r][c] = Sbox[s[r][c]];
  }
  return s;
}


function ShiftRows(s, Nb) {    // shift row r of state S left by r bytes [§5.1.2]
  var t = new Array(4);
  for (var r=1; r<4; r++) {
    for (var c=0; c<4; c++) t[c] = s[r][(c+r)%Nb];  // shift into temp copy
    for (var c=0; c<4; c++) s[r][c] = t[c];         // and copy back
  }          // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
  return s;  // see fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf 
}


function MixColumns(s, Nb) {   // combine bytes of each col of state S [§5.1.3]
  for (var c=0; c<4; c++) {
    var a = new Array(4);  // 'a' is a copy of the current column from 's'
    var b = new Array(4);  // 'b' is a•{02} in GF(2^8)
    for (var i=0; i<4; i++) {
      a[i] = s[i][c];
      b[i] = s[i][c]&0x80 ? s[i][c]<<1 ^ 0x011b : s[i][c]<<1;
    }
    // a[n] ^ b[n] is a•{03} in GF(2^8)
    s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
    s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
    s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
    s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
  }
  return s;
}


function AddRoundKey(state, w, rnd, Nb) {  // xor Round Key into state S [§5.1.4]
  for (var r=0; r<4; r++) {
    for (var c=0; c<Nb; c++) state[r][c] ^= w[rnd*4+c][r];
  }
  return state;
}


function KeyExpansion(key) {  // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
  var Nb = 4;            // block size (in words): no of columns in state (fixed at 4 for AES)
  var Nk = key.length/4  // key length (in words): 4/6/8 for 128/192/256-bit keys
  var Nr = Nk + 6;       // no of rounds: 10/12/14 for 128/192/256-bit keys

  var w = new Array(Nb*(Nr+1));
  var temp = new Array(4);

  for (var i=0; i<Nk; i++) {
    var r = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]];
    w[i] = r;
  }

  for (var i=Nk; i<(Nb*(Nr+1)); i++) {
    w[i] = new Array(4);
    for (var t=0; t<4; t++) temp[t] = w[i-1][t];
    if (i % Nk == 0) {
      temp = SubWord(RotWord(temp));
      for (var t=0; t<4; t++) temp[t] ^= Rcon[i/Nk][t];
    } else if (Nk > 6 && i%Nk == 4) {
      temp = SubWord(temp);
    }
    for (var t=0; t<4; t++) w[i][t] = w[i-Nk][t] ^ temp[t];
  }

  return w;
}

function SubWord(w) {    // apply SBox to 4-byte word w
  for (var i=0; i<4; i++) w[i] = Sbox[w[i]];
  return w;
}

function RotWord(w) {    // rotate 4-byte word w left by one byte
  w[4] = w[0];
  for (var i=0; i<4; i++) w[i] = w[i+1];
  return w;
}


// Sbox is pre-computed multiplicative inverse in GF(2^8) used in SubBytes and KeyExpansion [§5.1.1]
var Sbox =  [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
             0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
             0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
             0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
             0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
             0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
             0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
             0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
             0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
             0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
             0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
             0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
             0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
             0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
             0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
             0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16];

// Rcon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
var Rcon = [ [0x00, 0x00, 0x00, 0x00],
             [0x01, 0x00, 0x00, 0x00],
             [0x02, 0x00, 0x00, 0x00],
             [0x04, 0x00, 0x00, 0x00],
             [0x08, 0x00, 0x00, 0x00],
             [0x10, 0x00, 0x00, 0x00],
             [0x20, 0x00, 0x00, 0x00],
             [0x40, 0x00, 0x00, 0x00],
             [0x80, 0x00, 0x00, 0x00],
             [0x1b, 0x00, 0x00, 0x00],
             [0x36, 0x00, 0x00, 0x00] ]; 


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

/* 
 * Use AES to encrypt 'plaintext' with 'password' using 'nBits' key, in 'Counter' mode of operation
 *                           - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
 *   for each block
 *   - outputblock = cipher(counter, key)
 *   - cipherblock = plaintext xor outputblock
 */
function AESEncryptCtr(plaintext, password, nBits) {
  if (!(nBits==128 || nBits==192 || nBits==256)) return '';  // standard allows 128/192/256 bit keys
	
  // for this example script, generate the key by applying Cipher to 1st 16/24/32 chars of password; 
  // for real-world applications, a more secure approach would be to hash the password e.g. with SHA-1
  var nBytes = nBits/8;  // no bytes in key
  var pwBytes = new Array(nBytes);
  for (var i=0; i<nBytes; i++) pwBytes[i] = password.charCodeAt(i) & 0xff;
  var key = Cipher(pwBytes, KeyExpansion(pwBytes));
  key = key.concat(key.slice(0, nBytes-16));  // key is now 16/24/32 bytes long

  // initialise counter block (NIST SP800-38A §B.2): millisecond time-stamp for nonce in 1st 8 bytes,
  // block counter in 2nd 8 bytes
  var blockSize = 16;  // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
  var counterBlock = new Array(blockSize);  // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
  var nonce = (new Date()).getTime();  // milliseconds since 1-Jan-1970

  // encode nonce in two stages to cater for JavaScript 32-bit limit on bitwise ops
  for (var i=0; i<4; i++) counterBlock[i] = (nonce >>> i*8) & 0xff;
  for (var i=0; i<4; i++) counterBlock[i+4] = (nonce/0x100000000 >>> i*8) & 0xff; 

  // generate key schedule - an expansion of the key into distinct Key Rounds for each round
  var keySchedule = KeyExpansion(key);

  var blockCount = Math.ceil(plaintext.length/blockSize);
  var ciphertext = new Array(blockCount);  // ciphertext as array of strings
  
  for (var b=0; b<blockCount; b++) {
    // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
    // again done in two stages for 32-bit ops
    for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> c*8) & 0xff;
    for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8)

    var cipherCntr = Cipher(counterBlock, keySchedule);  // -- encrypt counter block --
    
    // calculate length of final block:
    var blockLength = b<blockCount-1 ? blockSize : (plaintext.length-1)%blockSize+1;

    var ct = '';
    for (var i=0; i<blockLength; i++) {  // -- xor plaintext with ciphered counter byte-by-byte --
      var plaintextByte = plaintext.charCodeAt(b*blockSize+i);
      var cipherByte = plaintextByte ^ cipherCntr[i];
      ct += String.fromCharCode(cipherByte);
    }
    // ct is now ciphertext for this block

    ciphertext[b] = escCtrlChars(ct);  // escape troublesome characters in ciphertext
  }

  // convert the nonce to a string to go on the front of the ciphertext
  var ctrTxt = '';

  for (var i=0; i<8; i++) ctrTxt += String.fromCharCode(counterBlock[i]);
  ctrTxt = escCtrlChars(ctrTxt);

  // use '-' to separate blocks, use Array.join to concatenate arrays of strings for efficiency
  return ctrTxt + '-' + ciphertext.join('-');
}


/* 
 * Use AES to decrypt 'ciphertext' with 'password' using 'nBits' key, in Counter mode of operation
 *
 *   for each block
 *   - outputblock = cipher(counter, key)
 *   - cipherblock = plaintext xor outputblock
 */
function AESDecryptCtr(ciphertext, password, nBits) {
  if (!(nBits==128 || nBits==192 || nBits==256)) return '';  // standard allows 128/192/256 bit keys

  var nBytes = nBits/8;  // no bytes in key
  var pwBytes = new Array(nBytes);
  for (var i=0; i<nBytes; i++) pwBytes[i] = password.charCodeAt(i) & 0xff;
  var pwKeySchedule = KeyExpansion(pwBytes);
  var key = Cipher(pwBytes, pwKeySchedule);
  key = key.concat(key.slice(0, nBytes-16));  // key is now 16/24/32 bytes long

  var keySchedule = KeyExpansion(key);

  ciphertext = ciphertext.split('-');  // split ciphertext into array of block-length strings 

  // recover nonce from 1st element of ciphertext
  var blockSize = 16;  // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
  var counterBlock = new Array(blockSize);
  var ctrTxt = unescCtrlChars(ciphertext[0]);
  for (var i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i);

  var plaintext = new Array(ciphertext.length-1);

  for (var b=1; b<ciphertext.length; b++) {
    // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
    for (var c=0; c<4; c++) counterBlock[15-c] = ((b-1) >>> c*8) & 0xff;
    for (var c=0; c<4; c++) counterBlock[15-c-4] = ((b/0x100000000-1) >>> c*8) & 0xff;

    var cipherCntr = Cipher(counterBlock, keySchedule);  // encrypt counter block

    ciphertext[b] = unescCtrlChars(ciphertext[b]);

    var pt = '';
    for (var i=0; i<ciphertext[b].length; i++) {
      // -- xor plaintext with ciphered counter byte-by-byte --
      var ciphertextByte = ciphertext[b].charCodeAt(i);
      var plaintextByte = ciphertextByte ^ cipherCntr[i];
      pt += String.fromCharCode(plaintextByte);
    }
    // pt is now plaintext for this block

    plaintext[b-1] = pt;  // b-1 'cos no initial nonce block in plaintext
  }

  return plaintext.join('');
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */

function escCtrlChars(str) {  // escape control chars which might cause problems handling ciphertext
  return str.replace(/[\0\t\n\v\f\r\xa0!-]/g, function(c) { return '!' + c.charCodeAt(0) + '!'; });
}  // \xa0 to cater for bug in Firefox; include '-' to leave it free for use as a block marker

function unescCtrlChars(str) {  // unescape potentially problematic control characters
  return str.replace(/!\d\d?\d?!/g, function(c) { return String.fromCharCode(c.slice(1,-1)); });
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */


  this.Encrypt=function(val,key,bits){
   if(!bits){
    bits=256;
   }
   return AESEncryptCtr(val, key, bits);
  };


  this.Decrypt=function(val,key,bits){
   if(!bits){
    bits=256;
   }
   return AESDecryptCtr(val, key, bits)
  };


  this.EncryptWithKeyCheck=function(val,key,bits){
   val="RijndaelKeyCheck"+val;
   return this.Encrypt(val,key,bits);
  };


  this.DecryptWithKeyCheck=function(val,key,bits){
   var decryptedValue=this.Decrypt(val,key,bits);
   if(decryptedValue.substring(0,16)=="RijndaelKeyCheck"){
    return decryptedValue.substring(16);
   }
  };


 };



System.Security.Cryptography.SHA1=function(){

 this.ComputeHash=function(val){
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1 Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/

/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << (24 - len % 32);
  x[((len + 64 >> 9) << 4) + 15] = len;

  var w = Array(80);
  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var e = -1009589776;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;
    var olde = e;

    for(var j = 0; j < 80; j++)
    {
      if(j < 16) w[j] = x[i + j];
      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
      e = d;
      d = c;
      c = rol(b, 30);
      b = a;
      a = t;
    }

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
    e = safe_add(e, olde);
  }
  return Array(a, b, c, d, e);
  
}

/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
  if(t < 20) return (b & c) | ((~b) & d);
  if(t < 40) return b ^ c ^ d;
  if(t < 60) return (b & c) | (b & d) | (c & d);
  return b ^ c ^ d;
}

/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
         (t < 60) ? -1894007588 : -899497514;
}  

/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data)
{
  var bkey = str2binb(key);
  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
  return core_sha1(opad.concat(hash), 512 + 160);
}

/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i%32);
  return bin;
}

/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask);
  return str;
}

/*
* Convert an array of big-endian words to a hex string.
*/
function binb2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
  }
  return str;
}

/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}
  return hex_sha1(val);
 };

};


System.Security.Cryptography.SHA256=function(){

 this.ComputeHash=function(val){
   /*!
    *   Copyright CertainKey Inc. 2002
    */
    var state=[0,0,0,0,0,0,0,0],count=[0,0],buf=[],PADDING="";
    buf[127]=0;
    PADDING="\200";

    for(var i=1;i<128;i++){
     PADDING+=String.fromCharCode(0);
    }

    function F(x){
     return(x+4294967296) % 4294967296;
    }

    function e0(x){
     return(((x>>>2)|(x<<30))^((x>>>13)|(x<<19))^((x>>>22)|(x<<10)));
    }

    function e1(x){
     return(((x>>>6)|(x<<26))^((x>>>11)|(x<<21))^((x>>>25)|(x<<7)));
    }

    function s0(x){
     return(((x>>>7)|(x<<25))^((x>>>18)|(x<<14))^(x>>>3));
    }

    function s1(x){
     return(((x>>>17)|(x<<15))^((x>>>19)|(x<<13))^(x >>> 10));
    }

    K=[0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
     0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
     0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
     0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
     0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
     0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
     0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
     0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
    ];

    function sha256Xform(state,input){
     var a,b,c,d,e,f,g,h,t1, t2;
     var W=[],i;

     W[15]=0;
     for(i=0;i<16;i++){
      t1=(input[(4*i)]&0xff);t1<<=8;
      t1|=(input[(4*i)+1]&0xff);t1<<=8;
      t1|=(input[(4*i)+2]&0xff);t1<<=8;
      t1|=(input[(4*i)+3]&0xff);
      W[i]=t1;
     }

     for(i=16;i<64;i++){
      W[i]=F(s1(W[i-2])+W[i-7]+s0(W[i-15])+W[i-16]);
     }

     a=state[0]; b=state[1]; c=state[2]; d=state[3];
     e=state[4]; f=state[5]; g=state[6]; h=state[7];

     for(i=0;i<64;i++){
      t1=F(h+e1(e)+((e&f)^(~e&g))+K[i]+W[i]);
      t2=F(e0(a)+((a&b)^(a&c)^(b&c)));
      h=g; g=f; f=e; e=F(d+t1);
      d=c; c=b; b=a; a=F(t1+t2);
     }
     state[0]=F(state[0]+a); state[1]=F(state[1]+b); state[2]=F(state[2]+c); state[3]=F(state[3]+d);
     state[4]=F(state[4]+e); state[5]=F(state[5]+f); state[6]=F(state[6]+g); state[7]=F(state[7]+h);

     for(i=0;i<64;i++){
      W[i]=0;
     }
     a=b=c=d=e=f=g=h=t1=t2=0;
    };

    function sha256Init() {
     state[0]=0x6a09e667;
     state[1]=0xbb67ae85;
     state[2]=0x3c6ef372;
     state[3]=0xa54ff53a;
     state[4]=0x510e527f;
     state[5]=0x9b05688c;
     state[6]=0x1f83d9ab;
     state[7]=0x5be0cd19;
     count[0]=count[1]=0;

     for(var i=0;i<128;i++){
      buf[i]=0;
     }
    }

function sha256Update(input, inputLen) {
  var i, j, index, partLen, temp=[];

  temp[4*16-1] = 0;

  index = ((count[0] >>> 3) & 0x3f);

  if ((count[0] += (inputLen << 3)) < (inputLen << 3)) {
    count[1]++;
    count[1] += (inputLen >>> 29);
  }

  partLen = 64 - index;

  if (inputLen >= partLen) {
    for (j=0; j<partLen; j++)
      buf[index + j] = input.charCodeAt(j); 
    sha256Xform(state, buf);

    for (i=partLen; i+63<inputLen; i+=64) {
      for (j=0; j<4*16; j++)
        temp[j] = input.charCodeAt(i + j);
      sha256Xform(state, temp);
    }
    for (j=0; j<4*16; j++)
      temp[j] = 0;

    index = 0;
  } else {
    i = 0;
  }

  for (j=0; j<inputLen-i; j++) {
    buf[index + j] = input.charCodeAt(i + j);
  }
}

function sha256Final(digest) {
  var bits="", index, padLen, t, i;

  t = count[1];
  bits += String.fromCharCode((t>>>24)&0xff);
  bits += String.fromCharCode((t>>>16)&0xff);
  bits += String.fromCharCode((t>>> 8)&0xff);
  bits += String.fromCharCode((t     )&0xff);
  t = count[0];
  bits += String.fromCharCode((t>>>24)&0xff);
  bits += String.fromCharCode((t>>>16)&0xff);
  bits += String.fromCharCode((t>>> 8)&0xff);
  bits += String.fromCharCode((t     )&0xff);

  index = (count[0] >>> 3) & 0x3f;
  padLen = (index < 56) ? (56 - index) : ((64+56) - index);
  sha256Update(PADDING, padLen);

  sha256Update(bits, 8);

  for (i=0; i<8; i++) {
    t = state[i];
    digest[4*i+3] = (t & 0xff); t>>>=8;
    digest[4*i+2] = (t & 0xff); t>>>=8;
    digest[4*i+1] = (t & 0xff); t>>>=8;
    digest[4*i  ] = (t & 0xff);
  }

  for (i=0; i<8; i++)
    state[i] = 0;
  count[0] = count[1] = 0;
  for (i=0; i<128; i++)
    buf[i] = 0;
}

function hex8(n) { return hex_(n,8); }
function hex(n) { return hex_(n,2); }
function hex_(n,l) {
  var ret ="",
      z = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
  for (var i=0; i<l; i++) {
    ret = z[n%16] +ret;
    n >>>= 4;
  }
  return ret;
}

function sha256Test() {
  var res=[], str = "abc", ans = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", i;

  res[8*4-1] = 0;
  for (i=0; i<8*4; i++)
    res[i] = 0;

  sha256Init();
  sha256Update(str, str.length);
  sha256Final(res);

  X="";
  for (i=0; i<8*4; i++) X += hex(res[i]);
  alert((X.indexOf(ans)==0)?"OK":"FAILED");
}

function sha256(str) {
  var res=[]; res[8*4-1]=0;
  sha256Init();
  sha256Update(str, str.length);
  sha256Final(res);
  X="";
  for (i=0; i<8*4; i++) X += hex(res[i]);
  return X;
}

  return sha256(val);

 };

};

 System.URL=function(url){


  this.Protocol=undefined;
  this.Path=undefined;


  this.Authority={

   User:undefined,
   Password:undefined,
   Host:undefined,
   Port:undefined,

   ToString:function(){

    var authString="";

    if(this.User){
     authString+=this.User;

     if(this.Password){
      authString+=":"+this.Password;
     }

     authString+="@";
    }

    if(this.Host){
     authString+=this.Host;
    }

    if(this.Port){
     authString+=":"+this.Port;
    }

    return authString;

   }

  };


  this.QueryString=new System.QueryString();


  if(url){

   //set authority
   urlProtocolDividerLocation=url.indexOf("://");
   if(urlProtocolDividerLocation>-1){

    this.Protocol=url.substring(0,urlProtocolDividerLocation);

    url=url.substring(urlProtocolDividerLocation+3);
    urlAuthorityDividerLocation=url.indexOf("/");
    this.Authority.Host=url.substring(0,urlAuthorityDividerLocation);

    url=url.substring(urlAuthorityDividerLocation);
   }

   //check for querystring
   urlQueryStringDividerLocation=url.indexOf("?");

   //set path
   if(urlQueryStringDividerLocation>0){
    this.Path=url.substring(0,urlQueryStringDividerLocation);
   }else if(urlQueryStringDividerLocation==-1){
    this.Path=url;
   }

   //set querystring
   if(urlQueryStringDividerLocation>-1){
    this.QueryString.Load(url.substring(urlQueryStringDividerLocation+1));
   }

  }


  this.Union=function(urlObj,overwrite){

   if(urlObj.Path&&(overwrite||!this.Path)){
    this.Path=urlObj.Path;
   }

   if(urlObj.Protocol&&(overwrite||!this.Protocol)){
    this.Protocol=urlObj.Protocol;
   }

   for(var i in urlObj.Authority){

    if(urlObj.Authority[i]&&i!="ToString"&&(overwrite||!this.Authority[i])){
     this.Authority[i]=urlObj.Authority[i];
    }

   }

   this.QueryString.Union(urlObj.QueryString,overwrite);

  };


  this.ToString=function(){

   this.Union(System.BaseURL,true);

   var urlString="";

   if(this.Protocol){
    urlString+=this.Protocol+"://";
   }

   var authString=this.Authority.ToString();
   if(authString){
    urlString+=authString;
   }

   if(this.Path){
    urlString+=this.Path;
   }

   var queryString=this.QueryString.ToString();
   if(queryString){
    urlString+="?"+queryString;
   }

   return urlString;

  };

 };


System.BaseURL=new System.URL();

function Tooltip(val){

 var ediv=document.createElement("div");
 ediv.style.position="absolute";
 ediv.style.display="none";
 ediv.style.zIndex=2000;
 ediv.innerHTML="<div style='position:relative;top:1px;left:14px;background:url(img/error/pointer_up.gif);width:15px;height:16px;font-size:1px;'>&nbsp;</div><table border='0' cellspacing='0' cellpadding='0'><tbody><tr><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_left_top.gif);'></td><td style='height:5px;font-size:1px;background:#FFFFE1;border-top:1px solid #000000;'>&nbsp;</td><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_right_top.gif);'></td></tr><tr><td style='width:5px;font-size:1px;background:#FFFFE1;border-left:1px solid #000000;'>&nbsp;</td><td style='background:#FFFFE1;font-size:11px;font-family:verdana;padding:4px;'>"+val+"</td><td style='width:5px;font-size:1px;background:#FFFFE1;border-right:1px solid #000000;'>&nbsp;</td></tr><tr><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_left_bottom.gif);'></td><td style='height:5px;font-size:1px;background:#FFFFE1;border-bottom:1px solid #000000;'>&nbsp;</td><td style='width:6px;height:6px;font-size:1px;background:url(img/error/corner_right_bottom.gif);'></td></tr></tbody></table>";

 ediv.setText=function(val){
  this.childNodes[1].firstChild.childNodes[1].childNodes[1].innerHTML=val;
 };

 ediv.getText=function(){
  return this.childNodes[1].firstChild.childNodes[1].childNodes[1].innerHTML;
 };

 ediv.AdjustToElementPosition=function(el,x,y){
  if(isNaN(x)){
   x=0;
  }
  if(isNaN(y)){
   y=0;
  }

  this.style.left=System.Element.GetXPosition(el)+x+"px";
  this.style.top=System.Element.GetYPosition(el)+y+el.offsetHeight+"px";
 }

 ediv.IsHidden=function(){
  if(this.style.display=="none"){
   return true;
  }
  return false;
 };

 ediv.Hide=function(){
  this.style.display="none";
 };

 ediv.UnHide=function(){
  this.style.display="";
 };

 ediv.Remove=function(){
  this.parentNode.removeChild(this);
 }

 ediv.Append=function(){
  document.body.appendChild(this);
 }

 ediv.Destroy=function(){

  System.Element.Destroy(this);
  this.Append=null;
  this.AdjustToElementPosition=null;
  this.IsHidden=null;
  this.getText=null;
  this.setText=null;
  this.Hide=null;
  this.UnHide=null;
  this.Remove=null;
  this.Destroy=null;

 }

 ediv.Append();

 return ediv;
}