// JavaScript Document
/*CHECKBOX*/
function changeStatus( e , change ){
   
	var c = document.getElementById(change);
    //alert(c.value);
	if(c.value == 'Não'){
		e.src = "images/check_yes.jpg";
		c.value = "Sim";
		e.value =1;
	}
	else{
		e.src = "images/check_no.jpg";
		c.value = "Não";
		e.value =0;
	} 

}




function isNIF(valor)
{
	//x = obj;
	//valor = obj.value;

	if(valor.length == 9)
	{
		var chars = new Array();
		chars = valor.split('');
		c = chars[0];
		
		if (valor == "123456789") {
			return false;
		} else {
	
			if(c == '1' || c == '2' || c == '5' || c == '6' || c == '9')  //digitos iniciais válidos
			{
				checkDigit = (c - '0') * 9;
	
				for(i = 2 ; i <= 8 ; i++)
					checkDigit += (chars[i - 1] - '0') * (10 - i);
	
				checkDigit = 11 - (checkDigit % 11);
			
				if(checkDigit >= 10)
					checkDigit = 0;
				
				if(checkDigit == (chars[8] - '0'))
					return true;
				else {
					return false;
				}
			}
			else {
				return false;
			}
		}
	}
	else {
		return false;
	}
	return false;
}

function isNIB (number) {
	if (checkibancore("pt50"+number) != "1") {
		return false;
	}
	else {
		return true;
	}
}

function isEmail (string) {
	var reg = new	RegExp("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3}$");
	if (reg.test(string)) {
		return true;	
	}
	else {
		return false;	
	}
}

function isEmpty (string) {
	if (string == "") {return false;}
	else {return true;}
}

function isNumber (number) {
	if (number.match(/[^\d^\.]/)) {return false;}
	else {return true;}
}
function hasLength (string, lmin, lmax) {
	if (lmin == lmax) {
		if (string.length == lmin) {
			return true;	
		}
		else {
			return false;	
		}
	}
	if (string.length <= lmin || string.length >= lmax) {
		return false;
	}
	else {
		return true;
	}
}
function isGreaterThan (value, v_compare) {
	if (value > v_compare) {return true;}
	else {return false;}
}
function isSmallerThan (value, v_compare) {
	if (value < v_compare) {return true;}
	else {return false;}
}
function startsWith (value1, value2) {
	var tam = value2.length;
	//alert('tam='+tam);
	//alert('valor='+value1.substring(0,tam));
	if (value1.substring(0,tam) != value2) {
		return false;
	}
	else {
		return true;
	}
}
function radioCheck(target) {
	//alert('here');
	var contents = document.getElementsByName(target);
	for (var i=0; i<contents.length; i++) {
		//alert(contents[i].id+" - "+contents[i].checked);
		if(contents[i].checked) {
			return true;
		}
	}
	return false;
}
function compareEmptyWith (id1, id2) {
	if (isEmpty(getValue(id1)) || isEmpty(getValue(id2))) {
		//alert("true");
		return true;	
	}
	else {
		//alert("false");
		return false;
	}
}
function comparePhones (id1, id2) {
	if (isEmpty(getValue(id1)) || isEmpty(getValue(id2))) {
		if (isNumber(getValue(id1)) || isNumber(getValue(id2))) {
			if (hasLength(getValue(id1), 9, 9) || hasLength(getValue(id2), 9, 9)) {
				return true;	
			}
			else {return false;}
		}
		else {return false;}
	}
	else {
		return false;
	}	
}
function getValue (id) {
	return document.getElementById(id).value;	
}

function isChecked (id) {
	return document.getElementById(id).checked;
}

function focusElem (id) {
	if(document.getElementById(id)) {
		document.getElementById(id).focus()
	}
}

