/*************************************************************************}
{*                                                                       *}
{* Author   : Alcindo Schleder                                           *}
{* Copyright: © 2003 by Alcindo Schleder. All rights reserved.           *}
{* Created  : 19/05/2007 - DD/MM/YYYY                                    *}
{* Modified :                                                            *}
{* Version  : 1.0.0.0                                                    *}
{* License  : you can freely use and distribute the included code        *}
{*            for any purpouse, but you cannot remove this copyright     *}
{*            notice. Send me any comments and updates, they are really  *}
{*            appreciated. This software is licensed under MPL License,  *}
{*            see http://www.mozilla.org/MPL/ for details                *}
{* Contact  : alcindo@sistemaprocessa.com.br                             *}
{*            alcindo@processa.org                                       *}
{*            alcindo@processavoip.net                                   *}
{*            http://www.sistemaprocessa.com.br                          *}
{*            http://www.processa.org                                    *}
{*            http://www.processavoip.net                                *}
{*                                                                       *}
{*************************************************************************/

//Hide status bar msg - by Alcindo Schleder
function hidestatus() {
  window.status='';
  return true;
}

if (document.layers)
  document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT)
document.onmouseover=hidestatus
document.onmouseout=hidestatus

gSpool      = [];
gSpoolIdx   = 0;
gPriorClass = "";
xmlhttp     = false;

function GetHttpObject () {    
  var aXmlObj;
  try {
    if (window.XMLHttpRequest) {
      aXmlObj = new XMLHttpRequest();
      if (aXmlObj.readyState == null) {
      aXmlObj.readyState = 1;
      aXmlObj.addEventListener("load", function () {
          aXmlObj.readyState = 4;
          if (typeof aXmlObj.onReadyStateChange == "function")
            aXmlObj.onReadyStateChange();
        }, false);
      }
     return aXmlObj;
    }
    if (window.ActiveXObject) {
      var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
      for (var i = 0; i < prefixes.length; i++) {
        try {
    				  aXmlObj = new ActiveXObject(prefixes[i] + ".XmlHttp");
          return aXmlObj;
        } catch (ex) {};
      }
    }
  } catch (ex) {}
    alert("XmlHttp Objects not supported by client browser!!!");
}

function Send(pMethod, pFunction) {
  if (!pFunction) pFunction = null
  if (!xmlhttp) 
		  xmlhttp = GetHttpObject();
		aUrl = gSpool[gSpoolIdx][0];
  var aParams = '';
		if (pMethod == "POST")
    aParams = gSpool[gSpoolIdx][1];
  aTarget = gSpool[gSpoolIdx][2];
//  if (pMethod == "GET") 
//    xmlhttp.open("GET", aUrl, true);
//  else {
    xmlhttp.open("POST", aUrl, true);
//    xmlhttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
    xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
    xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
    xmlhttp.setRequestHeader("Pragma", "no-cache"); 
//		}
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4) {
      aHtmlText=unescape(xmlhttp.responseText.replace(/\+/g," "));
      document.getElementById(aTarget).innerHTML = aHtmlText;
      if (pFunction) {
        aCall = new CallParams(aParams);
//        aCall.showParams();
        aCall.execute(pFunction);
      }
      init();
      gSpoolIdx++;
      if (gSpoolIdx < gSpool.length) 
//        if (pMethod == "GET") 
//          setTimeout("Send('GET')", 1000);
//								else
          setTimeout("Send('POST')", 1000);
						else {
        gSpool    = [];
						  gSpoolIdx = 0;
						}
    }
  }
//  if (pMethod == "GET") 
//    xmlhttp.send(null);
//		else
    xmlhttp.send(aParams);
}

function ValidFields(aType, pGetParams) {
  if ((!aType) || (aType==""))
    return false;
  else {
    if ((aType=="submit") || (aType=="reset") || (aType=="button") || (aType=="label") || (aType=="legend") || (aType=="hidden"))
      if ((pGetParams) && (aType=="hidden"))
        return true;
      else
        return false;
    else 
      return true;
  }
} 

