// fogeca.js

//=================================================================
	var sPrefix = 'O campo ';
	var sSuffix = ' é de preenchimento obrigatório!';
	var sSuffix_num = 'tem que ser um valor numérico';
	var sTitle = 'Personel Information';
	var sButton = 'OK';
	var sChange = '<BR><BR>Please change this before submitting';

	var isIE = document.all?true:false;
	var isNS = document.layers?true:false;	

//=================================================================
//=================================================================

//=================================================================
// Verifica o form de preenchimento de uma instalação de determinada empresa
//=================================================================
function ValidateInstalation() {
	var oForm = GetForm(0);
	var firstElementError = "";
	var isError = "";

	if (!validateElement(oForm.elements['name'], 1, 'text')) {
		isError += "-" + " 'Nome' " + sSuffix + "\n";
		firstElementError = "name";
	}

	if (!validateElement(oForm.elements['contactemail'], 0, 'email')) {
		isError += "-" + " 'Email geral' não apresenta um formato válido." + "\n";
		if (firstElementError=="")
			firstElementError = "contactemail";
	}


	if (!validateSize(oForm.elements['schedules'], 1000, 1,0)) {
		isError += "-" + " 'Horários' está limitado a 1000 caracteres." + "\n";
		if (firstElementError=="")
			firstElementError = "schedules";
	}

	if (isError.length>0) {
		alert("Foram detectadas as seguintes incorrecções no preenchimento do formulário: \n" + isError);
		SelectElement(oForm.elements[firstElementError]);
		return false;
	}

	return true;
}

//=================================================================
// Verifica o form de preenchimento de uma empresa
//=================================================================
function ValidateCompany() {
	var oForm = GetForm(0);
	var firstElementError = "";
	var isError = "";

	if (!validateElement(oForm.elements['name'], 1, 'text')) {
		isError += "-" + " 'Nome' " + sSuffix + "\n";
		firstElementError = "name";
	}

	if (!validateElement(oForm.elements['respemail'], 0, 'email')) {
		isError += "-" + " 'Email do Responsável' não apresenta um formato válido." + "\n";
		if (firstElementError=="")
			firstElementError = "respemail";
	}

	if (isError.length>0) {
		alert("Foram detectadas as seguintes incorrecções no preenchimento do formulário: \n" + isError);
		SelectElement(oForm.elements[firstElementError]);
		return false;
	}

	return true;
}

// ----------------------------------------------------------------------

function change_bgcolor(id){
//	alert(id)
//	alert(document.getElementById(id))
//	alert(document.getElementById(id).style.backgroundColor)
	if (document.getElementById(id)!=null)
		if (document.getElementById("top_l_" + id).style.backgroundColor == "#ffffff") {
			document.getElementById("top_l_" + id).style.backgroundColor = "#fc4f00";
			document.getElementById("top_c_" + id).style.backgroundColor = "#fc4f00";
			document.getElementById("top_r_" + id).style.backgroundColor = "#fc4f00";

			document.getElementById("top_l2_" + id).style.backgroundColor = "#fc4f00";
			document.getElementById("top_r2_" + id).style.backgroundColor = "#fc4f00";

			document.getElementById("bottom_l2_" + id).style.backgroundColor = "#fc4f00";
			document.getElementById("bottom_r2_" + id).style.backgroundColor = "#fc4f00";

			document.getElementById("bottom_l_" + id).style.backgroundColor = "#fc4f00";
			document.getElementById("bottom_c_" + id).style.backgroundColor = "#fc4f00";
			document.getElementById("bottom_r_" + id).style.backgroundColor = "#fc4f00";
		} else {
			document.getElementById("top_l_" + id).style.backgroundColor = "#ffffff";
			document.getElementById("top_c_" + id).style.backgroundColor = "#ffffff";
			document.getElementById("top_r_" + id).style.backgroundColor = "#ffffff";

			document.getElementById("top_l2_" + id).style.backgroundColor = "#ffffff";
			document.getElementById("top_r2_" + id).style.backgroundColor = "#ffffff";

			document.getElementById("bottom_l2_" + id).style.backgroundColor = "#ffffff";
			document.getElementById("bottom_r2_" + id).style.backgroundColor = "#ffffff";

			document.getElementById("bottom_l_" + id).style.backgroundColor = "#ffffff";
			document.getElementById("bottom_c_" + id).style.backgroundColor = "#ffffff";
			document.getElementById("bottom_r_" + id).style.backgroundColor = "#ffffff";
		}
}


