
var _utils=function() {
  return {
    
    mainTotalProducts:null,
    mainCurrentVi:0,
    mainbLink:[],
    
    getInputFromName:function(theName) {
      var ii=document.getElementsByTagName('input');
      var ii2=document.getElementsByTagName('textarea');
      var arr=[];
      for (var z=0,zEnd=ii.length;z<zEnd;z++)
        arr.push(ii[z]);
      for (var z=0,zEnd=ii2.length;z<zEnd;z++)
        arr.push(ii2[z]);
      for (var zx=0,zxEnd=arr.length;zx<zxEnd;zx++) {
        if (arr[zx].name==theName)
          return arr[zx];
      }
      return null;
    },
    
    ajaxReply:function(http) {
      var r=http.responseText;
      var rr=r.split('{');
      if (rr[0]==1) {
        _utils.g('form_response').innerHTML=rr[1];
        _utils.g('the_submit_form').innerHTML='';
      } else {
        _utils.g('form_response').innerHTML=rr[1];        
        var rows=rr[2].split("~");        
        for (var z=0,zEnd=rows.length;z<zEnd;z++) {
          var xx=_utils.getInputFromName(rows[z]);
          if (xx) {
            xx.style.background='#F3D26D';
            xx.style.color='black';
          }
        }
      }  
    },

    ajaxReply2:function(http) {
      var r=http.responseText;
      var rr=r.split('{');
      if (rr[0]==1) {
        _utils.g('form_response2').innerHTML=rr[1];
        setTimeout('ggwin.hide()',2000);
        _utils.g('inputy_01').style.visibility='hidden';
        _utils.g('inputy_02').style.visibility='hidden';                                                  
        _utils.g('inputy_03').style.visibility='hidden';
        _utils.g('inputy_05').style.visibility='hidden';
        _utils.g('inputy_06').style.visibility='hidden';
        //_utils.g('the_submit_form2').innerHTML='';
      } else {
        _utils.g('form_response2').innerHTML=rr[1];        
        var rows=rr[2].split("~");        
        for (var z=0,zEnd=rows.length;z<zEnd;z++) {
          var xx=_utils.getInputFromName(rows[z]);
          if (xx) {
            xx.style.background='#F3D26D';
            xx.style.color='black';
          }
        }
      }  
    },
    
    g:function(s) {
      return document.getElementById(s);
    },  
    
    buildLanguageCombo:function(o) {
      document.write(HT_lang_combo);
    },
    
    showNextProduct:function(o) {
      var o;
      var sid='dmainframewin_'+_utils.mainCurrentVi;
      o=_utils.g(sid);
      o.style.display='none';
      _utils.mainCurrentVi++;
      var tot=_utils.mainTotalProducts;
      if (_utils.mainCurrentVi>tot) {
        _utils.mainCurrentVi=0;
      }
      o=_utils.g('dmainframewin_'+_utils.mainCurrentVi);
      o.style.display='block';
      
      _utils.g('sheetlink').href=_utils.mainbLink[_utils.mainCurrentVi];
    },  

    buildSearchBar:function(o) {
      html='<form action="/"><input title="'+HT_SEARCH_HELP_TEXT+'" name="s" onclick=\'this.value=""\' type="text" class="searchbox" value="'+o.text+'"></form>';
      document.write(html);
    },
    
    setLang:function(o) {
      var id=o.options[o.selectedIndex].value;
      document.location='/?hlang='+id;
    },
    
    doChangePasswordWindow:function(o) {
      var lw=450;
      var lh=600;
      ggwin=document.getElementById('ggwind');
      if (!ggwin) {
      
        /*
        ggwin0=document.createElement('div');
        ggwin0.style.position='absolute';
        document.body.appendChild(ggwin0);
        ggwin0.innerHTML='<table style="background:gray;opacity:.5" height="100%" width="100%"><tr><td>&nbsp;</td></tr></table>';
        */

        ggwin=document.createElement('div');
        ggwin.id='ggwind';
        ggwin.style.position='absolute';
        ggwin.style.left='50%';
        ggwin.style.marginLeft='-'+(lw/2)+'px';
        ggwin.style.width=lw+'px';
        //ggwin.style.height=lh+'px';
        document.body.appendChild(ggwin);
      }
      ggwin.style.top='90px';
      ggwin.style.display='block';
      ggwin.hide=function() {
        ggwin.style.display='none';
      }
      
      ggwin.innerHTML='<form id="the_submit_form2" action="?fnp=1" method="post"><table cellpadding="0" cellspacing="0" style="background:white;border-left:6px solid #C0C0C0;border-right:6px solid #C0C0C0;border-bottom:6px solid #C0C0C0;border-top:3px solid #C0C0C0;" width="100%"><tr><td style="font-size:12px;font-weight:bold;font-family:arial;cursor:default;height:20px;padding:5px;color:#333;background:#C0C0C0" width="100%">'+HT_CHANGE_PWD_TITLE+'</td><td onclick="ggwin.hide()" style="font-size:12px;font-weight:bold;font-family:arial;cursor:default;height:20px;padding:5px;color:#555;background:#C0C0C0" align="right"><img src="/wp-includes/js/thickbox/tb-close.png"></td></tr><tr><td colspan=2  style="padding:20px;" align="left"><h3 style="color:#555">'+HT_CHANGE_PWD_TITLE+'</h3></td></tr><tr><td colspan=2  style="padding-left:20px;" align="left"><div id="form_response2"></div></td></tr><tr><td colspan=2  id="inputy_06" style="font-family:arial;font-size:12px;padding-left:20px;padding-top:5px;" align="left">'+HT_CHANGE_PWD_PWD+'</td></tr><tr><td colspan=2  style="padding-left:20px;padding-top:5px;" align="left"><input id="inputy_02" style="width:200px;" type="password" name="ff_req_set_new_pwd"></td></tr><tr><td colspan=2  id="inputy_05" style="font-family:arial;font-size:12px;padding-left:20px;padding-top:5px;" align="left">'+HT_CHANGE_PWD_NPWD+'</td></tr><tr><td colspan=2 style="padding-left:20px;padding-top:5px;" align="left"><input id="inputy_01" style="width:200px;" type="password" name="ff_req_set_new_pwd_confirm"></td></tr><tr><td colspan=2 align="right" style="padding-right:20px;padding-top:90px;padding-bottom:30px;" align="left"><input style="font-size:10px;font-family:arial;" id="inputy_03" type="submit" value="'+HT_CHANGE_PWD_SUBMIT+'">&nbsp;          <input style="font-size:10px;font-family:arial;" type="button" onclick="ggwin.hide()" value="'+HT_CHANGE_PWD_CANCEL+'"></td></tr></table></form>      ';

      var tf2=_utils.g('the_submit_form2'); //change password
      if (tf2) {
        tf2.onsubmit=function() {
          _utils.g('form_response2').innerHTML='<span class="wait">'+HT_PLEASE_WAIT+'</span>';
          gloRequest.post(tf2.action,tf2,_utils.ajaxReply2,true);
          return false;
        }
      }

      
    }
  }  
}();



