// HTML code to show wait
var arrMandatoryFields;
var intNumberOfBlockers = 0;
var gColor;

function showLargePicture(obj) {
    /*var arrPos = getPosition(obj);
    
    var imgLarge = document.createElement("img");
    imgLarge.src = obj.src;
    
    var divLarge = document.getElementById("div_large");
    divLarge.innerHTML = "";
    divLarge.appendChild(imgLarge);
     
    divLarge.style.display = "";
    divLarge.style.width = imgLarge.width+"px";
    */
    window.open(obj.src, "_picture", "resizable=yes,scrollbars=yes,directories=no,location=no,menubar=no,toolbar=no");
}

function reloadPicture(container, path)
{
    document.getElementById('img_'+container).src = path;
    if (path == "") {
        document.getElementById(container).value = path; 
        alert(utf8_encode("Clique em SALVAR para salvar as mudanças"));
    }
    document.getElementById("div_upload").style.display = "none";
}

function reloadFile(container, path, file)
{   
    document.getElementById('a_'+container).href = path;                               
    document.getElementById('a_'+container).innerHTML = file;
    document.getElementById(container).value = file;
    document.getElementById("div_upload").style.display = "none";   
}

function getPosition(obj) {
    scwEle=obj;
    
    var offsetTop=scwEle.offsetTop;
    var offsetLeft=scwEle.offsetLeft;
    
    do {
        scwEle=scwEle.offsetParent;
        offsetTop +=parseInt(scwEle.offsetTop, 10);
        offsetLeft+=parseInt(scwEle.offsetLeft,10);
    } while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML');
    
    var retArray = new Array(offsetTop, offsetLeft);
    return retArray; 
}

var xml_form, ctl_name;
 
function OpenDialog(url, vxml_form, vctl_name, obj) {
    xml_form = vxml_form;
    ctl_name = vctl_name;
            
    arrPos = getPosition(obj);
    
    var theIFrame = document.getElementById("iframe_help");                                                 
    var theDiv = document.getElementById("div_help");
    theDiv.style.top = (arrPos[0]-200)+"px";
    //theDiv.style.left = (arrPos[1]-600)+"px";
    
    theIFrame.src = "../"+url+"&DialogLayout=1";
    window.setTimeout("ShowDialog();", 2000);
}
            
function ShowDialog() {        
    var theDiv = document.getElementById("div_help");
    theDiv.style.display = "";
}

function CloseDialog(obj) {
    var theDiv = document.getElementById("div_help");
    theDiv.style.display = "none";
    //obj.style.display="none";
    //alert(xml_form);
    if (xml_form != "")
    {
        ReloadControl();
    }
}

function ReloadControl() {
    //window.open("index.php?fuseaction=Form.ReloadControl&xml_form="+xml_form+"&ctl="+ctl_name);
    http("GET", "index.php?fuseaction=Form.ReloadControl2&xml_form="+xml_form+"&ctl="+ctl_name, "ReloadControl_cb");
}

function ReloadControl_cb(result) {
    var objCtl = document.getElementById(ctl_name);
    var oldValue = objCtl.value;
    objCtl.innerHTML = "";
                                      
    if (result) {
        LoadOptions(objCtl, result);
        objCtl.value = oldValue;
    }
}

function LoadOptions(objCombo, arrOptions) {
    for (var i in arrOptions) {   
        var option = document.createElement("OPTION");
        option.text = arrOptions[i]._text;
        option.value = arrOptions[i]._value;
        objCombo.options.add(option);
    }
}
                                                                                      
function ShowUploadDialog(container, path, width, height, obj, fuseaction) {
    var theForm = document.getElementById("frm_upload");
    theForm.path.value = path;
    theForm.width.value = width;
    theForm.height.value = height;
    theForm.container.value = container;
    
    if (fuseaction != undefined)
        theForm.fuseaction.value = fuseaction;

    arrPos = getPosition(obj);
                                                     
    var theDiv = document.getElementById("div_upload");
    theDiv.style.top = arrPos[0]+"px";
    theDiv.style.left = (arrPos[1]-100)+"px";
    theDiv.style.display = "";
} 

function redLabelsNew(firstLoad) {
	var obj;
	
	for (i=0 ; i<arrMandatoryFields.length ; i++) {
		obj = document.getElementsByName(arrMandatoryFields[i])[0];
		if (obj != null)			
			redLabelNew(obj, firstLoad);
	}
}

function redLabelNew(obj, firstLoad)
{
    if (gColor == undefined) gColor = "black";  
	if (obj.tagName.toLowerCase() == "input" && obj.type.toLowerCase() == "radio") {
		var options = document.getElementsByName(obj.name);
		color = "red";
		for (j=0 ; j<options.length ; j++) {
			if (options[j].checked) {
				color = gColor;
				break;
			}
		}
	} else {
		if (obj.value == "" || obj.value == undefined || obj.value == null) {
			if (obj.disabled)
				color = gColor;
			else
				color = "red";
		} else	
			color = gColor;
	}
	
	try {
		document.getElementById("td_"+obj.name).style.color = color;
	} catch (ex) {}	
	
	if (firstLoad != true) {
	    if (eval("typeof "+obj.name+"_onchange == 'function'"))
	  		eval(obj.name+"_onchange(obj);");		
	}
}

