/*
**  
*/
function KASKO(base_url, button_id){
	this.base_url='./model_cars/';
	this.k_damage=1.0;											// коэффициент ущерба (К2)
	this.k_theft=1.0;											// коэффициент хищения (К5)
	this.k_protection=1.0; 										// коэффициент ПУ (К6)
	this.k_count_people=1.0;									// коэффициент для количества лиц (К3)
	this.k_exp=1.0;												// коэффициент стажа (К4)
	this.k_BTU=0;
	this.k_BTH=0;
	this.k_year=1.0;
	
	this.cur_price=0;											// стоимость авто
	this.cur_car='';											// текущая марка машины
	this.cur_model='';											// текущая модель марки
	this.cur_production='en';									// производитель авто
	this.is_right_roel='false';
	
	this.init();
}
KASKO.prototype={
	init:function(){
		var o_this=this;
		this.hideError();
		this.hidePrice();
		$('#o_cars').change(function(){o_this.loadModelOfCar();});
		$('#o_button').click(function(){o_this.calculate();});
		//загрузить список авто
		this.loadCars();
	},
	// запрос на загрузку марок авто
	loadCars:function(){
		$('#o_cars').append('<option value="" style="color:#666;">загрузка марок...</option>');
		$("#o_cars").attr("disabled","disabled");
		$("#o_models").attr("disabled","disabled");
		$("#o_button").attr("disabled","disabled");
		var o_this=this;
		$.get(this.base_url+'cars.xml', function(xml){o_this.onLoadCars(xml);}, 'xml');
	},
	// обработка запроса на загрузку марок
	onLoadCars:function(xml){
		$('#o_cars').empty();
		$("#o_button").attr("disabled","disabled");
		var cars=$('car', xml);
		if(cars){
			$(cars).each(function(){
				$('#o_cars').append('<option value="'+$(this).attr('file')+'" production="'+$(this).attr('production')+'">'+$(this).text()+'</option>');
			});
		}
		this.loadModelOfCar();
	},
	// запрос на загрузку моделей для марки
	loadModelOfCar:function(){
		$("#o_button").attr("disabled","disabled");
		$('#o_models').empty();
		$('#o_models').append('<option value="" style="color:#666;">загрузка моделей...</option>');
		var o_this=this;
		$.get(this.base_url+$('#o_cars option:selected').attr('value')+'.xml', function(xml){o_this.onLoadModelOfCars(xml);}, 'xml');
	},
	// обработка запроса на загрузку моделей для марки
	onLoadModelOfCars:function(xml){
		var models=$('model', xml);
		$('#o_models').empty();
		$(models).each(function(){
			$('#o_models').append('<option value="" damage="'+$(this).attr('damage')+'" theft="'+$(this).attr('theft')+'">'+$(this).text()+'</option>');
		});
		$("#o_cars").removeAttr("disabled");
		$("#o_models").removeAttr("disabled");
		$("#o_button").removeAttr("disabled");
	},
	calculate:function(){
		if(!this.checkedFields()){
			return;
		}
		this.setKoeff();
		
		var P1=this.k_year*this.k_damage*this.k_count_people*this.k_exp;
		var P2=this.k_theft*this.k_protection;
		var RT=(this.k_BTU*P1+this.k_BTH*P2)/100;
		var price=Math.round(this.cur_price*RT);
		this.hideError();
		this.showPrice(price);
	},
	checkedFields:function(){
		// проверить стоимость автомобиля
		var price=$('#o_price').val();
		if(!price){
			this.showError(1);
			return false;
		}
		if (isNaN(price)){
			this.showError(2);
			return false;
		}
		var birthday=$('#o_birthday').datepick('getDate');
		if(!birthday){
			this.showError(3);
			return false;
		}
		var diff0=this.dateDiff(new Date(), birthday);
		if(diff0<18){
			this.showError(4);
			return false;
		}
		return true;
	},
	setKoeff:function(){
		// заполнить коэффициенты для расчета
		this.cur_price=$('#o_price').val();
		this.k_damage=$('#o_models option:selected').attr('damage');
		this.k_theft=$('#o_models option:selected').attr('theft');
		this.k_year=$('#o_year option:selected').val();
		this.k_protection=$('#o_protection option:selected').val();
		this.k_count_people=$('#o_count_people option:selected').val();
		this.k_production=$('#o_cars option:selected').attr('production');
		this.k_epx=$('#o_first_date option:selected').val();
		this.is_right_roel=$('#o_right_roel').attr('checked');
		if(this.is_right_roel==true){
			this.k_damage=1.20;
		}
		this.k_BTH=this.cur_production=='en' ? 1.20 : 1.50;
		if(this.cur_production=='en'){
			if(this.cur_price<=800000){
				this.k_BTU=5.50;
			}
			else if(this.cur_price<=1350000){
				this.k_BTU=5.30;
			}
			else if(this.cur_price<=2700000){
				this.k_BTU=5.00;
			}
			else{
				this.k_BTU=4.50;
			}
		}
		else{
			this.k_BTU=5.70;
		}
	},
	hideError:function(){
    	$('#kasko-error').hide();
		$('#kasko-err').hide();
	},
	showError:function(code){
	    this.hideError();
		this.hidePrice();
		$('#kasko-err').show();
	    switch (code) {
	        case 1:
	            $('#kasko-error').html('Введите стоимость автомобиля').slideDown();
	            break;
	        case 2:
	            $('#kasko-error').html('Стоимость автомобиля должна быть числовым значением').slideDown();
	            break;
	        case 3:
	            $('#kasko-error').html('Вы не ввели дату рождения').slideDown();
	            break;
	        case 4:
	            $('#kasko-error').html('Вам должно быть 18 и более лет').slideDown();
	            break;
	        default:
	            $('#kasko-error').html('Неизвестная ошибка').slideDown();
	            break;

	    }
	},
	hidePrice:function(){
    	$('#kasko-result').hide();
		$('#kasko-res').hide();
	},
	showPrice:function(price){
		$('#kasko-res').show();
    	$('#kasko-result').html(price+' руб.').slideDown();
	},
	dateDiff:function(date1, date2){
		//вычисляет разницу в днях между датами
		var diff = date1.getTime() - date2.getTime();
		return Math.round((diff)/(1000 * 60 * 60 * 24*365));
	}
}