var gloRequest=function() {
  var activeRequests=[];
  
  var that=this;
  //var obj;
  //var IPath='/glOS/system';
  //var IPathCore=IPath+'/coreWindows';

  function getRequestSlot(oHttp) {
    var zEnd=activeRequests.length;
    var ret=-1;
    for (var z=0;z<zEnd;z++) {
      if (!activeRequests[z])
        ret=z;
    }
    if (ret==-1) {
      if (z) ret=z;
      else ret=1;
    }
    activeRequests[ret]=oHttp;
    return ret;
  }

  function doAbortAllRequests() {
    var zEnd=activeRequests.length;
    for (var z=0;z<zEnd;z++) {
      if (activeRequests[z]) {
        activeRequests[z].abort();
      }  
    }
    activeRequests=[]; //empty request array
  }
  
  /*internal*/
  function encodeFormData(docForm, additionalParams) {
  /*
  v1.1 - 22/09/06
  select-multipe added to encode list
  (before this sending of select multiple object data was not supported)
  (no values at server side)
  */
  
      var     result = '';
      var     formElem;
      var     strLastElemName = '';
  
      for (i = 0; i < docForm.elements.length; i++) {
          formElem = docForm.elements[i];
          switch (formElem.type) {
              // Text fields, hidden form elements
              case 'select-multiple': //v1.1 22/09/06 - ok@16.05
                   var selcombooptions=new Array();
                   var opt;
                   for (var z=0;z<formElem.options.length;z++) {
                     opt=formElem.options[z];
                     if (opt.selected)
                       selcombooptions.push(formElem.name+'='+encodeURIComponent(opt.value));
                   }
                   if (selcombooptions.length) {
                     aa=selcombooptions.join('&');
                     result+=selcombooptions.join('&')+'&';
                   }  
                   break;
              case 'file':
                //temo non sia possibile :p
                result += formElem.name + '=' + encodeURIComponent(formElem.value) + '&';
              break;
              case 'text':
              case 'hidden':
              case 'password':
              case 'textarea':
              case 'select-one':
                  result += formElem.name + '=' + encodeURIComponent(formElem.value) + '&';
                  break;
  
              // Radio buttons
              case 'radio':
                  if (formElem.checked) {
                      result += formElem.name + '=' + encodeURIComponent(formElem.value) + '&';
                  }
                  break;
  
              // Checkboxes
              case 'checkbox':
                  if (formElem.checked) {
                      // Continuing multiple, same-name checkboxes
                      if (formElem.name == strLastElemName) {
                          // Strip of end ampersand if there is one
                          if (result.lastIndexOf('&') == result.length-1) {
                              result = result.substr(0, result.length - 1);
                          }
                          // Append value as comma-delimited string
                          result += ',' + encodeURIComponent(formElem.value);
                      }
                      else {
                          result += formElem.name + '=' + encodeURIComponent(formElem.value);
                      }
                      result += '&';
                      strLastElemName = formElem.name;
                  }
                  break;
  
          }
      }
      if (additionalParams != null) {
          result = result + additionalParams;
      } else {
          result = result.substr(0, result.length - 1);
      }
      return result;
  }
  
  //internal
  // Gets an HTTP object to be used to issue a dynamic request
  function getHTTPObject() {
      var result;
      try {
          result = new XMLHttpRequest();
      } catch (error) {
          try {
              result = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (error) {
              return false;
          }
      }
      return result;
  }
  
  // internal
  // Called when the state of the http object changes.
  // When the ready state is "ready" (4) then this will
  // call the response handler to process the data.
  //
  // The response handler should ensure that the status
  // is non-error (200) before processing the data.
  function readyStateChanged(http,responseHandler,forced,iRequestId) {
    if (http.readyState == 4 || forced) {
      try {
        /* 
        var params=responseHandler.split('|');
        var parami='';
        if (params.length>1)
          for (var z=1;z<params.length;z++)
            parami+=','+params[z];
  			if (params[0]) 		
          eval(params[0] + '(http'+parami+');');
         */
         if (!activeRequests[iRequestId])
           return;

         if (typeof(responseHandler)=='string') {
           try {
             eval(responseHandler);
           } catch(er) {
             if (gloRequest.DEBUG)
               console.log('.Error.\n\nGlorequest error:\n'+readyStateChanged+'\n'+er);
           }
         } else {
           responseHandler(http);
         }
      } catch (error) {
  		  try {
          PARENT.debugger_debug(http.readyState+' '+params[0] + '(http'+parami+')'+error);
  			} catch(er) {
  			}
        // do nothing, no status indicates request cancelled
      }
//      console.log(iRequestId);
      activeRequests[iRequestId]=0;
    }
  }
  
  
  //USE THIS
  // Performs a GET on the given URL string with the method name given
  // specified as the "womid" parameter.  When the response is ready this will
  // call the responseHandler function with the http object and the
  // key parameter given here.
  // glo modz
  // if you want to use doGet as a preloader you must set enableCache to true
  // so uris are not changed (by this way the browser will retrieve objects
  // having the same uri from its cache)
  function doGetX(urlString, responseHandler,async,enableCache) {
      if (typeof(async)=='undefined')
        async=true; 
      var urlo=urlString;

      //ENCODE PARAMS
      if (urlo.indexOf('?')!=-1) {
        urlo=urlo.replace(/\?(.*)/,'?');
        urlo=urlo+encodeURIComponent(RegExp.$1);
        urlo=urlo.replace(/%3D/g,'=');
        urlo=urlo.replace(/%26/g,'&');
      }
      urlString=urlo;
      //alert(urlString);
      var http = getHTTPObject();
      if (http) {
  		  if (!enableCache) {
          //GREAT BUG FIX BY GATO
          //add time component so request is never cached
          var forcenocachedata=(new Date()).getTime();
          if (urlo.indexOf('?')!=-1)
            urlString+='&'+forcenocachedata;
          else  
            urlString+='?'+forcenocachedata;
  		  }	
        http.open("GET", urlString, async);
        var idx=getRequestSlot(http);
  			if (async) {
          http.onreadystatechange = function() { readyStateChanged(http, responseHandler,0,idx); };
          try {
          http.send(null);
          } catch(er) {
            if (gloRequest.DEBUG) {
              alert('Error\ndoGetX');
              console.log('Error\nurlString:'+urlString+'\nresponseHandler:'+responseHandler+'\nasync:'+async+'\nenableCache:'+enableCache+'\nError:'+er+'\n----------\n'+doGetX);
            }  
            http.abort();
          }
  			} else {
          http.send(null);
  				if (responseHandler)
  				  readyStateChanged(http,responseHandler,1,idx);
  				else {
  				  return http.responseText;
  				}		
  			}
      }
  }
  //internal
  // POSTs to the given URL string with the given POST data in submitString.  The
  // methodName is encoded as the form paraemter "womid" to communicate with the server
  // which method is to execute.
  //
  // The key parameter will be passed to the responseHandler function.
  //
  // If the async flag is true the request will run asynchronously, else it will
  // wait for a response before returning.
  function doPostForm(urlString,submitString,responseHandler,async) {
    var http = getHTTPObject();
    //another encode by gato
      var urlo=urlString;
      //ENCODE PARAMS
      if (urlo.indexOf('?')!=-1) {
        urlo=urlo.replace(/\?(.*)/,'?');
        urlo=urlo+encodeURIComponent(RegExp.$1);
        urlo=urlo.replace(/%3D/g,'=');
        urlo=urlo.replace(/%26/g,'&');
      } else {
       urlo=urlo+'?';
      }
      urlString=urlo;
    
    if (http) {
      //add time component so request is never cached
      urlString += '&' + ((new Date()).getTime());
   
      http.open("POST", urlString, async);
      http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      var idx=getRequestSlot(http);
  		if (async) {
        if (responseHandler != null) {
          http.onreadystatechange = function() {
            readyStateChanged(http, responseHandler,0,idx); //call so user defined func is called with http response as a parameter
          };
        }
        http.send(submitString);
  		} else {
        http.send(submitString);
  			if (responseHandler)
          readyStateChanged(http,responseHandler,1,0,idx);
  		}	
    }
  }
  
  //internal
  // Posts to a FORM URL with the given action, using the encoded values of the
  // form given and methodName as POST parameters.
  //
  // The response handler given will be called when the response is ready for
  // processing.
  function doPostFormWithAction(action,aForm,responseHandler,async) {
    doPostForm(action,encodeFormData(aForm, null),responseHandler,async);
  }
  
  
  //USE THIS
  // Uses doPostFormWithAction using specified action or the form's action attribute.
  // is action param is null.
  // The response handler given will be called when the response is ready for
  // processing.
  function doPostX(action,aForm,responseHandler,async) {
    if (typeof(async)=='undefined')
      async=true; 
    if (typeof(action)=='undefined')
      action=aForm.action
    doPostFormWithAction(action,aForm,responseHandler,async);
  }
  
  //Flag indicating we have W3CDOM available to us as a minimum requirement
  var   hasW3CDOM = (document.createElement && document.getElementsByTagName);
  
  // Flag indicates whether AJAX capabilities are supported.
  var   hasAJAX = hasW3CDOM && getHTTPObject();


  return {
    DEBUG:0,
    abortAll: function() {
      doAbortAllRequests();
    },
    post: function(action,oForm,responseHandler,async) {
      //post oForm object to action url <- when done run responseHandler(http) func
      doPostX(action,oForm,responseHandler,async);
    },
    get: function(urlString,responseHandler,async,enableCache) {
      doGetX(urlString, responseHandler, async,enableCache)
    }
  }
}()