function CheckParms(pForm) {
  for(i=0;i<pForm.elements.length;i++) {
   	nome=pForm.elements[i].name;
   	tipo=pForm.elements[i].type;
 	  pForm.elements[i].value=Trim(pForm.elements[i].value);
    if (pForm.elements[i].value=="") 
		    return false
  }
		return true;
}

function CheckCustomerData(pForm, pTarget) {
	 var aPassword = pForm.Senha.value;
	 var aPwdConf  = pForm.Confirmacao.value;
  if ((aPassword.value=="") || (aPwdConf.value=="") || (aPwdConf.value!=aPassword.value))
    return false;
		if ((!pTarget) || (pTarget==""))
		  return false;
		return SendAjaxForm(pForm, "POST", pTarget)
}

function CheckEMail(pObj) {
  pObj.value=Trim(pObj.value);
  if (pObj.value!="") {
    atPos = pObj.value.indexOf('@');
    atPos1 = pObj.value.indexOf('.');
    if ((atPos < 1) || (atPos1 < 1) || (atPos1 == (pObj.value.length - 1)) || (atPos == (pObj.value.length - 1)))
	     return false;
  }
  return true;
}

function PositiveNumber(pObj) {
  if ((pObj) && (pObj.value.match(/[0-9]+/g)) && (Number(pObj.value) != 'NaN') && (Number(pObj.value) > 0)) 
    return true;
  else
    return false;
}

function cascadedStyle(pObj, pCssProperty, pCssPropertyNS){
  if (pObj.currentStyle)
    return pObj.currentStyle[pCssProperty]
  else 
		  if (window.getComputedStyle) {
      var aObjStyle=window.getComputedStyle(pObj, "")
      return aObjStyle.getPropertyValue(pCssPropertyNS)
  }
}

function SetFieldMouseOver() {
	 if (navigator.appName=="Microsoft Internet Explorer") {
    var aTop=event.clientY;
    var aLeft=event.clientX;
  	 var aObj=event.srcElement;
		}
		else {
  	 var aObj=event.target;
    var aTop=aObj.style.pixelTop;
    var aLeft=aObj.style.pixelLeft;
		}
		if (aObj) {
				var aMessage="";
				var aShowHint=cascadedStyle(aObj, "u_showhint", "u_showhint");
				var aShowError=cascadedStyle(aObj, "u_showerror", "u_showerror");
    if (aShowError=="true") 
				  aMessage=aObj.getAttribute("u_invalid");
				else
      if (aShowHint=="true") 
		  		  aMessage=aObj.getAttribute("u_hint");
				showBox(aTop, aLeft, document.getElementById("dvHint"), aMessage, aShowHint, aShowError);
		}
}

function SetFieldMouseOut() {
/*
	 if (navigator.appName=="Microsoft Internet Explorer")
  	 var aObj=event.srcElement;
		else
  	 var aObj=event.target;
*/
		hideBox(document.getElementById("dvHint"));
}

function ValidateFormField(pObj, pAlertMsg) {
  var aRet=true;
  if (ValidFields(pObj, false)) {
    if (pObj.getAttribute("u_required")=="true") {
      var aMsg=pObj.getAttribute("u_invalid");
      if (pObj.value=="") aRet=false;
      if ((pObj.getAttribute("u_validate")) && (aRet)) {
        if ((pObj.getAttribute("u_validate")=="eMail") && (!CheckEMail(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="PosNum") && (!PositiveNumber(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="FloatNum") && (!GenericFloat(pObj)))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="CPF") && (!verificaCPF(pObj.value.replace(/[\.|\-]+/g, ''))))
          aRet=false;
        if ((pObj.getAttribute("u_validate")=="CNPJ") && (!validaCNPJ(pObj.value.replace(/[\.|\/|\-]+/g, ''))))
          aRet=false;
      }
      if (!aRet) {
        pObj.className="form-field-invalid";
        if (pAlertMsg) {
          pObj.focus();
          alert(aMsg);
        }
        return false;
      }
    }
  }
  return true;
}

