var SUBMIT_FLAG=false;

function submitForm(f, validationFunc)
{
 var res= false;

 if (!SUBMIT_FLAG)
 	{
 	  if (validationFunc!='' && validationFunc!=null &&
 	  	  !eval(validationFunc) )
 	  	return false;

 	  SUBMIT_FLAG = true;
 	  return true;
 	}
 else {
 	// alert('BE PATIENT!!');
 	return false;
 	}
}

function Utils() {
	this.name = 'Util';
	this._link = '#';
}

Utils.prototype.newWindow = function() { window.open(this._link) };

Utils.prototype.exec = function(cmd,link)
{
	this._link = link;
	eval("this."+cmd);
}

Utils.prototype.getBrowse = function()
{
	if(navigator.userAgent.indexOf('Mac_PowerPC') > -1)
	{
		return("MAC");
	}
	else if(navigator.userAgent.indexOf('MSIE 6.0') > -1)
	{
		return("WINIE");
	}
	else if(navigator.userAgent.indexOf('Gecko') > -1)
	{
		return("MOZILLA");
	}
}

function popjanparams(objName, windowName, params)
{
	window.open(objName, windowName, params);
}

function mostrarNomeUsuario()
{
	var username = getCookie('usuario'); 

	if (username != null) {
		var paths = new Array;
		username = Url.decode(username);
		paths = username.split(';');
		for(var x=0;x < paths.length;x++) {
			paths[x] = paths[x].replace(/\+/gi, " ");
		}
		// Pego só o primeiro nome do usuário
		var primeiroNome = paths[1].split(' ');
		document.write(primeiroNome[0]);
	}
	else {
		document.write("visitante");
	}
}

var Url = {
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}

function getCookie (name)
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;

	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function getCookieVal (offset)
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;

	return unescape(document.cookie.substring(offset, endstr));
}

function localSetCookie (name, value) {
	
	var expDays = 30;
	var exp = new Date();
	exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

	var argv = localSetCookie.arguments;
	var argc = localSetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	if (domain == null) {
          domain = ".abril.";
          domain = domain + "com.br";
    }
	document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
           ((path == null) ? ("; path=" + "/") : ("; path=" + "/")) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}

function consultarCEP(sgluf, numCep)
{
	var URL = document.location.protocol + "//" + document.location.host + "/cep/dne.do";

    // Faz um trim na uf
    sgluf = trim(sgluf);
    // Faz um trim no cep
    numCep = trim(numCep);
	// Se um CEP for informado, faz a consulta
    if (numCep == "" || numCep.length < 5) {
		URL += "?metodo=prepararConsultar";
	}
	else {
		URL += "?metodo=consultar";
		URL += "&cep=" + numCep;
	}
	URL += "&sglUf=" + sgluf;
	URL += "&range=15";
	//URL += "&templateTeste=true";

	var w = screen.availWidth;
	var h = screen.availHeight;
	var popW = 650, popH = 562;
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	window.open(URL,'PesquisarCEP','scrollbars=yes,resizable=no,width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos);
}

function getValue(obj) {
  for (i=0; i<obj.length; i++) {
	if (obj[i].checked) return obj[i].value;
  }
  return "";
}

function validarCPF(obj_cpf) {
    var i;
    var dig1 = 0;
    var dig2 = 0;
	var CPFValue = obj_cpf.value;

    if (trim(CPFValue) == null || trim(CPFValue) == "") return false;

    if (trim(CPFValue).length > 11 || trim(CPFValue).length < 11) {
		alert("CPF inválido.");
        return false;
    }

    for (i=1; i<=9; i++){
      dig1= dig1 + parseInt(CPFValue.substring(i-1,i),10) *i;
    }

    dig1= dig1%11;

    if (dig1==10) dig1=0;

    if (dig1 != CPFValue.substring(9,10)) {
		alert("CPF inválido.");
		return false;
	}

    for (i=2; i<=10; i++){
       dig2= dig2 + parseInt(CPFValue.substring(i-1,i),10)*(i-1);
    }

    dig2= dig2%11;

    if (dig2==10) dig2=0;

    if(dig2 != CPFValue.substring(10,11)){
		alert("CPF inválido.");
		return false;
    }
    else{
      return true;
    }

}

function validarCNPJ(obj_cnpj) {
	var dig1 = 0;
	var dig2 = 0;
	var i;
	var fator;
	var CNPJValue = obj_cnpj.value;

	if (CNPJValue ==null || trim(CNPJValue).length > 14 || trim(CNPJValue).length < 14 ) {
		alert("CNPJ inválido.");
		return false;
	}

	// primeiro digito
	fator=14;
	for (i=12; i>=1; i--) {
		if (i==4) fator= 6;
		dig1= dig1 + parseInt(CNPJValue.substring(i-1,i),10)*(fator-i);
	}

	dig1= dig1%11;
	if (dig1==0 || dig1==1) dig1=0;
	else dig1= 11-dig1;

	if (!parseInt(dig1,10) == CNPJValue.substring(12,13) ) {
		alert("CNPJ inválido.");
		return false;
	}

	// segundo digito
	fator=15;
	for (i=13; i>=1; i--) {
		if (i==5) fator= 7;
		dig2= dig2 + parseInt(CNPJValue.substring(i-1,i),10)*(fator-i);
	}

	dig2= dig2%11;
	if (dig2==0 || dig2==1) dig2=0;
	else dig2= 11-dig2;

	if( parseInt(dig2,10) != (CNPJValue.substring(13,14))) {
		alert("CNPJ inválido.");
		return false;
	}

	return true;
}

//-------------------------------------------------------------------
// This function accepts a string variable and verifies if it is in
// the proper format for an e-mail address or not.
// The function returns true if the format is valid, false if not.
//-------------------------------------------------------------------
function isEmail(email) {
    invalidChars = " ~\'^\`\"*+=\\|][(){}$&!#%/:,;";

    // Check for null
    if (email == "") {
        return true;
    }

    // Check for invalid characters as defined above
    for (i=0; i<invalidChars.length; i++) {
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar,0) > -1) {
            return false;
        }
    }
    lengthOfEmail = email.length;
    if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
        return false;
    }
    Pos = email.indexOf("@",1);
    if (email.charAt(Pos + 1) == ".") {
        return false;
    }
    while ((Pos < lengthOfEmail) && ( Pos != -1)) {
        Pos = email.indexOf(".",Pos);
        if (email.charAt(Pos + 1) == ".") {
            return false;
        }
        if (Pos != -1) {
            Pos++;
        }
    }

    // There must be at least one @ symbol
    atPos = email.indexOf("@",1);
    if (atPos == -1) {
        return false;
    }

    // But only ONE @ symbol
    if (email.indexOf("@",atPos+1) != -1) {
        return false;
    }

    // Also check for at least one period after the @ symbol
    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1) {
        return false;
    }
    if (periodPos+3 > email.length) {
        return false;
    }
    return true;
}

