$(function() {
	$("#toggleForm").bind("click", function() {
		$("#block_top").toggle();
		if($("#block_top").css('display') == 'block'){
			$("#toggleForm").attr('src','themes/transgruz/images/where2.png');
		}else{
			$("#toggleForm").attr('src','themes/transgruz/images/where.png');
		}
	});
});

function checkinput(evt, val){ 
    if (!evt) evt = event;
    if (evt.charCode) var charCode = evt.charCode;
    else if (evt.keyCode) var charCode = evt.keyCode;
    else if (evt.which) var charCode = evt.which;
    else var charCode = 0;
    if (charCode>31 && (charCode<48 || charCode>57)) return false;
	return true;
}

function checkform(){
	if (!$('[name=name]').val()){
		//replyError($('[name=name]'));
		replyError(document.getElementById('name'));
		return false;
	}
	if (!$('[name=tel]').val()){
		//replyError($('[name=tel]'));
		replyError(document.getElementById('tel'));
		return false;
	}
	return true;
}

function replyError(s, step){
	if(step===undefined||step===null)step=0;
	if (step%2==0) s.className = s.className.replace("replyfield-ok", "replyfield-err");
	else s.className = s.className.replace("replyfield-err", "replyfield-ok");
	if (step < 5) setTimeout("replyError(document.getElementById('"+s.id+"'),"+(step+1)+");", 100);
}

function carx(){
	if ($("#car").attr('checked') == false) $("#way").attr('checked',false);
}

function wayx(){
	if ($("#way").attr('checked') == true) $("#car").attr('checked',true);
}

function calc(){
	var total = per_car = 0;
	var carType = $('[name=carType]:checked').val();
	if (carType == '3') {per_car = price_3; per_km = price_km_3}
	else if(carType == '4.5') {per_car = price_4_5; per_km = price_km_4_5}
	else if(carType == '6') {per_car = price_6; per_km = price_km_6}
	else if(carType == '7.5') {per_car = price_7_5; per_km = price_km_7_5}
	
	km = parseInt($('[name=km]').val());
	car_time = 1 + parseInt($('[name=car_time]').val());
	if ($("#way").attr('checked')) {
		if (km <= 40) car_time += 1;
		else total += per_km * km * 2;
	}
	if ($("#car").attr('checked')) 
		total += per_car * $('[name=car_qty]').val() * car_time;
	if ($("#loader").attr('checked')) 
		total += price_gr * $('[name=gr_qty]').val() * $('[name=gr_time]').val();
		
	var calculated = total;			
	var decimal_places = round(calculated) == round(calculated, 2) ? 0 : 2;
	calculated = round(calculated, 2);
	var result = number_format(calculated, decimal_places, ',', '');
	$('#totalSum').attr('innerHTML', result + ' грн');
}

function IsNumeric(sText){
	if (sText > 9999) return false;
	sText = sText+'';
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	//alert(sText + ' = ' + sText.length);
	for (i=0;i<sText.length && IsNumber == true; i++){ 		
		Char = sText.charAt(i); 		
		if (ValidChars.indexOf(Char) == -1) IsNumber = false;
	}
	return IsNumber;
}
   
function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

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){
        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;
    }
}
