(function($) {
	
	$(document).ready(function() {
		var counterWheel = 0;
		var counterWheel2 = 0;
		$('#rightMenu>li').addClass('li');
		$('#rightMenu>li>a').addClass('liA');
		
		$('#sendQuestionForm').live('click',function() {
			sendForm("questionForm");
		})
			
		$('#questionForm').submit(function() {
			sendForm("questionForm");
		})
		
		$('#closeButton').live('click',function() {
			$('#diskPopup').fadeOut();
			$('#contactsPopup').fadeOut();
		})
		
		$('.sortDiametr').bind('click',function(e) {
			$('#shadow').show();
			$('#loader').show();
			e.preventDefault();
			$('#catalogDisks li').removeClass('activeLink');
			$(this).parent().addClass('activeLink');
			var url = $(this).attr('href');
			$.ajax({
				url:url,
				type:'POST',
				success:function(response) {
					$('#shadow').hide();
					$('#loader').hide();
					$('#contentText').html(response);
				}
			})
		})
		
		$('#contactsLink').bind('click',function() {
			$('#contactsPopup').fadeIn();
		})
		
		$('#catalogAccesorize a').live('click',function(e) {
			$('#shadow').show();
			$('#loader').show();
			e.preventDefault();
			var url = $(this).attr('href');
			$('#catalogAccesorize li').removeClass('activeLink');
			$(this).parent().addClass('activeLink');
			$.ajax({
				url:url,
				type:'POST',
				success:function(response) {
					$('#shadow').hide();
					$('#loader').hide();
					$('#contentText').html(response);
				}
			})
		})
		
		$('#pages .ajaxPageLink').live('click',function(e){
			e.preventDefault();
			$('#shadow').show();
			$('#loader').show();
			var url = $(this).attr('href');
			var object = $(this);
			$.ajax({
				url:url,
				type:'GET',
				success:function(response) {
					$('#shadow').hide();
					$('#loader').hide();
					$('#contentText').html(response);
				}
			})
		})
		
		$('a[rel~="external"]').live('click',function() {
		   var href = $(this).attr('href');
           window.open(href);
		   return false;
		})
		
		$('.showDisk').live('click',function() {
			var title = $(this).attr('title');
			if($(this).hasClass('diametr') == true && $(this).hasClass('titleLink') == true) {
				var params = $(this).attr('class');
				params = params.substr(34);
			} else if($(this).hasClass('diametr') == true && $(this).hasClass('titleLink') == false) {
				var params = $(this).attr('class');
				params = params.substr(24);
			} else 	
				var params = false;
			showDisk(title,params);
			return false;
		})
		
		$('.showAccessories').live('click',function() {
			var title = $(this).attr('title');
			showAccessories(title);
			return false;
		})
		
		if(parseInt($('#textInfo').height()) > 300) {
			$('#textInfo').before('<div id="sliderText">&nbsp;</div>');
			var heightScroll = 300;
			var coeffScroll =  ($('#textInfo').height()-heightScroll)/heightScroll;
			$('#sliderText').slider({
				orientation: 'vertical',
				animate:false,
				change:function(event,ui) {
					$(this).hide();
					var offset = parseInt(((100-ui.value)*heightScroll/100)*coeffScroll);
					counterWheel2 = parseInt(offset/70);
					$('#textInfo').stop().animate({
						top:'-'+offset+'px'
					},{
						queue:false,
						duration:700
					});
					$(this).show();
				}
			});
			$('.ui-slider-handle').css('bottom','300px');
			var heightText = parseInt($('#textInfo').height()-heightScroll);
			var maxCounter2 = Math.ceil(heightText/70);
			$('#textInfo').bind('wheel',function(event,delta) {
				if(!$.browser.opera) {
					if(counterWheel2 >= maxCounter2 && delta < 0)
						return false;
					if(counterWheel2 <= 0 && delta > 0)
						return false;
					counterWheel2 = (delta<0)?counterWheel2+1:counterWheel2-1;	
				} else {
					if(counterWheel2 >= maxCounter2 && delta > 0)
						return false;
					if(counterWheel2 <= 0 && delta < 0)
						return false;
					counterWheel2 = (delta<0)?counterWheel2-1:counterWheel2+1;
				}
				scrollMe('textInfo',300,counterWheel2);
				event.stopPropagation();
				event.preventDefault();
			}); 
		}
		
		if(parseInt($('#text').height()) > 200) {
			$('#text').before('<span id="sliderMenu">&nbsp;</span>');
			var heightScrollMenu = 175;
			var coeffScrollMenu =  ($('#text').height()-heightScrollMenu)/heightScrollMenu;
			if($('#text .activeMenuLink').length > 0) {
				var activeOffset = $('#text .activeMenuLink').position();
				var activeOffset = activeOffset.top-40;
				$('#text').stop().animate({
					top:'-'+activeOffset+'px'
				},{
					queue:false,
					duration:100
				});
				var beginValue = 100-parseInt(activeOffset/$('#text').height()*100);
				counterWheel = Math.ceil(activeOffset/70);
			} else {
				var beginValue = 100;
				counterWheel = 0;
				$('.ui-slider-handle').css('bottom','175px');
			}
			$('#sliderMenu').slider({
				orientation: 'vertical',
				value:beginValue,
				animate:false,
				change:function(event,ui) {
					$(this).hide();
					var offset = parseInt(((100-ui.value)*heightScrollMenu/100)*coeffScrollMenu);
					counterWheel = parseInt(offset/70);
					$('#text').stop().animate({
						top:'-'+offset+'px'
					},{
						queue:false,
						duration:700
					});
					$(this).show();
				}
			});
			$('.shadow').bind('wheel',function(event,delta) {
				var heightScrollMenu = 175;
				var heightTextMenu = parseInt($('#text').height()-heightScrollMenu);
				var maxCounter = Math.ceil(heightTextMenu/70);
				if(!$.browser.opera) {
					if(counterWheel >= maxCounter && delta < 0)
						return false;
					if(counterWheel <= 0 && delta > 0)
						return false;
					counterWheel = (delta<0)?counterWheel+1:counterWheel-1;	
				} else {
					if(counterWheel >= maxCounter && delta > 0)
						return false;
					if(counterWheel <= 0 && delta < 0)
						return false;
					counterWheel = (delta<0)?counterWheel-1:counterWheel+1;
				}
				scrollMe('text',175,counterWheel);
				event.stopPropagation();
				event.preventDefault();
			});
		}
		
		$('#nextModel,#prevModel,#diskParams').live('click',function(e) {
			e.preventDefault();
			var url = $(this).attr('href');
			url = url.substr(1);
			$('#shadow').show();
			$('#loader').show();
			$('#diskPopup').remove();
			$.ajax({
				url:url,
				type:'GET',
				success:function(response) {
					$('#catalogList').before('<div id="diskPopup">'+response+'</div>');
					$('#shadow').hide();
					$('#loader').hide();
					$('#diskPopup').fadeIn();
				}
			})
			return false;
		})
		
		
		$('#searchButton').live('click',function() {
			return alert('Сервис пока не доступен');
		})
		
		$('.showBig').live('click',function() {
			var model = $(this).attr('alt');
			$('#shadow').show();
			$('#loader').show();
			$('#diskPopup').remove();
			$.ajax({
				url:'/catalog/getImage/'+model,
				type:'GET',
				success:function(response) {
					$('#catalogList').before('<div id="diskPopup">'+response+'</div>');
					$('#shadow').hide();
					$('#loader').hide();
					$('#diskPopup').fadeIn();
				}
			})
			return false;
		})
		
		$('#selectDisks').live('click',function() {
			return alert('сервис недоступен');
		})

	})
	
	scrollMe = function(blockID,heightScroll,counterWheel) {
		// 70 - примерно нормальное разбиение текста, пока const
		// 35 - отступ скролла
		var margin = parseInt(70*counterWheel);
		var heightText = parseInt($('#'+blockID).height()-heightScroll);
		var marginScroll = parseInt((heightScroll*70/heightText)*counterWheel);
		if(marginScroll > heightScroll)
			marginScroll = heightScroll;
		else if(marginScroll == 0) 
			marginScroll = 0;
		var speed = parseInt(5*(heightText-heightScroll));
		$('#'+blockID).stop().animate({
			top:'-'+margin+'px'
		},{
			queue:false,
			duration:speed
		});
		$('#'+blockID).prev().find('a').stop().animate({
			bottom:(heightScroll-marginScroll)+'px'
		},{
			queue:false,
			duration:700
		});
	}
	
	sendForm = function(name) {
		var error = 0;
		var regMail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var regPhone = /^([0-9]{6,12})$/;
		var action  = $('#'+name).attr('action');
		var type 	= $('#'+name).attr('method');
		var offset 	= $('#'+name).offset();
		var top = offset.top - 50;
 		$('#'+name+' .required').each(function() {
			if($(this).val() == '' || $(this).val() == 'Имя' ||  $(this).val() == 'Ваш вопрос' || $(this).val() == 'Код' || $(this).val() == 'Контактный телефон') {
				$(this).addClass('notValid');
				error++;
			} else if($(this).attr('name') == 'email' && !regMail.test($(this).val())) {
				$(this).addClass('notValid');
				error++;
			} else if($(this).attr('name') == 'phone' && !regPhone.test($(this).val())) {
				$(this).addClass('notValid');
				error++;
			}
			else 
				$(this).removeClass('notValid');
		});
		
		if(error !== 0) {
			$('#'+name+' .info').addClass('error').html('Проверьте введеные данные');
		} else {
			$('#'+name+' .info').html(' ');
			var data = $('#'+name).serialize();
			$.ajax({
				url: action,
				type: type,
				data: data,
				success: function(response) {
					$('#'+name+' .info').html(response);
					if(response == '<span class="ok">Ваше письмо успешно отправлено</span>') {
						$('#'+name+' input[name="fio"]').attr('value','Имя');
						$('#'+name+' input[name="email"]').attr('value','E-mail');
						$('#'+name+' input[name="captcha"]').attr('value','Код');
						$('#'+name+' textarea[name="question"]').html('Ваш вопрос');
					}
				}
			})
		}
	}
	
	showDisk = function(name,params) {
		$('#shadow').show();
		$('#loader').show();
		$('#diskPopup').remove();
		var url = (params === false)?'/catalog/getOne/'+name+'/disks/':'/catalog/getOne/'+name+'/disks/'+params+'/';
		$.ajax({
			url:url,
			type:'GET',
			success:function(response) {
				$('#catalogList').before('<div id="diskPopup">'+response+'</div>');
				setTimeout(function() {
					if($('#contentDisk').height() > 380) {
						$('#contentDisk').before('<div id="sliderPopup">&nbsp;</div>');
						var heightScroll = 300;
						var coeffScroll =  ($('#contentDisk').height()-heightScroll)/300;
						$('#sliderPopup').slider({
							orientation: 'vertical',
							change:function(event,ui) {
								var offset = parseInt(((100-ui.value)*heightScroll/100)*coeffScroll);
								counterWheel2 = parseInt(offset/70);
								$('#contentDisk').stop().animate({
									top:'-'+offset+'px'
								},{
									queue:false,
									duration:700
								});
							}
						});
						$('.ui-slider-handle').removeAttr('style');
						var counterWheel = 0;
						$('#contentDiskWrapper').bind('wheel',function(event,delta) {
							var heightScrollMenu = 300;
							var heightTextMenu = parseInt($('#contentDisk').height()-heightScrollMenu);
							var maxCounter = Math.ceil(heightTextMenu/70);
							if(!$.browser.opera) {
								if(counterWheel >= maxCounter && delta < 0)
									return false;
								if(counterWheel <= 0 && delta > 0)
									return false;
								counterWheel = (delta<0)?counterWheel+1:counterWheel-1;	
							} else {
								if(counterWheel >= maxCounter && delta > 0)
									return false;
								if(counterWheel <= 0 && delta < 0)
									return false;
								counterWheel = (delta<0)?counterWheel-1:counterWheel+1;
							}
							scrollMe('contentDisk',300,counterWheel);
							event.stopPropagation();
							event.preventDefault();
						});
					}
				},500);
				$('#shadow').hide();
				$('#loader').hide();
				$('#diskPopup').fadeIn();
			}
		})
		return false;
	}
	
	showAccessories = function(name) {
		$('#shadow').show();
		$('#loader').show();
		$('#diskPopup').remove();
		$.ajax({
			url:'/catalog/getOne/'+name+'/accessories/',
			type:'GET',
			success:function(response) {
				$('#catalogList').before('<div id="diskPopup">'+response+'</div>');
				setTimeout(function() {
					if($('#contentDisk').height() > 380) {
						$('#contentDisk').before('<div id="sliderPopup">&nbsp;</div>');
						var heightScroll = 300;
						var coeffScroll =  ($('#contentDisk').height()-heightScroll)/300;
						$('#sliderPopup').slider({
							orientation: 'vertical',
							change:function(event,ui) {
								var offset = parseInt(((100-ui.value)*heightScroll/100)*coeffScroll);
								counterWheel2 = parseInt(offset/70);
								$('#contentDisk').stop().animate({
									top:'-'+offset+'px'
								},{
									queue:false,
									duration:700
								});
							}
						});
						$('.ui-slider-handle').removeAttr('style');
						var counterWheel = 0;
						$('#contentDiskWrapper').bind('wheel',function(event,delta) {
							var heightScrollMenu = 300;
							var heightTextMenu = parseInt($('#contentDisk').height()-heightScrollMenu);
							var maxCounter = Math.ceil(heightTextMenu/70);
							if(!$.browser.opera) {
								if(counterWheel >= maxCounter && delta < 0)
									return false;
								if(counterWheel <= 0 && delta > 0)
									return false;
								counterWheel = (delta<0)?counterWheel+1:counterWheel-1;	
							} else {
								if(counterWheel >= maxCounter && delta > 0)
									return false;
								if(counterWheel <= 0 && delta < 0)
									return false;
								counterWheel = (delta<0)?counterWheel-1:counterWheel+1;
							}
							scrollMe('contentDisk',300,counterWheel);
							event.stopPropagation();
							event.preventDefault();
						});
					}
				},500);
				$('#shadow').hide();
				$('#loader').hide();
				$('#diskPopup').fadeIn();
			}
		})
		return false;
	}
	
	
})(jQuery);