//-------------------------------------------------------------------
// Verify if the string passed is a valid date (DD/MM/YYYY)
//   Returns true or false
//-------------------------------------------------------------------
function isDate(dateStr) {
  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var matchArray = dateStr.match(datePat); // is the format ok?
  if (matchArray == null) {
    //alert("Entre uma data válida, no formato (dd/mm/yyyy).");
    return false;
  }
  month = matchArray[3]; // parse date into variables
  day   = matchArray[1];
  year  = matchArray[5];
  if (month < 1 || month > 12) { // check month range
    //alert("O mês deve estar entre 1 e 12.");
    return false;
  }
  if (day < 1 || day > 31) {
    //alert("O dia deve estar entre 1 e 31.");
    return false;
  }
  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    //alert("O mês "+month+" não tem 31 dias!")
    return false;
  }
  if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day > 29 || (day==29 && !isleap)) {
      //alert("Fevereiro de " + year + " não tem " + day + " dias!");
      return false;
    }
  }
  return true; // date is valid
}

function trim(str) {
  return str.replace(/^\s*|\s*$/g,"");
}

function validateNumber(snum) {
  var i=0;

  for (i=0; i<snum.length; i++)
    if (snum.charAt(i)<'0' || snum.charAt(i)>'9')
      return false;

  return true;
}

function userLogged() {
	
	username = getCookie('usuario');
	ticket = getCookie('ticket');

	if ((username == null) && (ticket == null)) return false;
	
	return true;
}

function exibeSair() {
	
	if (userLogged()) {
		var sair = document.getElementById('sair');
		sair.style.display = 'block';
	}
}

function logout() {
	clearCookie();
	window.location.reload();
}

function clearCookie() {
	pathname = location.pathname;
	myDomain = pathname.substring(0,pathname.lastIndexOf('/')) +'/';
	var largeExpDate = new Date();
	largeExpDate.setTime(largeExpDate.getTime() + (60 * 24 * 3600 * -1000));
	localSetCookie('usuario',"unknown",largeExpDate,myDomain);
	localSetCookie('Ticket',"unknown",largeExpDate,myDomain);
	localSetCookie('aapgCookie',"unknown",largeExpDate,myDomain);
	localSetCookie('aapgPersonCookie',"unknown",largeExpDate,myDomain);
	localSetCookie('aapgTokenCookie',"unknown",largeExpDate,myDomain);
}

function openWindow(url, name)
{ var winWidth = 488;
  var winHeight = 450;
  var winTop = parseInt((screen.availHeight - winHeight) / 2);
  var winLeft = parseInt((screen.availWidth - winWidth) / 2);
			  
  popupWin = window.open(url,name,"width=" + winWidth + ",height=" + winHeight + ",top=" + winTop + ",left=" + winLeft + ",resizable=no,scrollbars=no,statusbar=no");
  if (popupWin.opener == null) popupWin.opener = self;
}