function SetSelectedLink(pContent, n) {
	 if (pContent) {
    var aLinks=pContent.getElementsByTagName("td");
    for(var i=0;i<aLinks.length;i++)
        aLinks[i].className="menu";
    aLinks[n-1].className="selected";
		}
}

function SetFieldFocus() {
	 if (navigator.appName=="Microsoft Internet Explorer")
    event.srcElement.className="form-field-focus";
		else
  	 event.target.className="form-field-focus";
}

function SetFieldBlur() {
  if (navigator.appName=="Microsoft Internet Explorer")
    var aObj=event.srcElement;
  else
    var aObj=event.target;
  var aValid=ValidateFormField(aObj, false);
  if (aValid)
    aObj.className="form-field-select";
  else
    aObj.className="form-field-invalid";
}

function GetFormParams(pForm) {
  aStr='?';
  for (i=0;i<pForm.elements.length;i++) {
   	Name=pForm.elements[i].name;
   	Type=pForm.elements[i].type;
   	Value=pForm.elements[i].value;
   	if (ValidFields(Type, true))
				  if (Type == "radio") {
						  if (pForm.elements[i].checked)
          aStr=aStr+Name+'='+Value+'&';
						} else
        aStr=aStr+Name+'='+Value+'&';
  }
  return aStr+"ExecMethod=emAjax";
}

function ValidateForm(pForm) {
  if (pForm) {
    for (i = 0; i < pForm.elements.length; i++) {
      var aRet=ValidateFormField(pForm.elements[i], true);
      if (!aRet) return aRet;
    }
  } else 
    return false;
}

function ClearAndConfirmation(pFormName, pOperation) {
	 if ((!pFormName) || (pFormName == '') || (!pOperation) || (pOperation == '')) return false;
		var aForm = document.getElementById(pFormName);
		if (pOperation == 'opNew')
  	 var aResult = true;
		else
  	 var aResult = false;
		if (aForm) {
			 if (pOperation == 'opDelete')
      aResult = confirm('Deseja realmente excluir este registro?');
				else
  				SetSampleValue(aForm);
				if ((aResult) || (pOperation == 'opNew')) 
  				aForm.op.value = pOperation;
  }
		return aResult;
}

function SetDefaultValue(pForm) {
  if (pForm) 
    for (i = 0; i < pForm.elements.length; i++) {
						var aType = pForm.elements[i].type;
						var aValue = '';
						var aValid = pForm.elements[i].getAttribute("u_validate");
						if ((aValid) && (aValid == "eMail"))
						  aValue = '';
						if ((aValid) && (aValid == "PosNum"))
						  aValue = '1';
						if ((aValid) && (aValid == "FloatNum"))
						  aValue = '0.00';
						if (aType == 'text') 
						  pForm.elements[i].value = aValue;
						if (aType == 'password') 
						  pForm.elements[i].value = aValue;
						if (aType == 'checkbox') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'radio') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'file') 
						  pForm.elements[i].value = aValue;
						if (aType == 'hidden') 
						  pForm.elements[i].value = '0';
						if (aType == 'select-one') 
						  pForm.elements[i].selectedIndex = 0;
    }
}

function SetSampleValue(pForm) {
  if (pForm) 
    for (i = 0; i < pForm.elements.length; i++) {
						var aType = pForm.elements[i].type;
						var aValue = '.';
						var aValid = pForm.elements[i].getAttribute("u_validate");
						if ((aValid) && (aValid == "eMail"))
						  aValue = 'teste@teste.com.br';
						if ((aValid) && (aValid == "PosNum"))
						  aValue = '1';
						if ((aValid) && (aValid == "FloatNum"))
						  aValue = '0.00';
						if (aType == 'text') 
						  pForm.elements[i].value = aValue;
						if (aType == 'password') 
						  pForm.elements[i].value = aValue;
						if (aType == 'checkbox') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'radio') 
						  pForm.elements[i].checked = 'false';
						if (aType == 'file') 
						  pForm.elements[i].value = aValue;
						if (aType == 'hidden') 
						  pForm.elements[i].value = '0';
						if (aType == 'select-one') 
						  pForm.elements[i].selectedIndex = 0;
    }
}