// ALternar imagens Menu //

function toggleImgMenu(id, imgName){
	
	
	if (document.images[imgName].src.indexOf( "_on.jpg" ) == -1)
		//imagem OFF
		document.images[imgName].src = "/media/common/images/" + imgName + "_on.jpg"
	else
		//imagem ON
		document.images[imgName].src = "/media/common/images/" + imgName + "_off.jpg"
}
/*
function validate_submit()
{
	var lista = ""
	for (n=0; n<document.images[n].length; n++)
		if (document.images[n].src.indexOf( "_on.jpg" ) == 0)
			lista = lista + document.images[n].name + ";"
}
*/
function centerPopup(popup_name,popup_url,popup_with,popup_height,myWidth,myHeight,myScrollbar) {
  if(!myWidth) {myWidth = 10;}
  if(!myHeight){myHeight = 50;}
  if(!myScrollbar){myScrollbar = 0;}
  var popup_left = (window.screen.width/2)  - (popup_with/2 + myWidth);
  var popup_top  = (window.screen.height/2) - (popup_height/2 + myHeight);
  window.open(popup_url ,popup_name,"toolbar=no,location=no,status=no,menubar=no,scrollbars=" + myScrollbar + ",resizable=no,width=" + popup_with + ",height=" + popup_height + ",left=" + popup_left + ",top=" + popup_top + ",screenX=" + popup_left + ",screenY=" + popup_top);
}
// ----------------------------------------------------------------------
// Funções Gerais
function GetForm(n) {
	return document.forms[n];
}

function Verified() {
	GetForm().submit();
}

function isMobileNumber(Element) {
	
	tel= ElementValue(Element);
	var x=tel.toString();
	var ind=x.substring(0,2)

	if (x.length!=9) return false;
	if(!((ind=="91")||(ind=="93")||(ind=="96"))) return false

	return true
}

function validateElement(Element, mandatory, type,size) {
	var bElementEmpty = ElementEmpty(Element);
	
	if (mandatory && bElementEmpty) return false;

	if (size>0 && ElementValue(Element).length > size) return false;

	if (!bElementEmpty) {
		switch (type) {
			case 'email':
				if (isEMail(ElementValue(Element))) return true;
				else return false;
				break;			
			case 'date':
				if (isDate(ElementValue(Element))) return true;
				else return false;
				break;
			case 'number':
				if (isNumeric(ElementValue(Element))) return true;
				else return false;
				break;		
			default:
				return true;
			}
	}
	return true;
}

function validateSize(Element,size,dif,mandatory) {
	
	// tem que ter exactamente o mesmo comprimento que size
	switch (dif) {
		case 0:				// tem que ter exactamente size posicoes
			var bElementEmpty = ElementEmpty(Element);
	
			if((mandatory==0)&&ElementValue(Element).length==0){
				return true;
			} else {
				if ((ElementValue(Element).length - size) !=0) 
					return false;
			}	 
				 
		case -1:			//no minimo tem que ter size posicoes

			if((mandatory==0)&&ElementValue(Element).length==0){
					 return true;
			} else {
				if ((ElementValue(Element).length - size) <0) 
					return false;
			}	 

		case 1:
			// no maximo pode ter tamanho size
			if ((ElementValue(Element).length - size) >0) return false;
		default:
			return true; 
		}
	return true;
}

function SelectOption(campo,valor) {
	
	var lista;
	var pos=0;
	var oForm = GetForm(0);
	lista = oForm[campo].options;

	for(var i=0; i<lista.length; i++)
		if(lista[i].value==valor)
			lista[i].selected=true;
}

function SelectRadioOption(campo,valor) {
	var lista;
	var pos=0;
	var oForm = GetForm(0);

	for (var i=0;i < oForm[campo].length;i++) 
		if (oForm[campo][i].value==valor)
			oForm[campo][i].checked =true
}

function SelectElement(Element) {
	var stype=Element.type;
	if (stype+''=='undefined') stype=Element[0].type;
	switch (stype) {
		case 'select-one':
			break;
		case 'radio':
			break;
		case 'select-multiple':
			break;		
		default:
			Element.select(); 
	}
}
	