function generalReturn (field, msgStr) {
	alert(msgStr);
	//focusElem (field);
	return false;
}
/**/
/**/
function formVerify (All, names) {
	
	//var All = new Array();
	//All = fields.split('|');
	//var names = new Array();
	//names = f_names.split('|');
	//alert(All);
	var field = new Array();
	
	var f_count = 0;
	
	for ( var i in All )
	{
		var campos = All[i].split(':');
		//alert(All[i]);
		for (var j in campos) {
			if (j%2 != 0) {
				var functions = campos[j].split(',');
				//alert(functions);
				for (var a in functions) {
					var argos = functions[a].split('~');
					//alert (argos);
					if (!check) {
						if (argos[0] == "hasLength") {
							if(!window[argos[0]](getValue(campos[j-1]), argos[1], argos[2])) {
								return generalReturn(campos[j-1], names[i]);	
							}
						}
						else if (argos[0] == "compareEmptyWith") {
							if (!window[argos[0]](campos[j-1], argos[1], argos[2])) {
								return generalReturn(campos[j-1], names[i]);
							}
						}
						else if (argos[0] == "comparePhones") {
							if (!window[argos[0]](campos[j-1], argos[1])) {
								return generalReturn(campos[j-1], names[i]);
							}
						}
						else if (argos[0] == "isGreaterThan") {
							if (!window[argos[0]](getValue(campos[j-1]), argos[1])) {
								return generalReturn(campos[j-1], names[i]);
							} 
						}
						else if (argos[0] == "isSmallerThan") {
							if (!window[argos[0]](getValue(campos[j-1]), argos[1])) {
								return generalReturn(campos[j-1], names[i]);
							} 
						}
						//----
						else if (argos[0] == "startsWith") {
							//alert(argos[1]);
							var count1 = 0;
							var count2 = 0;
							var pref = argos[1].split("*");
							for (var x in pref) {
								
								count2++;
							}
							//alert(count2);
							for (var numPrefs = 0; numPrefs < count2; numPrefs++) {
								//alert("pref="+pref[numPrefs]);
								//alert(getValue(campos[j-1]));
								if (!window[argos[0]](getValue(campos[j-1]), pref[numPrefs])) {
									count1++;
								}
							}
							//alert(count1);
							//alert(count2);
							if (count1 == (count2)) {
								return generalReturn(campos[j-1], names[i]);
							}
						}
						//----
						
						else if (argos[0] == "CheckBoxs") {
							//alert(argos[1]);
							var count1 = 0;
							var count2 = 0;
							var pref = argos[1].split("*");
							for (var y in pref) {
								count2++;
							}
							//alert(count2);
							for (var numPrefs = 0; numPrefs < count2; numPrefs++) {
								//alert("pref="+pref[numPrefs]);
								//alert(getValue(campos[j-1]));
								if (!isChecked(pref[numPrefs])) {
									count1++;
								}
							}
							//alert(count1);
							//alert(count2);
							if (count1 == count2) {
								return generalReturn(campos[j-1], names[i]);
							}
						}
						else if(argos[0] == 'isChecked') {
							if (!window[functions[a]](campos[j-1])) {
								return generalReturn(campos[j-1], names[i]);
							}
						}
						
						else if (!window[functions[a]](getValue(campos[j-1]))) {
							return generalReturn(campos[j-1], names[i]);
						}
					}
				} 
			} check = false;
		}	
	}
	return true;
}
function ifNameSurname( string ){

    var s = string.split(' ');
    if( s.length > 1 )
        if(hasLength (s[1], 2, 50))
            return true;
        else
            return false;
    else
        return false;
}
function startW( s ){ 
    var el = document.getElementById(s);
    
    if(el.value == "") return false;
    if(!isNumber(el.value))return false;
    if(el.value.length != 9) return false;
    if(startsWith(el.value, '2')) return true;
    else if(startsWith(el.value, '91')) return true;
    else if(startsWith(el.value, '92')) return true;
    else if(startsWith(el.value, '93')) return true;
    else if(startsWith(el.value, '96')) return true;
    else return false;
    alert(el.value);

}
function validate(){

    
    var name = ifNameSurname(document.getElementById('name').value);
	var telefone=startW('phone');
	var nif = isNIF(document.getElementById('nif').value);
    var openstore = isEmpty(document.getElementById('openstore').value);
    var exclusive = document.getElementById('exclusive').checked;
    var exp_emp = document.getElementById('exp_emp').checked;
    var sector = isEmpty(document.getElementById('sector').value);
    var email = isEmail(document.getElementById('email').value);
    
    var in1 = document.getElementById('in1').checked;
    var in2 = document.getElementById('in2').checked;
    var in3 = document.getElementById('in3').checked;
    
    var own1 = document.getElementById('owner1').checked;
    var own2 = document.getElementById('owner2').checked;
    
    /*
    “Nome”, “Telefone”, “Onde pretende abrir uma loja”, “Vai dedicar-se exclusivamente a esta actividade” (eliminatório), “Experiência como empresário”.             
    */

     if(!name){
        alert('Preencha o seu primeiro e último nome, correctamente.');
        return false;
    }
    if(!telefone){
        alert('Introduza um número de telefone válido.');
        return false;
    }
	if ((document.getElementById('nif').value != "") && (!nif)) {
		alert('Introduza um contribuinte válido.');
		return false;
	}
    if(!email){
        alert('Introduza um email válido.');
        return false;
    }
    if(!own1 && !own2 ){
        alert('Seleccione se tem loja própria ou não.');
        return false;
    }   
    if(!openstore){
        alert('Introduza onde pretende abrir uma loja.');
        return false;
    }
    if(!exclusive){
        alert('Franchise Resolve implica um regime de exclusividade');
        return false;
    }
    if(exp_emp && !sector){
        alert('Seleccione o sector actividade.');
        return false;
    } 
    if(!in1 && !in2 && !in3){
        alert('Seleccione a capacidade de investimento.');
        return false;
    }

    return true;  
}
function validate2(email){

    if(!isEmail(email)){
        alert('O email que nos forneceu não está correcto. Insira novamente o seu email por favor.');
        return false;
    }
   //alert(email);
   return true;
   
      
}