function formatCurrency(obj) {
    num = obj.value;
    num = num.toString().replace(/\$|\,/g,'');
    num = num.replace(",","");
    num = num.replace(".","");

    if(isNaN(num))
        num = "0";

    num = num/100;
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();

    if(cents<10)
        cents = "0" + cents;

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+'.'+ num.substring(num.length-(4*i+3));
    obj.value = (((sign)?'':'-') + num + ',' + cents);
}

// Validate key pressed
function validateKeyPressed(dataType,e,element)
{
  // Get the key code
  if(!e)
    e=window.event;
  key = e.keyCode ? e.keyCode : e.which;
  // 1 - Let some keys to be pressed
  // BS = 8 / TAB = 9 / END = 35 / HOME = 36 / LEFT = 37 / RIGHT = 39 / DEL = 46
  if ( key==8 || key==9 || key==35 || key==36 || key==37 || key==39) {
    return true;
  }
  
    // 2 - Let only authorized types to be used
    switch(dataType)
    {                             
      case "Number":
      case "Currency":
      case "CPF":
        if ( (key<48 || key>57)  )
          return false;
      break;

      case "Telephone":
        if ( key<48 || key>57 || key==46)
          return false;
      break;
      
      case "Char":
        if ( (key<65 || (key>90 && key<97) || key>122) && key!=32 && key!=46)
          return false;
      break;
      
      case "Email":
        if ( 
             (key<48 || key>57) 
             && 
             (key<64 || (key>90 && key<97) || key>122) 
             && key!=46 && key!=45
           )
          return false;          
      break;
    }

}


function hideSelects( protected_id,show )
{
  var is_ie/*@cc_on = {
    // quirksmode : (document.compatMode=="BackCompat"),
    version : parseFloat(navigator.appVersion.match(/MSIE (.+?);/)[1])
  }@*/;

  if (is_ie && (is_ie.version < 7))
  {
    // Get all select HTML elements
    selects = document.getElementsByTagName("select");

    // For each founded do:    
    for (i=0; i<selects.length; i++)
    {
      atual = selects[i];

      // Check if the select is outside the protected div
      process = true;
      while ( atual.parentNode != undefined )
      {
        if ( atual.parentNode.id==protected_id )
        {
          process = false;
          break;
        }
		atual = atual.parentNode;
      }
      
      if ( process )
        if ( show==true )
        {
          //selects[i].style.display = '';
          selects[i].style.visibility = 'visible';
        }
        else
        {
          //selects[i].style.display = 'none';
          selects[i].style.visibility = 'hidden';
        }
    }
  }
}

function validar_cpf_cnpj(obj) {
    var invalid, s;
    invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;

    var s;


    // inicio de verificacao de cnpj ou cpf
    if (obj.value.length == 0) {
        return false; 
    }

    s = limpa_string(obj.value);


    // checa se é cpf
    if (s.length == 11) {
        if (valida_CPF(obj.value) == false ) {
            alert(utf8_encode("O CPF não é válido"));
            obj.select();
            return false;
        }
    } // checa se é cgc
    else if (s.length == 14) {
        if (valida_CGC(obj.value) == false ) {
            alert(utf8_encode("O CNPJ não é válido."));
            obj.select();
            return false; 
        }
    }
    else {
        alert(utf8_encode("O CPF/CNPJ não é válido."));
        obj.select();
        return false;
    }
}

function utf8_encode(s) {
  //return unescape( encodeURIComponent( s ) );
  return s;
}

function utf8_decode(s) {
  return decodeURIComponent( escape( s ) );
}

function limpa_string(S){
    // Deixa so' os digitos no numero
    var Digitos = "0123456789";
    var temp = "";
    var digito = "";

    for (var i=0; i<S.length; i++) {
        digito = S.charAt(i);
        if (Digitos.indexOf(digito)>=0) {
            temp=temp+digito 
        }
    }
    return temp
}


function valida_CPF(s) {
    var i;
    s = limpa_string(s);
    var c = s.substr(0,9);
    var dv = s.substr(9,2);
    var d1 = 0;
    
    for (i = 0; i < 9; i++) {
        d1 += c.charAt(i)*(10-i);
    }
    
    if (d1 == 0) return false;
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1) {
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 9; i++) {
        d1 += c.charAt(i)*(11-i);
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1) {
        return false;
    }
    return true;
}

function valida_CGC(s)
{
    var i;
    s = limpa_string(s);
    var c = s.substr(0,12);
    var dv = s.substr(12,2);
    var d1 = 0;
    for (i = 0; i < 12; i++) {
        d1 += c.charAt(11-i)*(2+(i % 8));
    }       
    if (d1 == 0) return false;
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    
    if (dv.charAt(0) != d1) {
        return false;
    }

    d1 *= 2;
    for (i = 0; i < 12; i++) {
        d1 += c.charAt(11-i)*(2+((i+1) % 8));
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1) {
        return false;
    }
    return true;
}