function ClearForm(pForm) {
  if (pForm) 
    for (i = 0; i < pForm.elements.length; i++)
      if (ValidateFormField(pForm.elements[i], true))
						  pForm.elements[i].value= '0';
}

function SendAjaxForm(pForm, pMethod, pTarget, pFunction) {
  if (!pFunction)
    pFunction = null;
  if (pForm) {
    for (i=0;i<pForm.elements.length;i++) {
      var aRet=ValidateFormField(pForm.elements[i], true);
      if (!aRet) return aRet;
    }
    var aParams = GetFormParams(pForm);
    pMethod="POST";
    if ((pTarget) && (pTarget=="")) pTarget="body";
    if (document.getElementById(pTarget)) {
      document.getElementById(pTarget).innerHTML = "<div class='Loading'>Carregando...</div>";
      gSpool[gSpool.length] = [pForm.action, aParams, pTarget];
      if ((gSpoolIdx + 1) == gSpool.length) {
        Send(pMethod, pFunction);
        return false;
   	  } else {
        return false
      }
    }
    else {
      alert('Don´t locate target (' + pTarget + ') in this document !!!!');
      return false
    }
  } else 
    return false;
}

function GetAjaxLink(pLink, pTarget, pFunction) {
  if (!pFunction) pFunction = null;
  if ((pLink) && (pLink!="")) {
    if ((pTarget) && (pTarget=="")) pTarget="body";
    document.getElementById(pTarget).innerHTML = "<div class='Loading'>Carregando...</div>";
    gSpool[gSpool.length] = [pLink, '', pTarget];
    if ((gSpoolIdx + 1) == gSpool.length) {
      Send("POST", pFunction);
    }
  }
}

function init() {
  // Atribui o evento onFocus e OnChange em todos os campos em todos os formulários do documento
  for (i=0;i<document.forms.length;i++) {
    var aForm=document.forms[i];
    for (j=0;j<aForm.elements.length;j++) {
      var aObj=aForm.elements[j];
      var aRet=ValidFields(aObj.type, false);
      if (aRet) {
        aObj.className="form-field-select";
        aObj.onfocus=SetFieldFocus;
        aObj.onblur=SetFieldBlur;
        aObj.onmouseover=SetFieldMouseOver;
        aObj.onmouseout=SetFieldMouseOut;
      }
    }
  }
}

function showBox(pTop, pLeft, pHintObj, pMessage, pShowHint, pShowError) {
  if ((pHintObj) && (pMessage) && (pMessage!="")) {
    if (pTop)
      pHintObj.style.top=pTop;
    if (pLeft)
      pHintObj.style.left=pLeft;
    var aWidth=pMessage.length;
    pHintObj.style.width=(aWidth*0.6)+"em"
    pHintObj.innerHTML=pMessage;
    if (pShowError=="true") 
      pHintObj.className="hintError";
    else
      if (pShowHint=="true") 
        pHintObj.className="hintVisible";
  }
}

function hideBox(pHintObj) {
  if (pHintObj) 
    pHintObj.className="hintInvisible";
}

function CallParams(pParams) {
  this.Params = pParams;
  pParams = pParams.substr(pParams.indexOf('?'), pParams.lenght - 1);
  this.ParamsArr = pParams.split('&');
  this.showParams = function () {
    return this.Params;
  }
  this.showParamsValueFromName = function (pName) {
    for (i = 0; i = ParamsArr.length;i++) {
      aName = ParamsArr[i].split('=');
      if (aName[0] == pName) {
        return aName[1];
      }
    }
    return -1;
  }
  this.showParamsValueFromIndex = function (pIndex) {
    if (pIndex <= ParamsArr.length) {
      aName = ParamsArr[pIndex].split('=');
      return aName[1];
    }
    return -1;
  }
  this.execute = function (callback) {
    callback(this.Params);
  }
}

window.onload=init;