function ElementEmpty(Element) {
	var stype=Element.type;
	if (stype+''=='undefined') stype=Element[0].type;
	switch (stype) {
		case 'select-one':
			return (Element.options[Element.selectedIndex].value=='');
			break;
		case 'radio':
			return RadioEmpty(Element);
			break;
		default:
			return (Element.value=='');
	}
	return (Element.value=='');
}
	
function RadioEmpty(Element) {
	for (var i=0;i < Element.length;i++) {
		if (Element[i].checked) return false;
	}		
	return true;
}

function ElementValue(Element) {
	var stype=Element.type;
	if (stype+''=='undefined') stype=Element[0].type;
	switch (stype) {
		case 'select-one':
			return Element.options[Element.selectedIndex].value;
			break;		
		case 'radio':
			return RadioValues(Element);
			break;
		default:
			return Element.value; 
	}
	return Element.value; 
}

function isChecked(Element) {
	if(Element.checked==true)
		return true;

	return false	
}

function RadioValues(Element) {
	for (var i=0;i < Element.length;i++) {
		if (Element[i].checked) return Element[i].value;
	}
	return '';
}
function RadioIndex(Element) {
	for (var i=0;i < Element.length;i++) {
		if (Element[i].checked) return i;
	}		
	return -1;
}		

function isNumeric(s) { 
	if (isEmpty(s)) 
	if (isNumeric.arguments.length == 1) return false; 
	else return (isNumeric.arguments[1] == true); 
	for (var i = 0; i < s.length; i++){
		if (!isDigit(s.charAt(i))) return false;
	}
	return true; 
} 

function isSignedNumeric(s) { 
	if (isEmpty(s)) {
		if (isSignedNumeric.arguments.length == 1) return false; 
	    else return (isSignedNumeric.arguments[1] == true); 
    } else {
  		var startPos = 0; 
    	var secondArg = false; 
    	if (isSignedNumeric.arguments.length > 1) secondArg = isSignedNumeric.arguments[1];
    	if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") ) startPos = 1; 
    	return (isNumeric(s.substring(startPos, s.length), secondArg)) 
  	} 
} 

function isvalidString(valor) {
	var position=-1;
	var strvalor = new String(ElementValue(valor));
	
	invalidchar = new Array(" ","'")
	for(var i=0;i<invalidchar.length; i++){
		if(strvalor.indexOf(invalidchar[i])!=-1)
			return false;
	}	
	return true;
}

function isNonnegativeNumeric (s) { 
	var secondArg = false; 
	if (isNonnegativeNumeric.arguments.length > 1) secondArg = isNonnegativeNumeric.arguments[1];
  	return (isSignedNumeric(s, secondArg) && ( (isEmpty(s) && secondArg) || (parseInt(s, 10) >= 0) ) );
} 

function isNumericInRange(s, a, b) { 
	if (isEmpty(s)) {
	  	if (isNumericInRange.arguments.length == 1) return defaultEmptyOK; 
    	else return (isNumericInRange.arguments[1] == true); 
    }
 	if (!isNumeric(s, false)) return false; 
	var num = parseInt (s, 10); 
	return ((num >= a) && (num <= b)); 
} 

function isDate(s) {
	
	var day,month,year;
	 
	if (isEmpty(s)) {
		if (isDate.arguments.length == 1) return false; 
		else return (isDate.arguments[1] == true);
	} else {
		if ((s.length == 8 || s.length == 10) && (s.charAt(2) == "/" || s.charAt(2) == "-") && (s.charAt(5) == "/" || s.charAt(5) == "-")) { 
			day = s.charAt(0) + s.charAt(1); 
			month = s.charAt(3) + s.charAt(4); 
			if (s.length == 8) year = s.charAt(6) + s.charAt(7); 
			else year = s.charAt(6) + s.charAt(7) + s.charAt(8) + s.charAt(9); 

			if (ValidateDate(year, month, day))return true; 
			else return false; 
	  	}
	  	else return false;
	}
} 

function isYear(s) { 
	if (isEmpty(s)) {
  		if (isYear.arguments.length == 1) return false; 
  		else return (isYear.arguments[1] == true); 
  	} else {
  		if (!isNonnegativeNumeric(s)) return false;
  		else return ((s.length == 2) || (s.length == 4));
  	}
}

