var mouseX = 0;
	var mouseY = 0;
	
	function mouseShowHandler(e){
			e = e || window.event;
	    if (e.pageX == null && e.clientX != null ) { 
	        var html = document.documentElement;
	        var body = document.body;
	        e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
	        e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
	    }
	    mouseX = parseInt(e.pageX)+parseInt(10);
		mouseY = parseInt(e.pageY)+parseInt(10);
	}
	
$(document).ready(function () {
	var elIndex = 1;
	$('.changererer').change(function() {
		var ewlCardSel = $(this).val();
		
		$('.top-toop').each(function() {
			if($(this).text() == ewlCardSel){
				elIndex = $(this).parents('td[td-index]').attr('td-index');
			}
		});
		if(elIndex){
			$('td[td-index]').css('background', 'white');
			$('td[td-index='+elIndex+']').css('background', '#e9f6fe');
		}
	});
	
	
	$('.detail-info-ri img').each(function() {
		$(this).css('opacity', '0.6');
	});
	$('.detail-info-ri img').mousemove(function() {
		$(this).css('opacity', '1');
		var altText = $(this).attr('alt');
		$('.tit').remove();
		$('body').append('<div class="tit" style="position: absolute; top: '+mouseY+'px; left: '+mouseX+'px; overflow: hidden; padding: 2px; font-size: 11px; background: #E9F6FE; border: 1px solid black;">'+altText+'</div>');
	});
	$('.detail-info-ri img').mouseleave(function() {
		$(this).css('opacity', '0.6');
		$('.tit').text(' ');
		$('.tit').remove();
	});
	
	$('.top-menu').corner('top 3px');
	$('.active').corner('bottom 3px');
	$('.top-menu a').corner('bottom 3px');
	$('.hover-panel').corner('3px');
	$('.block-ri').corner('3px');
	$('.active-filter-proiz').corner('4px');
	$('.active-page').corner('4px');
	$('.block-sravneniy').corner('10px');
	$('.popup').corner('10px');
	$('.pop-bottom').corner('bottom 10px');
	$('.kryglashi').corner('5px');
	$('.slide-drag-ag-g').corner('5px');
	
	
	
	function rasch(el) {
		var event = $(el).keydown();
		if ((event.keyCode < 48 || event.keyCode > 57) || event.keyCode != 44){
			var val = el.val().replace(/[^\d|\.|,]+/gi, '');
			el.val(val);
			if(el.val() == ''){
				el.blur(function() {
					if(el.val() == ''){
						$(this).val('0');
					}
				});
			}
		}

		var ploshad = $('input[name=pl]').val(); 
        var heightPot = $('input[name=steklo]').val(); 
        var ploshad = $('input[name=pl]').val(); 
        var chekSelect = $('input[name=rad]:checked').attr('value');
                                        
		var ifRast = ploshad * heightPot * 30 * chekSelect;
		
		var tottal = ifRast;

		// если мощность посчитали, то подгружаем аяксом подходящие кондиционеры
		if ( tottal > 0 ) {
			// функция находится в файле main_s.js
			upload_by_power(tottal);
		}
		
		var predZnEl = parseInt($('.tottal-prise span').text());
		$('.tottal-prise span').text(tottal);
//		console.log(hiddenPl, hiddenPc, hiddenMen, radioEl, Pl, Steklo, Pc, Vt, Men, ifRas, tottal);
	}
	$('.calc').find('input[type=radio]').change(function() {
		rasch($(this));
	});
	$('.calc').find('input').keyup(function() {
		rasch($(this));
	});
	$('.calc').find('input').focus(function() {
		if($(this).val() == 0){
			$(this).val('');
		}
	});
	$('.calc').find('input').blur(function() {
		if($(this).val() == ''){
			$(this).val('0');
		}
	});
		
	/*
	$('.add-list').click(function() {
		if($(this).hasClass('selected') != true){
			$(this).addClass('selected');
			$(this).text('убрать из сравнения');
			var selEl = $(this).parents('.name-prodyct').find('a:first').clone();
			$('.elem-srav').append(selEl);
			return false;
		}else{
			$(this).removeClass('selected');
			$(this).text('сравнить');
			var selEl = $(this).parents('.name-prodyct').find('a:first').text();
			$('.elem-srav').find(selEl);
			return false;
		}
	});
	*/
	$('.inp-namb').blur(function() {
		var valEl = $(this).val();
		if(valEl == '' && valEl == 0){
			var valEl = $(this).val('0');
		}
	});
	
		
				var FormValidator = function(element){
				    this.init.apply(this, arguments)
				};
				FormValidator.prototype = {

				    init: function(element){
				        var t = this;
				        t.form = $(element);
				        t.fields = $("input", element);
				        t.textareas = $("textarea", element);
				        t.submit = $(".submit", element);
				        t.is_valid = t.validateAll();
				        t.form.submit(function(){
				            return t.is_valid
				        });
				        t.fields.change(function(){
				            t.validateAll();
				        });
				        t.textareas.change(function(){
				            t.validateAll();
				        });
				        t.fields.keyup(function(){
				            t.validateAll();
				        });
				    },   
				    validateAll: function(){
				       var t = this;
				        // презумпция невиновности пользователя
				        var is_valid = true;
				        var methodRe = new RegExp("validate-as-(\\S*)", "i");
				        
				        for (var i = 0; field = t.fields[i]; ++i) {
				            var is_field_valid = true;
				            var method = methodRe.exec(field.className)
				            //если нет класса валидатора для поля, или такой валидатор не найден - считаем поле валидным
				            if (method && method.length > 1) {
				               method = method[1];
				                var local_validator = t["validate-as-" + method];
				                if (local_validator) {
				                    is_field_valid = local_validator(field.value);
				                    if (is_field_valid) {
				                        $(field).removeClass("invalid");
				                    } else {
				                        $(field).addClass("invalid");
				                    }
				                   
				                }            
				            }
				            // если поле невалидно - невалидна вся форма
				            // но цикл нужно пройти до конца, чтобы подсветить невалидные поля
				            if (!is_field_valid) {
				                is_valid = false
				            }
				        }       
				        for (var i = 0; textAr = t.textareas[i]; ++i) {
				            var is_field_valid = true;
				            var method = methodRe.exec(textAr.className)
				            //если нет класса валидатора для поля, или такой валидатор не найден - считаем поле валидным
				            if (method && method.length > 1) {
				               method = method[1];
				                var local_validator = t["validate-as-" + method];
				                if (local_validator) {
				                    is_field_valid = local_validator(textAr.value);
				                    if (is_field_valid) {
				                        $(textAr).removeClass("invalid");
				                    } else {
				                        $(textAr).addClass("invalid");
				                    }
				                   
				                }            
				            }
				            // если поле невалидно - невалидна вся форма
				            // но цикл нужно пройти до конца, чтобы подсветить невалидные поля
				            if (!is_field_valid) {
				                is_valid = false
				            }
				        } 
				        if (!is_valid) {
				        	 $('.submit').val('Заполните все поля');
				            t.submit.addClass("inactive")
				        } else {
				        	 $('.submit').val('Отправить заявку');
				            t.submit.removeClass("inactive")
				        }       
				        return t.is_valid = is_valid;
				    },

    				    "validate-as-text": function(text){
    				        var valid = true
    				        if (text.length < 2) {
    				            valid = false
    				        }
    				        return valid
    				    },  
    				    "validate-as-textarea": function(text){
    				        var valid = true
    				        if (text.length < 2) {
    				            valid = false
    				        }
    				        return valid
    				    },  
    				    "validate-as-number": function(text){
    				        var valid = true
    				        if (text.length < 1) {
    				            valid = false
    				        }
    				        return valid
    				    },  
    				    "validate-as-fio": function(text){
    				        var valid = true
    				        if (text.length < 2) {
    				            valid = false
    				        }
    				        return valid
    				    },  
    				    "validate-as-reppass": function(text){
    				        var valid = true
    				        var validPass = $('.povtor').val();
    				        var Pass = $('.pass').val();
//    				        console.log(validPass, Pass);
    				        if (text.length < 6 || validPass != Pass) {
    				            valid = false
    				        }
    				        return valid
    				    },
    				    "validate-as-name": function(name){
    				        var valid = true
    				        if (name.length < 3) {
    				            valid = false
    				        }
    				        return valid
    				    },
    				    "validate-as-checkbox": function(name){
    				        var valid = true
    				        if($('input[par=box]').is(':checked')==false){
    				        	valid = false
    				        	$('.qwer').css('color', 'red');
    				        	}
    				        else {$('.qwer').css('color', 'black');}
    					    return valid
    				    },
    				    "validate-as-textarea": function(text){
    				        var valid = true
    				        if (text.length < 2) {
    				            valid = false
    				        }
    				        return valid
    				    }, 
    				    "validate-as-email": function(email){
    				        var emailRe = new RegExp("^[^\\s()<>@,;:\\/]+@\\w[\\w\\.-]+\\.[a-z]{2,}$", "i")
    				        return emailRe.test(email)
    				    },
    				    "validate-as-phone": function(phone){
    				        var phoneRe = /[0-9]{1}/i
    				        return phoneRe.test(phone)
    				    }
    				}
    				$(function(){
    				    $(".apply-validator").each(function(){
    				        new FormValidator(this)
    				    })
    				})

    				var counttel = 1;
    				var countimg = 0;
	
	$('.exit, .black-obj, .close-pop').mousedown(function() {
		$('.black-obj, .popup').hide();
		return false;
	});
    $('.submit').mousedown(function() {
    	var elForm = $(this).parents('form');
    	elForm.find('.form-error *').remove();
    	elForm.find('.yslyga-block-line input').css('border', '1px solid #8f8f8f');
    	elForm.find('.invalid').each(function() {
			$(this).css('border', '1px solid red');
			var textInvalid = $(this).parent().find('p:first').text();
			var valEl = $(this).val();
			if(valEl.length >= 1){
				elForm.find('.form-error').append('<p>Поле '+textInvalid+' заполнено не верно</p>');
			}else{
				elForm.find('.form-error').append('<p>Поле '+textInvalid+' не заполнено</p>');
			}
		//	console.log(textInvalid);
		});
	});
    
	var one = $('input[name=cena-za-odny]').val();	
	var all = $('input[name=coll-el]').val();	
	var el = $('.inp-namb').each(function() {
		$(this);
	});	
	
	$('.feedback-block-panel a[ottributionumosus=fuuu]').click(function() {
		var imgEl = $(this).parents('td').find('img').attr('srcbig'); 
		$('.black-obj').show();
		$('.big-img').show();
		$('.big-img').append('<img class="preload" src="/img/load.gif" width="40px"  alt="" />');
		$('.big-img').append('<img class="showw" src="'+imgEl+'" style="display: none;" width="400"  alt="" />');
		$('.preload').remove();
		$('.showw').show();
		return false;
	});
	
	$('.big-img').click(function() {
		$(this).html(' ');
		$(this).hide();
	});
	$('.big-img').click(function() {
		$('.big-img').html(' ');
		$(this).hide();
		$('.black-obj').hide();
	});
	$('.black-obj').mousedown(function() {
		$('.big-img').html(' ');
		$('.big-img').hide();
		$(this).hide();
	});
	//страница файлов ховер на блок файла
	$('.file-block').mouseenter(function() {
		$(this).css('border', '1px solid #3F84BE');
	});
	$('.file-block').mouseleave(function() {
		$(this).css('border', '1px solid white');
	});
	//расчет стоимости
	$('.inp-namb').keyup(function() {
		if ((event.keyCode < 48 || event.keyCode > 57) || event.keyCode != 44){
			var val = $(this).val().replace(/\D+/gi, '');
			$(this).val(val);
			$(this).parents('tr').find('.inp-namb').val(val);
			$(this).parents('tr').find('input[name=coll-el]').val(val);
			var one = parseInt($(this).parents('tr').find('input[name=cena-za-odny]').val());	
			var all = parseInt($(this).parents('tr').find('input[name=coll-el]').val());	
			var curPrice = parseInt($(this).parents('tr').find('input[name=cena-all]').val());
			var el = $(this);	
			if($(this).val() == ''){
				all = '0';
			}
			raschetStoimosty(one, all, el, curPrice);
		}
	});
	
	function raschetStoimosty(one, all, el, curPrice) {
		var cost = one*all;
		if (cost > curPrice) {
			var des = cost - curPrice;
			var inch = Math.round(des / 5);
			el.parents('tr').find('input[name=cena-all]').everyTime(50, function(i) {
				curPrice = curPrice + inch;
				if (curPrice < 0)
					curPrice = curPrice * (-1);
					el.parents('tr').find('input[name=cena-all]').val(curPrice);
					el.parents('tr').find('.bablo').text(curPrice+' руб.');
					allMon();
				if (i == 5) {
					el.parents('tr').find('input[name=cena-all]').val(cost);
					el.parents('tr').find('.bablo').text(cost+' руб.');
					allMon();
				}
				allMon();
			}, 5);
		} else {
			var des = curPrice - cost;
			var inch = Math.round(des / 5);
			el.parents('tr').find('input[name=cena-all]').everyTime(10, function(i) {
				curPrice = curPrice - inch;
				if (curPrice < 0)
					curPrice = curPrice * (-1);
					el.parents('tr').find('input[name=cena-all]').val(curPrice);
					el.parents('tr').find('.bablo').text(curPrice+' руб.');
					allMon();
				if (i == 5) {
					el.parents('tr').find('input[name=cena-all]').val(cost);
					el.parents('tr').find('.bablo').text(cost+' руб.');
					allMon();
				}
				allMon();
			}, 5);
		}
	}
	function allMon() {
		var vse = 0;
		var predZn = $('.symma-vseh input[name=symma-cen]').val();
		$('input[name=cena-all]').each(function() {
			vse = vse + parseInt($(this).val());
		});	
		if (vse > predZn) {
			var dess = vse - predZn;
			var inchh = Math.round(dess / 5);
			$('.symma-vseh input[name=symma-cen]').everyTime(10, function(i) {
				predZn = predZn + inchh;
				if (predZn < 0){predZn = predZn * (-1);}
				if (i == 5) {
					$('.symma-vseh input[name=symma-cen]').val(vse);
					$('.symma-vseh p span').text(vse+' руб.');
					allMon(el);
				}
			}, 5);
		} else {
			var dess = predZn - vse;
			var inchh = Math.round(dess / 5);
			$('.symma-vseh input[name=symma-cen]').everyTime(10, function(i) {
				predZn = predZn - inchh;
				if (predZn < 0){predZn = predZn * (-1);}
				if (i == 5) {
					$('.symma-vseh input[name=symma-cen]').val(vse);
					$('.symma-vseh p span').text(vse+' руб.');
					allMon(el);
				}
			}, 5);
		}
	}
	$('.inp-namb').each(function() {
		var el = $(this);
		var one = parseInt(el.parents('tr').find('input[name=cena-za-odny]').val());	
		var all = parseInt(el.parents('tr').find('input[name=coll-el]').val());
		var curPrice = parseInt(el.parents('tr').find('input[name=cena-all]').val());	
		raschetStoimosty(one, all, el, curPrice);
		allMon(el);
	});
	
	//выделение полей в списке
	$('.detail-info-le-text:odd').css('background', '#F6F9FC');
	
	$(".detail-info-le table tbody tr").find('td').each(function() {
		var elInd = $(this).index();
		$(this).attr('td-index', elInd);
	});
	function elHeight() {
		var elSizeEl = $('.name-block-el-text').size();
		$('.name-block-el-text').each(function() {
			var thisHeight = $(this).height();
			var thisIndex = $(this).index();
			$(".detail-info-le table tbody tr").eq(thisIndex).find('p').height(thisHeight);
		});
		var bodHeight = $('.detail-info-le table').height();
		$('.view').animate({height: bodHeight+22},0);
		var lemClickIndex = 0;
		$(".detail-info-le table tbody tr").find('td').mouseenter(function() {
			lemClickIndex = $(this).attr('td-index');
				$(this).css('cursor', 'pointer');
				$('td[td-index]').css('background', 'white');
				$('td[td-index='+lemClickIndex+']').css('background', '#e9f6fe');
				$(this).parents('tbody').find('td[td-index='+lemClickIndex+']').find('span').css('visibility', 'visible');
		});
		$(".detail-info-le table tbody tr").find('td').mouseleave(function() {
				var thisIndqwe = $('.changererer option:selected').index();
				$('td').css('background', 'white');
				$('td[td-index='+thisIndqwe+']').css('background', '#e9f6fe');
				$(this).css('cursor', 'default');
				$(this).parents('tbody').find('td[td-index='+lemClickIndex+']').find('span').css('visibility', 'hidden');
				
			if($(this).parents('tbody').find('td[td-index='+lemClickIndex+']').find('span').text() == 'удалить'){
				$(this).parents('tbody').find('td[td-index='+lemClickIndex+']').find('span').css('visibility', '');
			}else{
				$(this).parents('tbody').find('td[td-index='+lemClickIndex+']').find('span').css('visibility', 'hidden');
			}
		});
	}
	elHeight();
	$('.detail-info-le table').find('td').find('span').click(function() {
		/*
		if($(this).text() == 'добавить'){
			$(this).text('удалить');
		}else{
			$(this).text('добавить');
		}
		*/
	});
	
	$('.elemen-mag tbody tr').mouseenter(function() {
		$(this).css('background', '#ebebeb');
		$(this).css('cursor', 'pointer');
	});
	$('.elemen-mag tbody tr').mouseleave(function() {
		$(this).css('background', 'none');
		$(this).css('cursor', 'default');
	});
	
	//удаление полей в списке
	$(".elemen-mag").find('tr').find('td').each(function() {
		var elInd = $(this).index();
		$(this).attr('td-index', elInd);
	});
	$('.exit-block a').click(function() {
		var lemClickIndex = $(this).parents('td').attr('td-index');
		$('td[td-index='+lemClickIndex+']').animate({opacity: 0}, 500, function() {
			$(this).remove();
		});
		return false;
	});
	
	//удаление полей в корзине
	$(".basket-table").find('tr').each(function() {
		var elIndBsc = $(this).index();
		$(this).attr('tr-index', elIndBsc);
	});
	$('.basket a').click(function() {
		var lemClickIndexBasket = $(this).parents('tbody tr').attr('tr-index');
		$('tbody tr[tr-index='+lemClickIndexBasket+']').animate({opacity: 0}, 500, function() {
			$(this).remove();
		});
		return false;
	});
	
	$('.mini-imgi a').click(function() {
		var srcBig = $('.bg-bg-bg img').attr('src');
		var curImg = $(this).attr('href');
		var curImgCur =  $(this).find('img').attr('src');
		if(srcBig != curImgCur){
			$(this).find('img').attr('src', srcBig);
			$(this).attr('href', srcBig);
			$('.bg-bg-bg').html(' ');
			$('.bg-bg-bg').append('<img alt="" src="'+curImg+'" width="300" height="auto" >');
		}
		return false;
	});
	
	$('.elemen-mag tbody').find('tr').mouseenter(function() {
		$('.elemen-mag tbody').find('tr').css('background', 'none');
		$(this).css('background', '#E5E5E5');
	});
	$('.elemen-mag tbody').find('tr').mouseleave(function() {
		$('.elemen-mag tbody').find('tr').css('background', 'none');
		$('.elemen-mag tbody').find('tr:odd').css('background', '#E5E5E5');
	});
	$('.elemen-mag tbody').find('tr:odd').css('background', '#E5E5E5');
	var str = $('.active-filter-proiz').text();
	
	var contHe = $('.footer').height();
	var docHe = $('.container').height();
	
//	var ras = parseInt(docHe)-parseInt(contHe)-parseInt(594);
//	$('.cont-bg').css('top', ras);
	
	$('.slider-line').mousedown(function() {
		$('.slider-line-panel').stop().animate({height: 0}, 400);
		$('.slider-line').animate({height: 33}, 400);
		$(this).stop().animate({height: 0}, 400);
		$(this).parent().find('.slider-line-panel').stop().animate({height: 156}, 400);
	});
	$('.slider-line:first').trigger('mousedown');
	
	$('.menu-left-block').each(function() {
		$(this).find('a:last').css('border', 'none');;
	});
	
	var animateBanner = false;
	var slbl =  $('.slider-block').height();
	var slblInd =  $('.slider-block').size()-1;
	var blockIndx = 0;
	$('.top-slider').height((slblInd+1)*slbl);
	
	$('.top-slider-le-ypr-le').click(function() {
		if(animateBanner == false){
			blockIndx --;
		}
		animateBanner = true;
		anim();
		return false;
	});
	$('.top-slider-le-ypr-ri').click(function() {
		
		if(animateBanner == false){
			blockIndx ++;
		}
		animateBanner = true;
		anim();
		return false;
	});
	
	function anim() {
		if(animateBanner){
			var rastTop = (parseInt(blockIndx)*parseInt(slbl))*(-1);
			$('.top-slider').stop().animate({top: rastTop}, 500, function() {
				animateBanner = false;
			});
	//		console.log(slblInd, blockIndx);
			yprContrl();
		}
	}
	function yprContrl() {
		if(blockIndx == 0){
			$('.top-slider-le-ypr-le').fadeOut(); 
			$('.top-slider-le-ypr-ri').fadeIn();
		}
		if(blockIndx >= slblInd){
			$('.top-slider-le-ypr-ri').fadeOut(); 
			$('.top-slider-le-ypr-le').fadeIn();
		}
		if(blockIndx < slblInd && blockIndx != 0){
			$('.top-slider-le-ypr-le').fadeIn(); 
			$('.top-slider-le-ypr-ri').fadeIn();
		}
	}
	
	var animDot = false;
	var dotBlock = $('.block-ri-slider-panel').width();
	var dotBlockSize = $('.block-ri-slider-panel').size();
	var dotEl = '<a href="#"></a>';
	var dotIndex = 0;
	initDotSlider();
	function initDotSlider() {
		$('.block-ri-slider').width(dotBlock*dotBlockSize);
		dotCreate();
		ypravlenieDotSlider();
	}
	function ypravlenieDotSlider() {
		$('.block-ri-dot a').click(function() {
			dotIndex = $(this).index();
			animateDotSlider();
			$('.block-ri-dot a').removeClass('dot-active');
			$(this).addClass('dot-active');
			return false;
		});
	}
	function animateDotSlider() {
		var animPar = dotIndex*dotBlock;
		$('.block-ri-slider').animate({left: (animPar)*(-1)}, 500);
	}
	function dotCreate() {
		$('.block-ri-dot').html('');
		for(i=1;i<=dotBlockSize;i++){
			$('.block-ri-dot').append(dotEl);
		}
		var dotSize = $('.block-ri-dot a').size();
		var dotWidth = $('.block-ri-dot a:first').width(); 
		$('.block-ri-dot').width(dotSize*(parseInt(dotWidth)+parseInt(5)));
		$('.block-ri-dot a').removeClass('dot-active');
		$('.block-ri-dot a:first').addClass('dot-active');
	}
	$('.pane').find('td[td-index]').css('background', 'white');
	$('.pane').find('td[td-index=0]').css('background', '#e9f6fe');
});
