
 /**
  *  Tree fetch a node by it's id
  */
  function tree_fetch_node_by_id(tree,id)
  {
      // This replaces the old tree._itemNodeMap[id] 
      try { 
          eval( " var node = tree._itemNodesMap." + id + "[0];");
          return node;
      } catch(e) { console.log('Error fetching node from tree id = ' + id); }
  }

 /**
  *  Fetch a store item
  */
  function store_fetch_id(store,id)
  {
      var obj = null
      store.fetchItemByIdentity({identity: id, onItem: function(item) { obj = item; } });
      return obj;
  }

 /**
  *  Dojo Tree, display item by id
  */
  function tree_open_id_parents(/* string */ id, /* string[] */ list,store)
  {
      list.push(id);
      
      // Iterate through each ReverseReference.
      for (var i in store._getItemByIdentity(id)._RRM)
      {
          tree_open_id_parents(i, list, store);
      }
  }

  function tree_open_id(tree,store,id)
  {
       // Begin here.  "id" is the identity value you're looking for.  This code assumes it does exist.
       var list = [];
       tree_open_id_parents(id, list, store);
      
       var node;
  
       // Walk through the list (in reverse) so you're expanding from the top down.    
       for (var i = list.length - 1; i > 0; i--)
       {
           //node = tree._itemNodeMap[list[i]];
           node = tree_fetch_node_by_id(tree,list[i])
      
           if (node.isExpandable) tree._expandNode(node);

       }

       //return last_node;
       //return tree._itemNodeMap[list[0]];
       return tree_fetch_node_by_id(tree,list[0])
  }

 /**
  *  Conflict Window
  */
  function conflict_win(ast_id,game_id)
  {
       var url = "proposal_conflict.php?ast_id="+ast_id+"&game_id="+game_id+"&tm="+unixtime_get();
       window.open(url,'conf'+unixtime_get(),"width=400,height=400");
  }

  function str_htmlentities_replace(val)
  {
      val = val.replace(/<br>/g,"");
      val = val.replace(/\&lt\;/g,"<");
      val = val.replace(/\&gt\;/g,">");
      val = val.replace(/\&amp\;/g,"&");
      return val;
  }

 /**
 /*  Open a help window
 */
 function help_win()
 {
     window.open("help_win.php","blah","width=400,height=800");
 }

 /**
 /*  Set a twirler
 */
 function id_loading(id)
 {
    try {
       dojo.byId(id).innerHTML = "..working..";
    } catch(e) {}
 }


 /**
 /*  Get the unixtime
 */
 function unixtime_get()
 {
     var d = new Date();
     return   tm = d.getTime();
 }

 function get_unixtime() { return unixtime_get(); }

 function div_set_waiting(node)
 {
     var guts = "<div style='padding: 40px 0px 10px 0px; vertical-align: middle; text-align: center;'><img width=16 height=16 src=imgs/waiting_gray.gif></div>";
     setInnerHTML (guts, node);
 }

 function setInnerHTML (content, dom_node)
 {
    try {
        var dom_node = dojo.byId(dom_node);
        dojo.query('[widgetId]', dom_node).forEach(function(n) { dijit.byNode(n).destroy(); }) ;
    } catch(e) { console.log('Error Setting InnerHTML'); }

    try { dom_node.innerHTML = content; } catch(e) { console.log('Error Setting InnerHTML (2) ' + e.description ); }
    try { dojo.parser.parse(dom_node);  } catch(e) { console.log('Error Setting InnerHTML (3)'); }
 }

 /**
 /*  Load Data into a div
 */
 var ajax_load_skip_fade = false;
 function ajax_load_div(id,url)
 {
     div_set_waiting(id);
     ajax_load_div_run(id,url,'');
 }

 function ajax_load_div_run(id,url,dothis)
 {
     div_set_waiting(id);
     return ajax_load_item_run(id,url,dothis,false)
 }

 function ajax_load_pane_run(id,url,dothis)
 {
     div_set_waiting(id);
     return ajax_load_item_run(id,url,dothis,true)
 }

 function ajax_load_item_run(id,url,dothis,ispane)
 {
        var contentNode = dojo.byId(id);

        // TODO if IE6 Dont animate
        if( dojo.isIE == 6 ) ajax_load_skip_fade = true;

        ajax_load_skip_fade = true;

        dojo.xhrGet({
                url: url,
                handleAs: "text",
                load: function(data,args){

                        if( !ajax_load_skip_fade )
                        {
                             /* fade out the node we're modifying */
                             dojo.fadeOut({
                                     node: contentNode,
                                     duration: 2,
                                     onEnd: function(){
                                       // set the data, fade it back in
                             
                                       if( ispane ) dijit.byId(id).setContent(data); 
                                       else         setInnerHTML (data,id);
                             
                                       //dijit.byId(id).setContent(data);
                                       dojo.fadeIn({node: contentNode, duration: 400}).play();    
                                       try { eval(dothis); } catch(e) { }
                                     }
                             }).play();
                        }
                        else
                        {
                               if( ispane ) dijit.byId(id).setContent(data); 
                               //else         contentNode.innerHTML = data; 
                               else         setInnerHTML (data, id);
                               //console.log('Loading Content... run... ' + id + data);
                               try { eval(dothis); } catch(e) { }
                        }
                },
                // if any error occurs, it goes here:
                error: function(error,args){
                        console.warn("error!",error);
                }
        });
   } 


  function ajax_json_query(url,items,good,ferror)
  {
          dojo.xhrPost({
                url: url,
                load: function (response, ioArgs) 
                      { 
                           try { eval("var ret = " + response); } catch(e) { alert("Error Parsing Request: " + response); return; }
                           try { good(ret); } catch(e) { alert("Error Processing Request..."); }
                      }, 
                handleAs: "text",
                error: function(err,args)
                      { 
                           if( ferror == null ) alert(err); else ferror(err); 
                      },
                content: items
          });

  }

  function ajax_text_query(url,items,good,ferror)
  {
          dojo.xhrPost({
                url: url,
                load: function (response, ioArgs) 
                      { 
                           try { good(response); } catch(e) { alert("Error Processing Request..."); }
                      }, 
                handleAs: "text",
                error: function(err,args)
                      { 
                           if( ferror == null ) alert(err); else ferror(err); 
                      },
                content: items
          });

  }

 
  function URLEncode(plaintext)
  {
     /* The Javascript escape and unescape functions do not correspond
      * with what browsers actually do...
      */
     var SAFECHARS = "0123456789" +                         // Numeric
                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +     // Alphabetic
                         "abcdefghijklmnopqrstuvwxyz" +
                         "-_.!~*'()";                         // RFC2396 Mark characters
     var HEX = "0123456789ABCDEF";

     var encoded = "";
     for (var i = 0; i < plaintext.length; i++ )
        {
          var ch = plaintext.charAt(i);
         if (ch == " ") {
              encoded += "+";                    // x-www-urlencoded, rather than %20
          } else if (SAFECHARS.indexOf(ch) != -1) {
              encoded += ch;
          } else {
              var charCode = ch.charCodeAt(0);
               if (charCode > 255) {
                   alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
                              "(URL encoding only supports 8-bit characters.)\n" +
                                "A space (+) will be substituted." );
                    encoded += "+";
               } else {
                    encoded += "%";
                    encoded += HEX.charAt((charCode >> 4) & 0xF);
                    encoded += HEX.charAt(charCode & 0xF);
               }
          }
     }

     return encoded;
  };



  
 /*  main function to process the fade request  */
 function colorFade(id,element,start,end,steps,speed) 
 {
     var startrgb,endrgb,er,eg,eb,step,rint,gint,bint,step;
     var target = document.getElementById(id);
     steps = steps || 20;
     speed = speed || 20;

     var timer = "TMR" + unixtime_get();
     try { clearInterval(timer); } catch(e) {}
     endrgb = colorConv(end);
     er = endrgb[0];
     eg = endrgb[1];
     eb = endrgb[2];

     //if(!target.r) 
     {
          startrgb = colorConv(start);
          r = startrgb[0];
          g = startrgb[1];
          b = startrgb[2];
          target.r = r;
          target.g = g;
          target.b = b;
    }

    rint = Math.round(Math.abs(target.r-er)/steps);
    gint = Math.round(Math.abs(target.g-eg)/steps);
    bint = Math.round(Math.abs(target.b-eb)/steps);
    if(rint == 0) { rint = 1 }
    if(gint == 0) { gint = 1 }
    if(bint == 0) { bint = 1 }
    target.step = 1;
    timer = setInterval( function() { animateColor(id,element,steps,er,eg,eb,rint,gint,bint,timer) }, speed);
 }

 /* incrementally close the gap between the two colors */
 function animateColor(id,element,steps,er,eg,eb,rint,gint,bint,timer) 
 {
     var target = document.getElementById(id);
     var color;
     if(target.step <= steps) 
     {
         var r = target.r;
         var g = target.g;
         var b = target.b;

         if(r >= er)  r = r - rint; 
         else         r = parseInt(r) + parseInt(rint);

         if(g >= eg)  g = g - gint; 
         else         g = parseInt(g) + parseInt(gint);

         if(b >= eb)  b = b - bint;
         else         b = parseInt(b) + parseInt(bint);

         color = 'rgb(' + r + ',' + g + ',' + b + ')';
         if(element == 'background') { target.style.backgroundColor = color; } 
         else if(element == 'border') { target.style.borderColor = color; } 
         else { target.style.color = color; }

         target.r = r;
         target.g = g;
         target.b = b;
         target.step = target.step + 1;
      } 
      else 
      {
         clearInterval(timer);
         color = 'rgb(' + er + ',' + eg + ',' + eb + ')';

         if(element == 'background') { target.style.backgroundColor = color; } 
         else if(element == 'border') { target.style.borderColor = color; } 
         else { target.style.color = color; }
      }
   }

   /* convert the color to rgb from hex */
   function colorConv(color) 
   {
       var rgb = [parseInt(color.substring(0,2),16), 
       parseInt(color.substring(2,4),16), 
       parseInt(color.substring(4,6),16)];
       return rgb;
   }

   function opacity_by_id(id,val)
   {
        try { dojo.byId(id).style.filter = "alpha(opacity="+val+")"; } catch(e) {}
        //dojo.byId(id).style.-moz-opacity:.40;
        try { dojo.byId(id).style.opacity = val / 100; } catch(e) {}
   }

   trapDeleteKey = function(){

    dojo.connect( document, "onkeypress",

            function( evt ) {

                // console.debug( "Key was pressed %o", evt.target );

                var stopIt = false;

                if( evt.keyCode == dojo.keys.BACKSPACE ){

                    stopIt = true;

                    if( evt.target.tagName ){

                        if((evt.target.tagName.toUpperCase() == "INPUT") && (evt.target.type) && (evt.target.type.toUpperCase() == "TEXT") ) {

                            //console.debug( "Got backspace key in text input field and not stopping it");
                            stopIt = false;

                        }

                        else if(evt.target.tagName.toUpperCase() == "TEXTAREA"){

                            console.debug( "Got backspace in text area and not stopping it")
                            stopIt = false;

                        }
                    }
                }

                if( stopIt ){ dojo.stopEvent( evt ); }

            }  );
   };


      function ajax_parse_response(resp)
      {
           msg = null;

           try 
           {
               eval("var msg = " + resp);
           } 
           catch(e) 
           {
               console.log(resp);
               alert('Invalid Response');
           }

           return msg; 
      }


     function intval( mixed_var, base ) 
     {
          // http://kevin.vanzonneveld.net
          // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
          // +   improved by: stensi
          // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
          // *     example 1: intval('Kevin van Zonneveld');
          // *     returns 1: 0
          // *     example 2: intval(4.2);
          // *     returns 2: 4
          // *     example 3: intval(42, 8);
          // *     returns 3: 42
          // *     example 4: intval('09');
          // *     returns 4: 9
 
        var tmp;
       
        var type = typeof( mixed_var );
       
        if(type == 'boolean'){
            if (mixed_var == true) {
                return 1;
            } else {
                return 0;
            }
        } else if(type == 'string'){
            tmp = parseInt(mixed_var * 1, 10);
            if(isNaN(tmp) || !isFinite(tmp)){
                return 0;
            } else{
                return tmp.toString(base || 10);
            }
        } else if(type == 'number' && isFinite(mixed_var) ){
            return Math.floor(mixed_var);
        } else{
            return 0;
        }
    }

    function div_loading_image(div,pad)
    {
        if( pad == null ) pad = 20;

         setInnerHTML("<div style='padding-top: "+pad+"px; text-align: center;'><img src=imgs/refresh-animated.gif border=0 width=16 height=16></div>",div);
        
    }