function isMonth(s) { 
	if (isEmpty(s)) {
  		if (isMonth.arguments.length == 1) return false; 
    	else return (isMonth.arguments[1] == true); 
    } else return isNumericInRange (s, 1, 12);
}

function isDay(s) {
	if (isEmpty(s)) {
		if (isDay.arguments.length == 1) return false; 
		else return (isDay.arguments[1] == true); 
	}
	else return isNumericInRange (s, 1, 31); 
} 

function daysInFebruary(year) {return ( ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 ); } 

function ValidateDate(year, month, day) { 
	if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false; 
	var daysInMonth = new Array();;
	daysInMonth[1] = 31;
	daysInMonth[2] = daysInFebruary(parseInt(year));
	daysInMonth[3] = 31; 
	daysInMonth[4] = 30; 
	daysInMonth[5] = 31; 
	daysInMonth[6] = 30; 
	daysInMonth[7] = 31; 
	daysInMonth[8] = 31; 
	daysInMonth[9] = 30; 
	daysInMonth[10] = 31; 
	daysInMonth[11] = 30; 
	daysInMonth[12] = 31;  
	if (parseInt(day) > daysInMonth[parseInt(month)]) return false; 
	else  return true;
}

function isEmpty(s) {return ((s == null) || (s.length == 0))} 

function isDigit(c) {return ((c >= "0") && (c <= "9"))} 

function isEMail (emailStr) {
	var emailPat=/^(.+)@(.+)$/;
	var specialChars='\\(\\)<>@,;:\\\\\\\"\\.\\[\\]';
	var validChars='\[^\\s' + specialChars + '\]';
	var quotedUser='(\"[^\"]*\")';
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word='(' + atom + '|' + quotedUser + ')';
	var userPat=new RegExp('^' + word + '(\\.' + word + ')*$');
	var domainPat=new RegExp('^' + atom + '(\\.' + atom + ')*$');

	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) return false;

	var user=matchArray[1];
	var domain=matchArray[2];

	if (user.match(userPat)==null) return false;

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {if (IPArray[i]>255) return false;}
    	return true;
	}

	var domainArray=domain.match(domainPat);
	if (domainArray==null) return false;

	var atomPat=new RegExp(atom,'g');
	var domArr=domain.match(atomPat);
	var len=domArr.length;

	if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) return false;
	if (len<2) return false;
	return true;
}

function roundOff(value, precision) {
	value = new String(value);  //convert value to string
	value=value.replace(',','.');
	precision = parseInt(precision);

	var whole = '' + Math.round(value * Math.pow(10, precision));
	if (whole.length==2) whole='0' + whole;
	if (whole.length==1) whole='00' + whole;
	var decPoint = whole.length - precision;

	if(decPoint != 0)  {
	  	result = whole.substring(0, decPoint);
    	result += '.';
    	result += whole.substring(decPoint, whole.length);
    } else result = whole;

	if (result=='.0' || result=='N.aN') result='0.00';
	return result;
}

function ValidateChecked(Element) {

	for (var i=0;i<Element.length;i++)
		if(Element[i].checked)
			return true;

	return false;
}

function EnableALL(){
	var oForm = document.forms[0];
	var fields = oForm.elements;
	for(var x=0;x<fields.length;x++)
		fields.elements[x].disabled=false
}


// -----------  Só permite a introdução de numeros no campo  ----------
//onkeypress="return onlyNumbers(event)"
function onlyNumbers(e) {
	var unicode = e.charCode? e.charCode : e.keyCode;
	//if the key isn't the backspace - Delete - Dot - Left Arrow - Right Arrow - Tab(which we should allow)
	if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=39 && unicode!=9) {
		if (unicode<48 || unicode>57) //if not a number
			return false //disable key press
	}
	return true;
}

// -----------  Limite o tamanho do conteúdo de um objecto ----------
//onkeyup="return limitlength(this, 20)"
function limitlength(obj, length){
	var maxlength=length;
	if (obj.value.length > maxlength)
		obj.value = obj.value.substring(0, maxlength);
}

