function round (val, precision, mode) {

    var retVal=0,v='',integer='',decimal='',decp=0,negative=false;
    var _round_half_oe = function (dtR,dtLa,even){
        if (even === true) {
            if (dtLa == 50) {
                if ((dtR % 2) === 1) {
                    if (dtLa >= 5) {
                        dtR+=1;
                    } else {
                        dtR-=1;
                    }
                }
            }else if (dtLa >= 5) {
                dtR+=1;
            }
        }else{
            if (dtLa == 5) {
                if ((dtR % 2) === 0) {
                    if (dtLa >= 5) {
                        dtR+=1;
                    }else{
                        dtR-=1;
                    }
                }
            }else if (dtLa >= 5) {
                dtR+=1;
            }
        }

        return dtR;
    };
    var _round_half_ud = function (dtR,dtLa,up) {
        if (up === true) {
            if (dtLa>=5) {
                dtR+=1;
            }
        }else{
            if (dtLa>5) {
                dtR+=1;
            }
        }
        return dtR;
    };
    var _round_half = function (val,decplaces,mode){
    /*Declare variables
         *V       - string representation of Val
         *Vlen    - The length of V - used only when rounding intgerers

         *VlenDif - The difference between the lengths of the original V
         *          and the V after being truncated
         *decp    - character in index of . [decimal place] in V
         *integer - Integr protion of Val
         *decimal - Decimal portion of Val
         *DigitToRound - The digit to round

         *DigitToLookAt- The digit to comapre when rounding
         *
         *round - A function to do the rounding
         */
        var v = val.toString(),vlen=0,vlenDif=0;
        var decp = v.indexOf('.');

        var digitToRound = 0,digitToLookAt = 0;
        var integer='',decimal='';
        var round = null,bool=false;
        switch (mode) {
            case 'up':
                bool = true;
                // Fall-through
            case 'down':
                round = _round_half_ud;
                break;
            case 'even':
                bool = true;
            case 'odd':
                round = _round_half_oe;
                break;
        }
        if (decplaces < 0){ //Int round
            vlen=v.length;

            decplaces = vlen + decplaces;
            digitToLookAt = Number(v.charAt(decplaces));
            digitToRound  = Number(v.charAt(decplaces-1));
            digitToRound  = round(digitToRound,digitToLookAt,bool);
            v = v.slice(0,decplaces-1);
            vlenDif = vlen-v.length-1;

            if (digitToRound == 10){
                v = String(Number(v)+1)+"0";
            }else{
                v+=digitToRound;
            }

            v = Number(v)*(Math.pow(10,vlenDif));
        }else if (decplaces > 0){
            integer=v.slice(0,decp);
            decimal=v.slice(decp+1);
            digitToLookAt = Number(decimal.charAt(decplaces));

            digitToRound  = Number(decimal.charAt(decplaces-1));
            digitToRound  = round(digitToRound,digitToLookAt,bool);
            decimal=decimal.slice(0,decplaces-1);
            if (digitToRound==10){
                v=Number(integer+'.'+decimal)+(1*(Math.pow(10,(0-decimal.length))));
            }else{
                v=Number(integer+'.'+decimal+digitToRound);
            }
        }else{
            integer=v.slice(0,decp);
            decimal=v.slice(decp+1);
            digitToLookAt = Number(decimal.charAt(decplaces));

            digitToRound  = Number(integer.charAt(integer.length-1));
            digitToRound  = round(digitToRound,digitToLookAt,bool);
            decimal='0';
            integer = integer.slice(0,integer.length-1);
            if (digitToRound==10){
                v=Number(integer)+1;
            }else{
                v=Number(integer+digitToRound);
            }
        }
        return v;
    };


    //precision optional - defaults 0
    if (typeof precision == 'undefined') {
        precision = 0;
    }
    //mode optional - defaults round half up
    if (typeof mode == 'undefined') {
        mode = 'PHP_ROUND_HALF_UP';
    }

    if (val < 0){ //Remember if val is negative
        negative = true;
    }else{
        negative = false;
    }

    v = Math.abs(val).toString(); //Take a string representation of val
    decp = v.indexOf('.');        //And locate the decimal point
    if ((decp == -1) && (precision >=0)){
   /* If there is no deciaml point and the precision is greater than 0
         * there is no need to round, return val
         */
        return val;
    }else{
        if (decp == -1){
            //There are no decimals so intger=V and decimal=0
            integer = v;
            decimal = '0';
        }else{
            //Otherwise we have to split the decimals from the integer
            integer = v.slice(0,decp);
            if (precision >= 0){
                //If the precision is greater than 0 then split the decimals from the integer
                //We truncate the decimals to a number of places equal to the precision requested+1
                decimal = v.substr(decp+1,precision+1);
            }else{
                //If the precision is less than 0 ignore the decimals - set to 0
                decimal = '0';
            }
        }
        if ((precision > 0) && (precision >= decimal.length)){
            /*If the precision requested is more decimal places than already exist
            * there is no need to round - return val
            */
            return val;
        }else if ((precision < 0) && (Math.abs(precision) >= integer.length)){
           /*If the precison is less than 0, and is greater than than the
             *number of digits in integer, return 0 - mimics PHP
             */
            return 0;
        }
        val = Number(integer+'.'+decimal); // After sanitizing recreate val
    }

    //Call approriate function based on passed mode, fall through for integer constants
    switch (mode){
        case 0:
        case 'PHP_ROUND_HALF_UP':
            retVal = _round_half(val,precision,'up');
            break;
        case 1:
        case 'PHP_ROUND_HALF_DOWN':
            retVal = _round_half(val, precision,'down');
            break;
        case 2:
        case 'PHP_ROUND_HALF_EVEN':
            retVal = _round_half(val,precision,'even');
            break;
        case 3:
        case 'PHP_ROUND_HALF_ODD':
            retVal = _round_half(val,precision,'odd');
            break;
    }
    if (negative){
        return 0-retVal;
    }else{
        return retVal;
    }
}


