function validbi(bi, check){
    values = new Array(bi.length);
    temp = bi;
    sum = 0;
    for(a = 0; a< bi.length; a++){
        values[a] = temp % 10;
        temp = Math.floor(temp / 10);
        
    }
    mult    = 2;
    for(j = 0; j < bi.length; j++){
        
        sum += (values[j] * mult);
        mult++;
    }
    if(check > 0){
        var total = Number(sum)+Number(check);
        if(total % 11 == 0){
            return true
        }else{
            return false
        }
    }else{
        if((sum % 11 == 0) || ((sum + 10) % 11 == 0)){
            return true;
        }else{
            return false
        }
    }   
}

function isIsbn(number){
        if(!number) return false;
        //ISBNRegExp = /^ISBN\s(?=[-0-9xX ]{13}$)(?:[0-9]+[- ]){3}[0-9]*[xX0-9]$/
        ISBNRegExp = /^(?=[-0-9xX ]{13}$)(?:[0-9]+[- ]){3}[0-9]*[xX0-9]$/
        return ISBNRegExp.test(number);
}

function validaNum(num) {
    var pos;
    var val = 0;

    // computar soma de controlo 
    for(pos = 0; pos < num.length-1; pos++)
        val += num[pos] * (9 - pos);

    val = val % 11 ? (11 - val % 11) % 10 : 0;

    // verificar soma de controlo 
    return val == num[pos];
}

function validcontribuinte(num) {
        var ret = false;
        var arr = new Array(num);
        arr = num.split('');
        // verificar validade do caracter inicial do NIF 
        switch(arr[0]) {
            case '1': case '2': case '5':
            case '6': case '8': case '9':
            //verificar validade do NIF 
            return validaNum(arr);
        }       
        return false;
}

function Trim(TRIM_VALUE){
    if(TRIM_VALUE.length < 1){
        return "";
    }
        TRIM_VALUE = RTrim(TRIM_VALUE);
        TRIM_VALUE = LTrim(TRIM_VALUE);
    if(TRIM_VALUE==""){
        return "";
    }
    else{
        return TRIM_VALUE;
    }
} //End Function