// -----------  Preenche o campo Dia  -------------------------------
function populate_day(field,sel) {
	var lista, pos;
	var dias = new Array("","01", "02", "03", "04", "05", "06", "07", "08", "09"); 
	pos=0
	lista = field.options
	lista[pos++]=new Option("Dia","")
	for (var i=1; i<=9; i++){
		lista[pos]=new Option(dias[i],i)
		if(sel==i)
			lista[pos].selected=true;
		pos++
	}
	for (var j=10; j<=31; j++){
		lista[pos]=new Option(j,j)
		if(sel==j)
			lista[pos].selected=true;

		pos++
	}
}
// -----------  Preenche o campo Mês Númerico  -------------------------------
function populate_month(field,sel) {
	var lista, pos;
	var meses = new Array("", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"); 
	pos=0
	lista = field.options
	lista[pos++]=new Option("Mês","")
	for (var i=1; i<=12; i++){
		lista[pos]=new Option(meses[i],i)
		if(sel==i)
			lista[pos].selected=true;

		pos++
	}
}
// -----------  Preenche o campo Mês Extenso  -------------------------------
function populate_monthDesc(field,sel) {
	var lista, pos;
	var meses = new Array("", "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"); 
	pos=0
	lista = field.options
	lista[pos++]=new Option("Mês","")
	for (var i=1; i<=12; i++){
		lista[pos]=new Option(meses[i],i)
		if(sel==i)
			lista[pos].selected=true;

		pos++
	}
}
// -----------  Preenche o campo Ano  -------------------------------
function populate_year(field,sel,startYear,endYear) {
	var lista, pos;
	pos=0
	lista = field.options
	lista[pos++]=new Option("Ano","")
	for (var i=endYear; i>=startYear; i--){
		lista[pos]=new Option(i,i)
		if(sel==i)
			lista[pos].selected=true;
		pos++
	}
}
// ------------------ Simulação Crédito, Leasing e ALD ---------------
// PVP - Preço de Venda ao Público
// Entrada - Entrada Inicial
// Taxa - Taxa de Juro
// Is - Imposto de Selo
// N - Número de prestações
// VR - valor Residual
function simulCredit(PVP,Entrada,Taxa,Is,N){
	Is = Is / 100;
	Taxa = Taxa / 100;
	var CF = parseFloat(PVP - Entrada);
	var Tjm = Taxa / 12;

	var Mensalidade = CF * ((Tjm * (1 + Is)) / (1 - (Math.pow(1 + (Tjm * (1 + Is)), -1 * N))));
alert("Mensalidade Credito : " + Mensalidade.toFixed(2));
	return Mensalidade;
}

function simulLeasing(PVP, AL, Taxa, N, VR){
	Taxa = Taxa / 100;
	Tjm = Taxa / 12;
	var entradazero = 0;
	// se a entrada dor zero então o primeiro aluguer é a entrada, logo
	// tenho que adicionar 1 ao disivor da formula
	// Resulta da equação de igualar a prestação ao primeiro aluguer
	if (AL == 0)
		entradazero = 1;

	var Renda = (PVP - AL - VR * (Math.pow(1 + Tjm, -1 * N))) / (((1 - (Math.pow(1 + Tjm, -1 * N + 1))) / Tjm) + entradazero);
alert("RENDA ALD : " + Renda.toFixed(2));
	return Renda;
}

function simulALD(PVP, AL, Taxa, N, VR){
	Taxa = Taxa / 100;
	Tjm = Taxa / 12;
// //////// alterar
	N = N + 1;
	var entradazero = 0;
	// se a entrada for zero então o primeiro aluguer é a entrada, logo
	// tenho que adicionar 1 ao divisor da formula
	// Resulta da equação de igualar a prestação ao primeiro aluguer
	if (AL == 0)
		entradazero = 1;

	var Renda = (PVP - AL - VR * (Math.pow(1 + Tjm, -1 * N))) / (((1 - (Math.pow(1 + Tjm, -1 * N + 1))) / Tjm) + entradazero);
	alert("RENDA ALD : " + Renda.toFixed(2));
	return Renda;
}
function simulTAEG(Taxa, VF, SubTotal) {
	var TIR = (Taxa * SubTotal) / VF;
	var TAEG = (Math.pow((1 + (TIR / 12) / 100), 12) - 1) * 100;
	alert("TAEG : " + TAEG.toFixed(2));
	return TAEG;
}
// ------------------------------------------------------------------------------


function clearText(thefield)
{

if (thefield.defaultValue == thefield.value) thefield.value = ""
else {
	if (thefield.value == "") 	thefield.value = thefield.defaultValue
	}
}


