function str_replace ( search, replace, subject ) {	// Replace all occurrences of the search string with the replacement string
	//
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Gabriel Paderni

	if(!(replace instanceof Array)){
		replace=new Array(replace);
		if(search instanceof Array){//If search	is an array and replace	is a string, then this replacement string is used for every value of search
			while(search.length>replace.length){
				replace[replace.length]=replace[0];
			}
		}
	}

	if(!(search instanceof Array))search=new Array(search);
	while(search.length>replace.length){//If replace	has fewer values than search , then an empty string is used for the rest of replacement values
		replace[replace.length]='';
	}

	if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
		for(k in subject){
			subject[k]=str_replace(search,replace,subject[k]);
		}
		return subject;
	}

	for(var k=0; k<search.length; k++){
		var i = subject.indexOf(search[k]);
		while(i>-1){
			subject = subject.replace(search[k], replace[k]);
			i = subject.indexOf(search[k],i);
		}
	}
	return subject;
}


$(document).ready(function(){
	$("a#calclink").click(function() {		$('.editablehead1').hide();
	});
	$("a#calclink").colorbox({ scrolling: false });
});

$(document).bind('cbox_cleanup', function(){
	$("input[name=mass]").val('');
	$("input[name=volume]").val('');
	$.Watermark.ShowAll();
	$("#lenta").slideUp();
});

$(document).bind('cbox_closed', function(){
	$('.editablehead1').show();
});


$(document).bind('cbox_complete', function(){
	changeSelects();
	$('#cboxBottomCenter').append('<div id="lenta"><a href="http://vtcargo.ru/reception/">оформить заявку</a></div>');

	jQuery(function($){
		$("input[name=mass]").Watermark("Вес (кг)","#2e333b");
		$("input[name=volume]").Watermark("Объем (м. кв.)","#2e333b");
	});
    $('input[name="mass"]').inputValue({allow:"0123456789.,"});
    $('input[name="volume"]').inputValue({allow:"0123456789.,"});

    $('input[name="mass"]').keyup(function() {
		$(this).val(str_replace ( '.,', '.', $(this).val() ));
		$(this).val(str_replace ( '..', '.', $(this).val() ));
		$(this).val(str_replace ( ',,', '.', $(this).val() ));
		$(this).val(str_replace ( ',', '.', $(this).val() ));
		$(this).val(str_replace ( ',.', '.', $(this).val() ));
	});

    $('input[name="volume"]').keyup(function() {
		$(this).val(str_replace ( '.,', '.', $(this).val() ));
		$(this).val(str_replace ( '..', '.', $(this).val() ));
		$(this).val(str_replace ( ',,', '.', $(this).val() ));
		$(this).val(str_replace ( ',', '.', $(this).val() ));
		$(this).val(str_replace ( ',.', '.', $(this).val() ));
	});

	$('#1001_fake > span').mousedown(function(){
		if ($(this).attr('name')!='-')
		{
			var sel = $(this).attr('name');
			$.post("calc.php", {city: sel},
        	function(htmlResult){
	    	    if (htmlResult!='')
	    	    {
	    	    	$("#1002_fake").html(htmlResult);
	    	    	$('#v1002').val($('span[name="--"]').html());
	    	    	$('#1002').val('--');

	    	    	optionClickHover();

					$('#1002_fake > span').mousedown(function(){
        				if ($(this).attr('name')!='--')
						{
        					var types = $(this).attr('name');
        					$('#sublink').unbind('click');
        					$.getScript('calc.php?param='+types+'&city='+sel,function(){
								$('#sublink').click(function(){

									var mass = Math.ceil(parseFloat($('input[name="mass"]').val()));
									var volume = parseFloat($('input[name="volume"]').val());
									if (!isFinite(volume)) {volume = 0;}

									if (isFinite(mass) && isFinite(volume))
									{
										$('#costaddi p').html('');
										if (types=='avia_1')
										{                                            price = limit_50;
                                            if (mass<min_mass) {mass = min_mass;}
                                            if (mass<volume*167) {mass = volume*167;}
											if (mass>51) price = limit_100;
											if (mass>101) price = limit_300;
											if (mass>301) price = limit_500;
											if (mass>501) price = limit_1000;

            								if (min_cost < price*Math.ceil(mass)) {curr_cost_mass = price*Math.ceil(mass);}
            								else {curr_cost_mass = min_cost;}

            								if (curr_cost_mass < volume*167) {curr_cost_mass = volume*167;}
            								avia_addi = 500;

      										$('#cost').html(Math.ceil((Math.ceil(parseFloat(curr_cost_mass))+Math.ceil(parseFloat(avia_addi))))+' руб.');
											$('#costaddi p').append('вид перевозки: <b>АВИА</b><br>');
											$('#costaddi p').append('вес к оплате: <b>'+Math.ceil(mass)+'</b>кг. &lt; тариф: <b>'+price+'</b>руб/кг &gt;<br>');
											$('#costaddi p').append('авиаперевозка: <b>'+Math.ceil(curr_cost_mass)+'</b>руб.<br>авианакладная: <b>'+avia_addi+'</b>руб.<br>');
										}
										else if (types=='train_1' || types=='train_2')
										{
                                            txt = 1;
                                            if (mass<volume*200) {txt = 2;}

            								if (txt==1) {curr_cost = cost_mass*mass;}
            								else if (txt==2) {curr_cost = cost_vol*volume;}

            								if (curr_cost < min_cost) {curr_cost = min_cost;txt = 3;}

											$('#cost').html(Math.ceil(curr_cost)+' руб.');
											if (types=='train_1'){$('#costaddi p').append('вид перевозки: <b>Ж/Д багажная скорость</b><br>');}
											else{$('#costaddi p').append('вид перевозки: <b>Ж/Д грузовая скорость</b><br>');}
											$('#costaddi p').append('срок доставки (дней): <b>'+time+'</b><br>');
											if (txt==1) {$('#costaddi p').append('расчет стоимости по весу: <b>'+Math.ceil(mass)+'</b>кг<br>тариф: <b>'+cost_mass+'</b>руб/кг<br>');}
											else if (txt==2) {$('#costaddi p').append('расчет стоимости по объему: <b>'+Math.round(volume*100)/100+'</b>м<sup>3</sup><br>тариф: <b>'+cost_vol+'</b>руб/м<sup>3</sup><br>');}
											else if (txt==3) {$('#costaddi p').append('расчет стоимости мин.: <b>'+curr_cost+'</b>руб<br>тариф: <b>'+curr_cost+'</b>руб<br>');}
										}
										$.fn.colorbox.resize();
										$("#lenta:hidden").oneTime("1s", function() {
											$(this).slideDown();
										});
									}
									else
									{										$("#costaddi p").html('<b class="alert">пожалуйста укажите вес груза!</b>');
									}
									return false;
								});
        					});
                        }
					});
	    	    }
        	});
        }
	});

	$('#reslink').click(function(){
		$("input[name=mass]").val('');
		$("input[name=volume]").val('');
		$("#cost").html('0 руб.');
		$.Watermark.ShowAll();
	    $("#lenta:visible").slideUp();
		$("#costaddi p").oneTime("1s", function() {
			$(this).html('детальный расчет стоимости');
			$.fn.colorbox.resize();
		});
		return false;
	});
});