function RTrim(VALUE){
    var w_space = String.fromCharCode(32);
    var v_length = VALUE.length;
    var strTemp = "";
    if(v_length < 0){
        return"";
    }
    var iTemp = v_length -1;
            
    while(iTemp > -1){
        if(VALUE.charAt(iTemp) == w_space){
        }
        else{
            strTemp = VALUE.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;
            
    } //End While
    return strTemp;
} //End Function

function LTrim(VALUE){
    var w_space = String.fromCharCode(32);
    if(v_length < 1){
        return"";
    }
    var v_length = VALUE.length;
    var strTemp = "";
    var iTemp = 0;
    while(iTemp < v_length){
        if(VALUE.charAt(iTemp) == w_space){
        }
        else{
            strTemp = VALUE.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    } //End While
    return strTemp;
} //End Function

function copyfieldvalues(fieldorigin, fielddestination) {
    var name_f = document.getElementById(fieldorigin);
    var name_m = document.getElementById(fielddestination);
    if(checkcopyaddress.checked) {
        name_m.value = name_f.value;
    } else {
        name_m.value = '';
    }
}

function validemail(email) {
    //var email = document.getElementById(fieldname).value;
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if(!email.match(emailExp)) {
        return false;         
    }
    return true;
}

function validphone(fieldname) {
    var phone = document.getElementById(fieldname).value;
    var regexp = /^[0-9]{9}$/;
    if(!phone.match(regexp)) {
        return false;         
    }
    return true;
}

function checkedbox(fieldname) {
    var field = document.getElementById(fieldname);
    if(!field.checked) {
        return false;
    }
    return true;
}

function validcp1(value) {
    if(value.length!=4)
        return false;
    if(value<1000 || value>9999)
        return false;
    return true;
}

function validcp2(value) {
    if(value.length!=3)
        return false;
    if(value<000 || value>999)
        return false;
    return true;
}

function validlocation(value) {
    if(value.length<2)
        return false;
    return true;
}

function validphone(value) {
    if (value.length<9)
        return false;
    return true;
}


//added functions
function edGet(fieldId) {
    return document.getElementById(fieldId);
}

function validText(fieldId) {
    var f = Trim(document.getElementById(fieldId).value);
    return f.length>0;
    
}

function validTextIfNotNull(fieldId) {
    var f = document.getElementById(fieldId).value;
    if(f.length==0) {
        return true;
    }
    var f = Trim(document.getElementById(fieldId).value);
    return f.length>0;
    
}

function validEmailIfNotNull(fieldId) {
    var f = document.getElementById(fieldId).value;
    if(f.length==0) {
        return true;
    }
    return validEmail(fieldId);
}

function validEmail(fieldId) {
    var f = document.getElementById(fieldId).value;
    var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if(!f.match(emailExp)) {
        return false;         
    }
    return true;
}

function validPhoneIfNotNull(fieldId) {
    var f = document.getElementById(fieldId).value;
    if(f.length==0) {
        return true;
    }
    return validPhone(fieldId);
}

function validPhone(fieldId) {
    var f = document.getElementById(fieldId).value;
    if(f.length<9 || f.length>13) {
        return false;
    }
    var regexp = /^[0-9]{9}$/;
    if(!f.match(regexp)) {
        return false;         
    }
    return true;
}

function validTextarea(fieldId) {
    var f = Trim(document.getElementById(fieldId).value);
    f = remove_newlines_textarea (f);
    return f.length>0;
    
}

function remove_newlines_textarea (val) {             
  // Adjust newlines so can do correct character counting for MySQL. MySQL counts a newline as 2 characters.
  if (val.indexOf('\r\n')!=-1)
    ; // this is IE on windows. Puts both characters for a newline, just what MySQL does. No need to alter
  else if (val.indexOf('\r')!=-1)
    val = val.replace ( /\r/g, "" );        // this is IE on a Mac. Need to add the line feed
  else if (val.indexOf('\n')!=-1)
    val = val.replace ( /\n/g, "" );        // this is Firefox on any platform. Need to add carriage return
  else 
    ;                                           // no newlines in the textarea  
  return val;
}

function validSelect(fieldId, nullValue) {
    var f = document.getElementById(fieldId);
    return (f.options[f.selectedIndex].value)!=nullValue;    
}

function validYear4Digits(fieldId) {
    var f = Trim(document.getElementById(fieldId).value);
    if(f.length==0) {
        return false;
    }
    if(isNaN(f)) {
        return false;
    }
    if(f.length!=4) {
        return false;
    }
    return true;
}

//obriga que pelo menos x dos elementos do grupo,
//checkbox ou radio button, esteja seleccionado
function validCheckGroup(fieldName, mandatoryChecks) {
    var f=document.getElementsByName(fieldName);
    var checks = 0;
    for(var i=0;i<f.length;i++){
        if (f[i].checked){
            ++checks;
            if(checks==mandatoryChecks) {
                return true;
            }
        }
    }
    return false;
}

function invalidFieldValue(str) {
    return '\nO campo «'+str+'» não está preenchido ou é inválido';
}

function invalidFieldValueIfNotNull(str) {
    return '\nO campo «'+str+'» é inválido';
}

function disableField(fieldId) {
    var f = document.getElementById(fieldId);
    f.disabled = true;
}

function enableField(fieldId) {
    var f = document.getElementById(fieldId);
    f.disabled = false;
}

function toggleEnableField(fieldId) {
    var f = document.getElementById(fieldId);
    if(f.disabled)
        f.disabled = false;
    else
        f.disabled = true;
}

function togglepassword2(id, idtext) {
	var ip = document.getElementById(id);
    var t = document.getElementById(idtext);
    var np=document.createElement('input');
    np.id = ip.id;
    if(ip.type=='password') {
    	np.type='text';
        t.innerHTML = 'Esconder palavra-chave';
    }
    else {
    	np.type='password';
        t.innerHTML = 'Mostrar palavra-chave';
    }
    np.value = ip.value;
    np.className = ip.className;
    ip.parentNode.replaceChild(np,ip);
}

          
 function Trim(TRIM_VALUE){
    if(TRIM_VALUE.length < 1){
        return"";
    }
    TRIM_VALUE = RTrim(TRIM_VALUE);
    TRIM_VALUE = LTrim(TRIM_VALUE);
    if(TRIM_VALUE==""){
        return "";
    }
    else{
        return TRIM_VALUE;
    }
} //End Function
                
function RTrim(VALUE){
    var w_space = String.fromCharCode(32);
    var v_length = VALUE.length;
    var strTemp = "";
    if(v_length < 0){
        return"";
    }
    var iTemp = v_length -1;
    while(iTemp > -1){
        if(VALUE.charAt(iTemp) == w_space) { }
        else {
            strTemp = VALUE.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;
    } //End While
    return strTemp;
} //End Function
                
function LTrim(VALUE){
    var w_space = String.fromCharCode(32);
    if(v_length < 1){
        return"";
    }
    var v_length = VALUE.length;
    var strTemp = "";
    var iTemp = 0;
    while(iTemp < v_length){
        if(VALUE.charAt(iTemp) == w_space) { }
        else{
            strTemp = VALUE.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    } //End While
    return strTemp;
} //End Function 

function edOpenNewWindow(url, params) {
    var load = window.open(url,'',params);
    return false;
}


function formatnumber(number){
	var matchflt=new RegExp(/.\d\d\d/);
	if(matchflt.test(number)){
		number = number.replace( "." , "");
	}
	number = number.replace( "," , "." );
	return parseFloat(number);
}

//valida entrada
function valnumber(field, id, typeitem){
	field.onfocus;
	var check = true;
	var value = field.value; 
	var returnvalue = "";
	for(var i=0;i < field.value.length; ++i){
	   var new_key = value.charAt(i); //cycle through characters
	   if( ((new_key < "0") || (new_key > "9")) && !(new_key == "") ){
		   //if(!(new_key == ".") ){
			   check = false;
			   new_key = "";
		   //}
	   }
	   returnvalue = returnvalue + new_key;
	}
	if(!check){
		field.value = returnvalue;
		return false;
	}
	//consoante ao tipo do produto 'prod ou promo'
	if( parseFloat( $F(typeitem + '_'  + id) ) == 0 ){
		if(confirm('Deseja remover produto do carrinho?') ){
			actualizavalores(id, 'removecart'+typeitem , typeitem);
		}else{
			window.location = 'index.php?pt=scdetail';
		}
	}else{
		actualizavalores(id, 'addcart'+typeitem, typeitem);
	}
}




function actualizavalores(id, action, typeitem){
	if(isNaN(parseFloat( $F(typeitem + '_'  + id)))){
		return false;
	}
	var url = 'process.php?op='+action+'&i='+id+'&quant='+ $F(typeitem + '_'+ id);
	new Ajax.Request( url,{
		  method: 'get',
		  onSuccess: function(transport){
		    $('flash').innerHTML = 'Actualizado quantidade com sucesso.' ;
		    new PeriodicalExecuter(function(pe) {
		    		$('flash').innerHTML = '';
		    		pe.stop();
		    	}, 3);
		    actualizalinha( id, action, typeitem );
		    actualizadivs( id, action, typeitem );
		  },
		  onException: function(transport, exp){
			  alert('Ocorreu um erro ao actualizar ' + exp);
		  }
		});
}

function actualizalinha(id, action, typeitem){
	var quantidade = parseFloat($F(typeitem + '_'+ id)) ;
	var price = formatnumber( $(typeitem +'_price_'+id).innerHTML ) ;
	$(typeitem + '_sub_'  + id).innerHTML = CurrencyFormatted(quantidade * price) + '&euro;';
}


function actualizadivs(id, action, typeitem){
	var transportationprice = isNaN( parseFloat( $('transportationprice').innerHTML  ) ) ? 0 : formatnumber(  $('transportationprice').innerHTML  );
	var grandtotalwithoutransportation = 0;
	$$('div[class="subs_prods"]').each(function(elm){
		grandtotalwithoutransportation = grandtotalwithoutransportation + formatnumber(elm.innerHTML);
	});
	$('grandtotalwithoutransportation').innerHTML = CurrencyFormatted( grandtotalwithoutransportation ) + '&euro;';
	$('grandtotal').innerHTML = CurrencyFormatted( parseFloat(grandtotalwithoutransportation + transportationprice ) ) + '&euro;';

	$('total_cart').innerHTML = 'TOTAL&nbsp;&nbsp;&nbsp;&nbsp;' + CurrencyFormatted( parseFloat(grandtotalwithoutransportation ) ) + '&euro;';;
	if( action == 'removecart'+typeitem) $(typeitem + '_tr_'+ id).remove();
	
	if( grandtotalwithoutransportation == 0 ){
		$('divcart').hide();
		$('scdetailcontainer').innerHTML = '<div id="messagebox">O carrinho de compras está vazio.<br><br><input value="voltar à página principal" onclick="window.location=\'http://www.ed-rom.com/clientes/monitor/site/?pt=home\'" style="background-color: rgb(38, 51, 67); color: rgb(255, 255, 255); height: 28px; font-size: 10px;" type="submit"></div>';
	}
	
}


function CurrencyFormatted(amount){
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