function is_numeric (mixed_var) {

    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function str_replace (search, replace, subject, count) {

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function validEmail(emailStr){
	var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(emailStr)) {
		return true;
	} else {
		return false;
	}
}

function validPhone(phoneStr){
	var filter=/^[0-9]{3}\-[0-9]{7}$/i
	if (filter.test(phoneStr)) {
		return true;
	} else {
		return false;
	}
}


$(document).ready(function()	{
	//focus the cursor

	$("div#actiePrijsOverview").show();
	$("div.prijs_berekening").css("font-size",'30px');
	//fill the val
	$("span.aPrijs").html('&#8364; 2950');

	$("input.oppervlak").focus().val('40').blur(function()	{
	//$("input.oppervlak").blur(function()	{
		//hide the error and the result
		$("div#actiePrijsError").hide();
		$("div#actiePrijsOverview").hide();

		var opVal = $(this).val();
		if (opVal != undefined && opVal != '')	{
			//not empty, continue
			//replace a , with .
			opVal = str_replace(',','.',opVal);
			//check numeric
			if (is_numeric(opVal))	{

				var prijsActie;
				var givenVal = parseInt(opVal);
				var somVal = '73.75';

				//alert(somVal);

				//calculatie the price
				if (opVal > 39 && opVal < 10000)	{
					prijsActie = '&#8364; '+ round(givenVal * somVal);
					if (prijsActie == 'NaN')	{
						prijsActie = 'Op aanvraag';
						$("div.prijs_berekening").css("font-size",'22px');
					}else	{
						$("div.prijs_berekening").css("font-size",'30px');
					}

				}else	{
					prijsActie = 'Op aanvraag';
					$("div.prijs_berekening").css("font-size",'22px');
				}

				//true, show the info
				$("div#actiePrijsOverview").show();
				//fill the val
				$("span.aPrijs").html(prijsActie);
			}else	{
				//give a error
				$("div#actiePrijsError").show();
			}
		}
	})

	//form submit
	$("form#offForm").submit(function()	{

		var errorReport = '';
		submitForm = true;

		//check the oppervlak
		var op = $("input.oppervlak").val();
		if (op != undefined && op != '')	{
			//check numeric
			op = str_replace(',','.',op);
			if (is_numeric(op))	{

			}else	{
				errorReport = errorReport + '<br>Vul een nummer in voor uw vloeroppervlak.';
				submitForm = false;
			}
		}else	{
			errorReport = errorReport + '<br>Vul een nummer in voor uw vloeroppervlak.';
			submitForm = false;
		}

		//check the name
		var nm = $("input[name=Naam]").val();
		if (nm == undefined || nm == '')	{
			errorReport = errorReport + '<br>Vul uw naam in.';
			submitForm = false;
		}

		//check the email
		var em = $("input[name=email]").val();
		if (em == undefined || em == '' || !validEmail(em))	{
			errorReport = errorReport + '<br>Vul een geldig email adres in.';
			submitForm = false;
		}

		//check the tel
		var tl = $("input[name=Telefoon]").val();
		if (tl == undefined || tl == '')	{
			errorReport = errorReport + '<br>Vul een geldig telefoonnummer in.';
			submitForm = false;
		}

		if (submitForm)	{
			return true;
		}else	{
			$("div.form_error").html(errorReport).show();
			return false;
		}

	})
})